@atoms-tech/atoms-mcp 0.15.2 → 0.15.4
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/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import e,{readFile as t,mkdir as i,writeFile as r,unlink as n}from"fs/promises";import{homedir as a}from"os";import s,{join as o}from"path";import{createClient as d}from"@supabase/supabase-js";import{createServer as c}from"http";import l,{randomUUID as m,randomBytes as p,createHash as _}from"crypto";import{fileURLToPath as u,URL as f}from"url";import{z as h}from"zod";import{registerAppTool as g,registerAppResource as y,RESOURCE_MIME_TYPE as w}from"@modelcontextprotocol/ext-apps/server";import{McpServer as b}from"@modelcontextprotocol/sdk/server/mcp.js";import{createRequire as v}from"module";import{StdioServerTransport as j}from"@modelcontextprotocol/sdk/server/stdio.js";var S,x,k,I,E,A,O,H=Object.defineProperty,D=Object.getOwnPropertyNames,C=(e,t,i)=>function(){if(i)throw i[0];try{return e&&(t=(0,e[D(e)[0]])(e=0)),t}catch(e){throw i=[e],e}},R=(e,t)=>{for(var i in t)H(e,i,{get:t[i],enumerable:!0})};function U(e){return O.get(e)}var q=C({"src/core/tool-catalog.ts"(){S=new Set(["atoms_status","atoms_list_projects"]),x=new Set(["atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_link_items","atoms_bulk_import","atoms_record_test_result","atoms_record_test_results","atoms_create_variable","atoms_update_variable","atoms_delete_variable","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_create_level","atoms_create_field","atoms_create_baseline","atoms_lock_baseline","atoms_restore_baseline","atoms_create_analysis","atoms_fill_row","atoms_link_mitigation"]),k=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_restore_baseline"]),I=new Set(["atoms_bulk_import"]),E={items:["atoms_list_items","atoms_get_item","atoms_search","atoms_semantic_search","atoms_browse","atoms_get_history","atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_bulk_import"],traceability:["atoms_trace","atoms_link_items","atoms_export_mermaid","atoms_impact_analysis"],coverage:["atoms_get_coverage","atoms_record_test_result","atoms_record_test_results","atoms_project_summary","atoms_list_assets"],variables:["atoms_list_variables","atoms_get_variable","atoms_create_variable","atoms_update_variable","atoms_delete_variable"],domains:["atoms_list_domains","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_list_levels","atoms_create_level","atoms_list_fields","atoms_create_field"],baselines:["atoms_list_baselines","atoms_create_baseline","atoms_lock_baseline","atoms_diff_baselines","atoms_restore_baseline"],analysis:["atoms_create_analysis","atoms_fill_row","atoms_get_analysis","atoms_link_mitigation","atoms_get_gaps"]},A=Object.keys(E),O=new Map;for(const[e,t]of Object.entries(E))for(const i of t)O.set(i,e)}});function M(e,t){if(S.has(t))return{allowed:!0};if(e.lockdown&&!new Set(["atoms_list_items","atoms_get_item","atoms_search","atoms_browse"]).has(t))return{allowed:!1,reason:"lockdown"};if(e.forbidden_tools.includes(t))return{allowed:!1,reason:"forbidden_tool"};if(e.read_only&&x.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&k.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&I.has(t))return{allowed:!1,reason:"block_bulk_import"};const i=U(t);return void 0===i||e.allowed_toolsets.includes(i)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function T(e,t){return M(e,t).allowed}function $(e){switch(e){case"lockdown":return"MCP is in lockdown mode for your role — only read-only browse is available.";case"read_only":return"Your org policy puts MCP in read-only mode. Mutating tools are not exposed.";case"block_destructive":return"Your org policy blocks destructive operations (delete tools).";case"block_bulk_import":return"Your org policy blocks bulk import.";case"forbidden_tool":return"This tool is on your org's forbidden list.";case"toolset_disabled":return"This tool's toolset is not enabled in your org policy."}}var P,N,L,F,W=C({"src/core/policy.ts"(){q()}}),V=C({"src/core/types.ts"(){P={read_only:!1,lockdown:!1,block_destructive:!1,block_bulk_import:!1,cross_project_browse:!0,allowed_toolsets:["items","traceability","coverage","variables","domains","baselines"],forbidden_tools:[],project_scope:null,require_confirmation_for:[]},N={read_only:!0,lockdown:!0,block_destructive:!0,block_bulk_import:!0,cross_project_browse:!1,allowed_toolsets:[],forbidden_tools:[],project_scope:[],require_confirmation_for:[]}}});function B(){return L}var z=C({"src/middleware/session-policy.ts"(){V(),L=P,F=null}});function J(){const e=process.env.ATOMS_MCP_TOOLSETS?.trim();if(!e)return null;const t=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===t.length)return null;const i=new Set,r=[];for(const e of t)A.includes(e)?i.add(e):r.push(e);return{allowed:i,unknown:r}}function Q(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function G(e){if(Q()&&x.has(e))return!1;if(S.has(e))return!0;const t=J();if(null===t)return T(B(),e);const i=U(e);return!!i&&!!t.allowed.has(i)&&T(B(),e)}var Y,K,Z=C({"src/middleware/tool-registry.ts"(){q(),W(),z()}}),X={};async function ee(){try{const e=await t(K,"utf-8"),i=JSON.parse(e);return i.access_token&&i.refresh_token?i:null}catch{return null}}async function te(e){await i(Y,{recursive:!0,mode:448}),await r(K,JSON.stringify(e,null,2),{mode:384})}async function ie(){const e=await ee();return!!e&&e.expires_at>Date.now()+6e4}function re(e){return e.expires_at>Date.now()+6e4}async function ne(){try{await n(K)}catch{}}function ae(){return K}R(X,{clearCredentials:()=>ne,getCredentialsPath:()=>ae,hasValidCredentials:()=>ie,isTokenValid:()=>re,readCredentials:()=>ee,writeCredentials:()=>te});var se,oe,de,ce=C({"src/auth/token-store.ts"(){Y=o(a(),".atoms"),K=o(Y,"credentials.json")}}),le={};function me(e){return e.trim().replace(/\/+$/,"")}R(le,{ATOMS_APP_URL:()=>de,ATOMS_SUPABASE_ANON_KEY:()=>oe,ATOMS_SUPABASE_URL:()=>se,resolveUrl:()=>me});var pe=C({"src/config.ts"(){se=me(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),oe=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",de=process.env.ATOMS_APP_URL??"https://atoms.tech"}}),_e={};async function ue(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=fe(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await ee();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' to connect your ATOMS account.");if(t.expires_at>Date.now()+6e4){const e=fe(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}process.stderr.write("[atoms-mcp] Refreshing access token...\n");const i=d(se,oe),{data:r,error:n}=await i.auth.refreshSession({refresh_token:t.refresh_token});if(n||!r.session)throw new Error(`Token refresh failed: ${n?.message??"No session returned"}. Re-run 'npx @atoms-tech/atoms-mcp login'.`);const a=r.session;return await te({access_token:a.access_token,refresh_token:a.refresh_token,expires_at:Date.now()+1e3*(a.expires_in??3600),user_email:a.user?.email}),{access_token:a.access_token,refresh_token:a.refresh_token,user_id:a.user?.id??"",email:a.user?.email??""}}function fe(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const i=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),r=JSON.parse(Buffer.from(i,"base64").toString("utf-8"));if(!r.sub)throw new Error("JWT missing 'sub' claim");return r}R(_e,{getValidToken:()=>ue});var he,ge,ye,we,be,ve=C({"src/auth/refresh.ts"(){ce(),pe()}}),je={};async function Se(){if(he)try{const e=await ee();e&&e.expires_at>be&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),xe())}catch{}if(he&&we>Date.now()+6e4)return he;he&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:i}=await ue(),r=e.split(".");if(3===r.length)try{const e=JSON.parse(Buffer.from(r[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());we=1e3*(e.exp??0)}catch{we=Date.now()+36e5}try{const e=await ee();be=e?.expires_at??0}catch{be=0}const n=d(se,oe,{global:{headers:{Authorization:`Bearer ${e}`}}});return ge=t,ye=i,he=n}function xe(){he=null,ge=null,ye=null,we=0,be=0}function ke(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const i=e;t="string"==typeof i.message?i.message:"string"==typeof i.code?i.code:String(e)}else null!=e&&(t=String(e));return/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)}async function Ie(e){try{return await e()}catch(t){if(!ke(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),xe(),await e()}}function Ee(){if(!ge)throw new Error("Not authenticated. Call getClient() first.");return ge}function Ae(){return ye??""}async function Oe(e,t){const i=Ee(),{data:r,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n||!r)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",i).eq("org_id",r.org_id).maybeSingle();if(s||!a){const{data:t}=await e.rpc("is_platform_admin");if(!0===t)return"admin";throw new Error("Not a member of this project's organization")}if("viewer"===a.role)throw new Error("VIEWER_ROLE");return a.role}R(je,{getClient:()=>Se,getUserEmail:()=>Ae,getUserId:()=>Ee,invalidateClient:()=>xe,isJwtExpiredError:()=>ke,requireWriteAccess:()=>Oe,withJwtRetry:()=>Ie});var He,De,Ce=C({"src/db/client.ts"(){ve(),ce(),pe(),he=null,ge=null,ye=null,we=0,be=0}}),Re={};async function Ue(){const e=p(32).toString("base64url"),t=_("sha256").update(e).digest("base64url"),i=`http://localhost:${He}${De}`,r=new f(`${de}/auth/mcp-consent`);return r.searchParams.set("redirect_uri",i),r.searchParams.set("code_challenge",t),r.searchParams.set("code_challenge_method","S256"),new Promise((t,i)=>{let n;function a(){clearTimeout(n)}const s=c(async(r,n)=>{const o=new f(r.url??"/",`http://localhost:${He}`);if(o.pathname!==De)return n.writeHead(404),void n.end("Not found");try{if("access_denied"===o.searchParams.get("error"))return n.writeHead(200,{"Content-Type":"text/html"}),n.end(Me("Authorization was cancelled.")),a(),s.close(),void i(new Error("Authorization cancelled by user."));const r=o.searchParams.get("code");if(r){const o=await fetch(`${se}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:oe},body:JSON.stringify({auth_code:r,code_verifier:e})}),d=await o.json();if(!o.ok||!d.access_token){const e=d.error_description??d.msg??"Unknown error";return n.writeHead(200,{"Content-Type":"text/html"}),n.end(Me(`Code exchange failed: ${e}`)),a(),s.close(),void i(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(d.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(se,oe,{global:{headers:{Authorization:`Bearer ${d.access_token}`}}}),{data:p,error:_}=await m.from("org_members").select("org_id").limit(1);return _||!p||0===p.length?(n.writeHead(200,{"Content-Type":"text/html"}),n.end(Me('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://atoms.tech">atoms.tech</a> first, then run this login command again.')),a(),s.close(),void i(new Error("No ATOMS account found. Sign up at atoms.tech first."))):(await te({access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Date.now()+1e3*(d.expires_in??3600),user_email:c}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(qe(c)),a(),s.close(),void t({email:c}))}const d=o.searchParams.get("access_token"),c=o.searchParams.get("refresh_token"),l=parseInt(o.searchParams.get("expires_in")??"3600",10);d&&c?(await te({access_token:d,refresh_token:c,expires_at:Date.now()+1e3*l}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(qe("authenticated")),a(),s.close(),t({email:"authenticated"})):(n.writeHead(200,{"Content-Type":"text/html"}),n.end("<!DOCTYPE html>\n<html>\n<head><title>ATOMS MCP Login</title></head>\n<body>\n <h1>Completing login...</h1>\n <script>\n const hash = window.location.hash.substring(1);\n const params = new URLSearchParams(hash);\n const data = {\n access_token: params.get('access_token'),\n refresh_token: params.get('refresh_token'),\n expires_in: params.get('expires_in'),\n user_email: ''\n };\n if (data.access_token) {\n // Decode JWT to get email\n try {\n const payload = JSON.parse(atob(data.access_token.split('.')[1]));\n data.user_email = payload.email || '';\n } catch(e) {}\n fetch('/token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data)\n }).then(() => {\n document.body.innerHTML = '<h1>Login successful! You can close this tab.</h1>';\n }).catch(() => {\n document.body.innerHTML = '<h1>Login failed. Please try again.</h1>';\n });\n } else {\n document.body.innerHTML = '<h1>Login failed — no tokens received.</h1>';\n }\n <\/script>\n</body>\n</html>"))}catch(e){n.writeHead(500),n.end("Authentication failed"),a(),s.close(),i(e)}});s.on("request",async(e,r)=>{if("POST"===e.method&&"/token"===e.url){let n="";e.on("data",e=>{n+=e.toString()}),e.on("end",async()=>{try{const e=JSON.parse(n);await te({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0})),a(),s.close(),t({email:e.user_email??"authenticated"})}catch(e){r.writeHead(500),r.end("Failed to store credentials"),a(),s.close(),i(e)}})}}),s.listen(He,"127.0.0.1",async()=>{process.stderr.write("\nOpening browser for ATOMS login...\n"),process.stderr.write(`If the browser doesn't open, visit:\n${r.toString()}\n\n`);try{const{default:e}=await import("open");await e(r.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),n=setTimeout(()=>{s.close(),i(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function qe(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Authorized</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #052e16;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 {\n font-size: 22px;\n font-weight: 600;\n margin-bottom: 8px;\n color: #22c55e;\n }\n .email {\n font-size: 14px;\n color: #a3a3a3;\n margin-bottom: 32px;\n }\n .permissions {\n text-align: left;\n background: #0a0a0a;\n border: 1px solid #262626;\n border-radius: 12px;\n padding: 20px;\n margin-bottom: 24px;\n }\n .permissions h3 {\n font-size: 12px;\n font-weight: 600;\n color: #737373;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n margin-bottom: 12px;\n }\n .perm-item {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 6px 0;\n font-size: 14px;\n color: #d4d4d4;\n }\n .perm-item .dot {\n width: 6px;\n height: 6px;\n background: #22c55e;\n border-radius: 50%;\n flex-shrink: 0;\n }\n .closing {\n font-size: 13px;\n color: #525252;\n }\n .closing span { color: #a3a3a3; font-variant-numeric: tabular-nums; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#22c55e" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1>Authorization Granted</h1>\n <p class="email">${e}</p>\n\n <div class="permissions">\n <h3>ATOMS MCP can now</h3>\n <div class="perm-item"><span class="dot"></span> Read your projects and requirements</div>\n <div class="perm-item"><span class="dot"></span> Create and edit requirements and test cases</div>\n <div class="perm-item"><span class="dot"></span> Record test results (pass/fail)</div>\n <div class="perm-item"><span class="dot"></span> Manage traceability relationships</div>\n <div class="perm-item"><span class="dot"></span> Export coverage reports and diagrams</div>\n </div>\n\n <p class="closing">This tab will close in <span id="countdown">5</span>s</p>\n </div>\n\n <script>\n let seconds = 5;\n const el = document.getElementById('countdown');\n const timer = setInterval(() => {\n seconds--;\n el.textContent = seconds;\n if (seconds <= 0) {\n clearInterval(timer);\n window.close();\n // If window.close() is blocked (not opened by script), update message\n setTimeout(() => {\n document.querySelector('.closing').textContent = 'You can close this tab now.';\n }, 500);\n }\n }, 1000);\n <\/script>\n</body>\n</html>`}function Me(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Failed</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #450a0a;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 { font-size: 22px; font-weight: 600; margin-bottom: 16px; color: #ef4444; }\n .reason { font-size: 14px; color: #a3a3a3; line-height: 1.6; }\n .reason a { color: #7c3aed; text-decoration: underline; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#ef4444" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1>Authorization Failed</h1>\n <p class="reason">${e}</p>\n </div>\n</body>\n</html>`}R(Re,{login:()=>Ue});var Te,$e,Pe,Ne,Le=C({"src/auth/login.ts"(){ce(),pe(),He=19275,De="/callback"}});function Fe(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Pe)if(t.test(e.trim()))return"[redacted]";return e.length>Ne?e.slice(0,Ne)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Fe(e,t+1));if(null!==e&&"object"==typeof e){const i={};for(const[r,n]of Object.entries(e)){const e=r.toLowerCase();Te.has(e)?i[r]="[redacted]":$e.has(e)?i[r]="string"==typeof n?"[content]":Fe(n,t+1):i[r]=Fe(n,t+1)}return i}return e}function We(e){return Fe(e)}var Ve,Be,ze,Je,Qe,Ge=C({"src/middleware/audit.ts"(){Te=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),$e=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Pe=[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,/^bearer\s+\S+$/i,/^(sk|pk|npm|gh|glpat|xoxb|xoxp|rk|SG\.)[-_][A-Za-z0-9_-]{16,}/,/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/],Ne=200}}),Ye=C({"src/middleware/rate-limiter.ts"(){Ve=60,Be=6e4}});function Ke(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?ze.test(e)?e:(Je||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),Je=!0),null):null}var Ze,Xe=C({"src/middleware/project-scope.ts"(){ze=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Je=!1,Qe=class extends Error{expectedProjectId;receivedProjectId;constructor(e,t){super("Tool call rejected: project_id is outside the configured ATOMS_MCP_PROJECT_ID scope."),this.name="ProjectScopeError",this.expectedProjectId=e,this.receivedProjectId=t}}}});function et(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?Ze:t:Ze}var tt,it,rt,nt,at,st,ot=C({"src/core/client-identity.ts"(){Ze="claude_desktop"}}),dt=C({"src/core/timestamps.ts"(){tt=h.string().datetime({offset:!0})}}),ct=C({"src/core/errors.ts"(){}}),lt={};function mt(e,t=rt){if("string"!=typeof e)return"";const i=e.replace(at,"").replace(st,"");return i.length<=t?i:i.slice(0,t)+"..."}function pt(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function _t(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function ut(e,t,i){return{total_count:e,limit:t,offset:i,has_more:i+t<e}}function ft(e,t){return{status:"error",message:e,next_steps:t}}function ht(e,t){return ft(`${e} '${mt(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function gt(e){return ft(`${e} role cannot modify project data`,["Contact your org admin to upgrade your role to editor","Use read-only tools (atoms_list_items, atoms_get_item, atoms_search) instead"])}function yt(e){return ft(`Validation error: ${mt(e,nt)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function wt(){return ft("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' first.",["Run: npx @atoms-tech/atoms-mcp login","Or set ATOMS_ACCESS_TOKEN environment variable"])}function bt(){return ft("Your ATOMS session token expired and could not be refreshed automatically.",["Call atoms_status() — it will refresh the token if possible","If that still reports 'expired', restart Claude Desktop (quit and reopen)","If the problem persists, run: npx @atoms-tech/atoms-mcp logout && npx @atoms-tech/atoms-mcp login"])}function vt(e){return ft("Tool call rejected: project_id is outside the configured ATOMS_MCP_PROJECT_ID scope.",[`This MCP session is bound to project ${e}`,"Pass that project_id, or restart without ATOMS_MCP_PROJECT_ID to access other projects"])}function jt(e){return ft("Rate limited: too many requests to ATOMS API.",[e?`Wait ${e} seconds before retrying.`:"Wait a few seconds before retrying.","Reduce the frequency of back-to-back tool calls"])}function St(e){return ft(`Parse error: ${mt(e,nt)}`,["Check that body/title/summary fields contain valid text (no unexpected control characters)","If the content was generated programmatically, validate the string before passing it","Simplify the content and retry — if it succeeds, the original content has a malformed character"])}function xt(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function kt(){return ft("Stale write rejected: this item changed after it was read.",["Call atoms_get_item again and use the returned metadata.updated_at value","Review the current item before retrying so you do not overwrite newer work","Retry atoms_update_item or atoms_link_items with the fresh expected timestamp"])}function It(e){const t=e instanceof Error?e.message:String(e);return/not authenticated/i.test(t)?wt():function(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const i=e;t="string"==typeof i.message?i.message:"string"==typeof i.code?i.code:String(e)}else null!=e&&(t=String(e));return/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)}(e)?bt():/rate.?limit|too many requests|429/i.test(t)?jt():xt(t)?kt():/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?St(t):Et(t)}function Et(e){return/row.level security|permission denied for/i.test(e)?ft("Permission denied: your account does not have write access to this project.",["Verify you have editor or admin role in this project","Contact your org admin to upgrade your permissions","Use atoms_list_projects to confirm the project_id is one you have access to"]):ft(`Database error: ${mt(e,nt)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function At(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function Ot(e){const t=JSON.stringify(e,null,2);if(t.length>it&&"success"===e.status&&Array.isArray(e.data)){const t=Math.max(1,Math.floor(e.data.length/2)),i={...e,data:e.data.slice(0,t),meta:{...e.meta,truncated:!0,truncation_message:`Response truncated from ${e.data.length} to ${t} items. Use 'offset' parameter or add filters to see more results.`}};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}}return{content:[{type:"text",text:t}],structuredContent:e}}function Ht(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}R(lt,{CHARACTER_LIMIT:()=>it,accessDeniedError:()=>gt,authError:()=>wt,classifyError:()=>It,dbError:()=>Et,errorResponse:()=>ft,formatErrorResult:()=>Ht,formatToolResult:()=>Ot,isStaleWriteErrorMessage:()=>xt,jwtExpiredError:()=>bt,notFoundError:()=>ht,paginationMeta:()=>ut,parseError:()=>St,rateLimitError:()=>jt,sanitizeForEcho:()=>mt,sanitizeTagOrLevel:()=>pt,scopeError:()=>vt,staleWriteError:()=>kt,success:()=>_t,validationError:()=>yt,wrapUserContent:()=>At});var Dt,Ct=C({"src/tools/_base.ts"(){ct(),it=25e3,rt=50,nt=200,at=new RegExp("[\\u0000-\\u001F\\u007F]","g"),st=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g")}});var Rt=C({"src/apps/register.ts"(){Dt={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function Ut(e){return function(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(`*${t=e,t.replace(/[\\%_*]/g,e=>`\\${e}`)}*`);var t}var qt=C({"src/core/postgrest.ts"(){}});async function Mt(e,t,i){let r=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0});i.type&&(r=r.eq("type",i.type)),i.domain&&(r=r.filter("data->tags->domains","cs",JSON.stringify([i.domain]))),i.level&&(r=r.filter("data->tags->>level","eq",i.level)),r=r.range(i.offset,i.offset+i.limit-1);const{data:n,error:a,count:s}=await r;if(a)throw new Error(a.message);return{items:n??[],totalCount:s??0}}async function Tt(e,t,i){const{data:r,error:n}=await e.from("items").select("*").eq("id",i).eq("project_id",t).is("deleted_at",null).maybeSingle();if(n)throw new Error(n.message);return r}async function $t(e,t){if(t.baseline_id&&t.as_of)throw new Error("baseline_id and as_of are mutually exclusive");if(t.as_of)return t.as_of;if(t.baseline_id){const{data:i,error:r}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",t.baseline_id).maybeSingle();if(r)throw new Error(`resolveSnapshotAt: ${r.message}`);if(!i||null!==i.deleted_at)throw new Error(`Baseline not found: ${t.baseline_id}`);if(i.project_id!==t.project_id)throw new Error("Baseline does not belong to this project");return i.snapshot_at}return null}async function Pt(e,t){const{data:i,error:r}=await e.from("baselines").select("id, project_id, name, description, snapshot_at, created_at, created_by, locked_at, locked_by, deleted_at").eq("id",t).maybeSingle();if(r)throw new Error(`getBaselineById: ${r.message}`);return i&&null===i.deleted_at?i:null}function Nt(e){return{id:e.id,project_id:e.project_id,type:e.type,title:e.title,data:e.data,created_by:e.changed_by,updated_by:e.changed_by,created_at:e.valid_from,updated_at:e.valid_from,deleted_at:null}}async function Lt(e,t,i){const{data:r,error:n}=await e.rpc("project_state_at",{p_project_id:t,p_snapshot_at:i});if(n)throw new Error(`projectStateAt: ${n.message}`);return r??[]}async function Ft(e,t,i,r){const n=i.trim();if(!n)return{items:[],totalCount:0};let a=null;if(r.asset&&r.asset.trim()){const{data:i,error:n}=await e.from("test_results").select("item_id").eq("project_id",t).eq("asset",r.asset.trim());if(n)throw new Error(n.message);const s=new Set;for(const e of i??[])s.add(e.item_id);if(a=Array.from(s),0===a.length)return{items:[],totalCount:0}}let s=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${Ut(n)},data->>body.ilike.${Ut(n)},data->>summary.ilike.${Ut(n)}`).limit(r.limit);r.type&&(s=s.eq("type",r.type)),a&&(s=s.in("id",a));const{data:o,error:d,count:c}=await s;if(d)throw new Error(d.message);return{items:o??[],totalCount:c??0}}function Wt(e,t){const i=new Set(e.map(e=>e.id)),r=new Set,n=[],a=(e,t,a)=>{if(e===t)return;if(!i.has(e)||!i.has(t))return;const s=`${e}|${t}|${a}`;r.has(s)||(r.add(s),n.push({from_id:e,to_id:t,type:a}))};for(const e of t)a(e.from_id,e.to_id,e.type);for(const t of e){const e=t.data?.relationships??{},i=t=>Array.isArray(e[t])?e[t].filter(e=>"string"==typeof e):[];for(const e of i("parents"))a(t.id,e,"parent");for(const e of i("children"))a(t.id,e,"child");for(const e of i("related"))a(t.id,e,"related");for(const e of i("verifies"))a(t.id,e,"verifies");for(const e of i("verified_by"))a(t.id,e,"verified_by");for(const e of i("mitigated_by"))a(t.id,e,"mitigated_by");for(const e of i("mitigates"))a(t.id,e,"mitigates")}return n}async function Vt(e,t,i){const r="requirement"===i?"REQ":"test-case"===i?"TC":"note"===i?"NOTE":"TABLE",{data:n,error:a}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(a)throw new Error(`ID generation failed: ${a.message}`);return n}var Bt=C({"src/db/queries.ts"(){qt()}}),zt={};async function Jt(){try{const e=await Ie(async()=>{const e=await Se();return await async function(e){const{data:t,error:i}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(i)throw new Error(i.message);return(t??[]).map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.organizations?.name??"Unknown",created_at:e.created_at}))}(e)}),t=Ke(),i=F,r=B().project_scope,n=r?new Set(r):null;return Ot(_t(e.filter(e=>!i||e.org_id===i).filter(e=>!t||e.id===t).filter(e=>!n||n.has(e.id)).map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.org_name,created_at:e.created_at}))))}catch(e){return Ht(It(e))}}R(zt,{listProjectsHandler:()=>Jt});var Qt=C({"src/tools/list-projects.ts"(){Ce(),Bt(),Xe(),z(),Ct()}}),Gt={};async function Yt(e){try{const t=await Se();let i,r,n=null;try{n=await $t(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ht(Et(e.message))}if(n){const a=(await Lt(t,e.project_id,n)).filter(t=>{if(e.type&&t.type!==e.type)return!1;const i=t.data??{};if(e.domain){const t=i?.tags?.domains??[];if(!Array.isArray(t)||!t.includes(e.domain))return!1}return!e.level||i?.tags?.level===e.level});r=a.length,i=a.slice(e.offset,e.offset+e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const n=await Mt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});i=n.items,r=n.totalCount}return Ot(_t(i.map(e=>({id:e.id,title:At(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ut(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Gt,{listItemsHandler:()=>Yt});var Kt=C({"src/tools/list-items.ts"(){Ce(),Bt(),Ct()}}),Zt={};async function Xt(e){try{const i=await Se();let r=null;try{r=await $t(i,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ht(ft(e.message,["Pass baseline_id OR as_of, not both"]))}const n=r?await async function(e,t,i,r){const{data:n,error:a}=await e.rpc("item_state_at",{p_item_id:i,p_project_id:t,p_snapshot_at:r});if(a)throw new Error(`itemStateAt: ${a.message}`);return(n??[])[0]??null}(i,e.project_id,e.item_id,r).then(e=>e?Nt(e):null):await Tt(i,e.project_id,e.item_id);if(!n)return Ht(ht("Item",e.item_id));const a={parents:[],children:[],related:[],verified_by:[],verifies:[],mitigated_by:[],mitigates:[]};if(r){const e=n.data?.relationships??{};for(const t of Object.keys(a)){const i=e[t];Array.isArray(i)&&(a[t]=i.slice())}}else{const t=await async function(e,t,i){const{data:r,error:n}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${i},to_id.eq.${i}`);if(n)throw new Error(n.message);return r??[]}(i,e.project_id,e.item_id),r={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",mitigated_by:"mitigated_by",mitigates:"mitigates"},s={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"},o=(e,t)=>{if(!(e in a))return;const i=a[e];i.includes(t)||i.push(t)},d=new Set([e.item_id]);for(const e of t)d.add(e.from_id),d.add(e.to_id);const c=n.data?.relationships??{};for(const e of Object.keys(a)){const t=c[e];if(Array.isArray(t))for(const e of t)"string"==typeof e&&d.add(e)}let l=new Set([e.item_id]);const m=Array.from(d);if(m.length>0){const{data:t,error:r}=await i.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",m);if(r)throw new Error(r.message);l=new Set((t??[]).map(e=>e.id)),l.add(e.item_id)}const p=e=>l.has(e);for(const i of t)if(i.from_id===e.item_id){if(!p(i.to_id))continue;o(r[i.type]??i.type,i.to_id)}else{if(!p(i.from_id))continue;o(s[i.type]??i.type,i.from_id)}for(const t of Object.keys(a)){const i=c[t];if(Array.isArray(i))for(const r of i)"string"==typeof r&&r!==e.item_id&&p(r)&&o(t,r)}}let s=[];if("test-case"===n.type)if(r)s=(n.data?.runs??[]).map(e=>({result:e.result??"not-run",run_by:e.by??e.run_by??null,run_at:e.date??e.run_at??"",note:e.note??null})).filter(e=>"string"==typeof e.run_at&&e.run_at.length>0).sort((e,t)=>t.run_at.localeCompare(e.run_at)).slice(0,20).map(e=>({result:e.result,run_by:e.run_by,run_at:e.run_at,note:e.note}));else{const{data:t,error:r}=await i.from("test_results").select("result, run_by, run_at, note").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);!r&&t&&(s=t)}return Ot(_t({id:n.id,type:n.type,title:At(n.title),summary:At(n.data?.summary),body:At(n.data?.body),tags:n.data?.tags??{domains:[]},ownership:n.data?.ownership??{primary:null,additional:[]},relationships:a,links:n.data?.links??[],fields:(t=n.data?.fields,!t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>"string"==typeof e[1]).map(([e,t])=>[e,At(t)]))),status:n.data?.status,..."test-case"===n.type?{latest_result:s[0]?.result??"not-run",test_results:s}:{},metadata:{created_at:n.created_at,created_by:n.created_by,updated_at:n.updated_at,updated_by:n.updated_by,source_id:n.data?.metadata?.source_id}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}var t}R(Zt,{getItemHandler:()=>Xt});var ei=C({"src/tools/get-item.ts"(){Ce(),Bt(),Ct()}}),ti={};async function ii(e){try{const t=await Se();let i,r,n=null;try{n=await $t(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return Ht(Et(e.message))}if(n){const a=await Lt(t,e.project_id,n),s=e.query.trim().toLowerCase(),o=0===s.length?[]:a.filter(t=>{if(e.type&&t.type!==e.type)return!1;const i=t.data??{};return[t.title,i?.body,i?.summary].filter(e=>"string"==typeof e).map(e=>e.toLowerCase()).some(e=>e.includes(s))});r=o.length,i=o.slice(0,e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const n=await Ft(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});i=n.items,r=n.totalCount}return Ot(_t(i.map(e=>({id:e.id,title:At(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ut(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(ti,{searchHandler:()=>ii});var ri=C({"src/tools/search.ts"(){Ce(),Bt(),Ct()}}),ni={};async function ai(e){try{const t=await Se(),{access_token:i}=await ue(),{items:r,totalCount:n}=await async function(e,t,i,r){const{ATOMS_SUPABASE_URL:n,ATOMS_SUPABASE_ANON_KEY:a}=await Promise.resolve().then(()=>(pe(),le)),s=await fetch(`${n}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`,apikey:a},body:JSON.stringify({input:i})});if(!s.ok)throw new Error(`Embed function failed: ${s.status}`);const{embedding:o}=await s.json(),{data:d,error:c}=await e.rpc("semantic_search",{query_embedding:o,p_project_id:t,match_threshold:.3,match_count:r.limit,p_type:r.type||null});if(c)throw new Error(c.message);return{items:d??[],totalCount:(d??[]).length,method:"semantic"}}(t,e.project_id,e.query,{type:e.type,limit:e.limit,accessToken:i});return Ot(_t(r.map(e=>({id:e.id,title:At(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ut(n,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(ni,{semanticSearchHandler:()=>ai});var si=C({"src/tools/semantic-search.ts"(){Ce(),ve(),Bt(),Ct()}}),oi={};async function di(e){try{if(e.baseline_id&&e.as_of)return Ht(yt("baseline_id and as_of are mutually exclusive"));const t=await Se();let i;if(e.baseline_id){const r=await Pt(t,e.baseline_id);if(!r)return Ht(yt(`Baseline ${e.baseline_id} not found`));if(r.project_id!==e.project_id)return Ht(yt("Baseline does not belong to this project"));i=r.snapshot_at}else e.as_of&&(i=e.as_of);const{covered:r,uncovered:n,total:a}=await async function(e,t,i){let r,n,a;if(i.snapshotAt){const s=(await Lt(e,t,i.snapshotAt)).map(Nt);r=s.filter(e=>"requirement"===e.type),n=s.map(e=>({id:e.id,data:e.data})),a=[]}else{const{data:i,error:s}=await e.from("items").select("*").eq("project_id",t).eq("type","requirement").is("deleted_at",null);if(s)throw new Error(s.message);r=i??[];const{data:o,error:d}=await e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null);if(d)throw new Error(d.message);n=o??[];const{data:c,error:l}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t);if(l)throw new Error(l.message);a=c??[]}const s=r.filter(e=>!(i.domain&&!(e.data?.tags?.domains??[]).includes(i.domain)||i.level&&e.data?.tags?.level!==i.level)),o=Wt(n,a),d=new Set;for(const e of o)"verifies"===e.type?d.add(e.to_id):"verified_by"===e.type&&d.add(e.from_id);return{covered:s.filter(e=>d.has(e.id)),uncovered:s.filter(e=>!d.has(e.id)),total:s.length}}(t,e.project_id,{domain:e.domain,level:e.level,snapshotAt:i}),s=n.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level}));return Ot(_t({covered:r.length,uncovered:n.length,total:a,coverage_percent:a>0?Math.round(r.length/a*1e3)/10:100,uncovered_items:s}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(oi,{getCoverageHandler:()=>di});var ci=C({"src/tools/get-coverage.ts"(){Ce(),Bt(),Ct()}}),li={};async function mi(e){try{const t=await Se(),i=await async function(e,t,i,r){const{data:n,error:a}=await e.from("change_history").select("*").eq("item_id",i).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r);if(a)throw new Error(a.message);return n??[]}(t,e.project_id,e.item_id,e.limit),r=i.map(e=>{const t=[],i=e.old_data,r=e.new_data;if(i&&r){const e=new Set([...Object.keys(i),...Object.keys(r)]);for(const n of e)JSON.stringify(i[n])!==JSON.stringify(r[n])&&t.push(n)}else r?t.push("(created)"):i&&t.push("(deleted)");return{id:e.id,event_type:e.event_type,changed_by:e.changed_by??null,changed_at:e.changed_at,actor:e.actor??"user",session_id:e.session_id??null,fields_changed:t}});return Ot(_t(r,ut(r.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(li,{getHistoryHandler:()=>mi});var pi=C({"src/tools/get-history.ts"(){Ce(),Bt(),Ct()}});function _i(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function ui(e){const t=hi(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:`["${t}"]`}function fi(e){const t=_i(e.from_id),i=_i(e.to_id);return"child"===e.type?`${t} --\x3e ${i}`:"verified_by"===e.type?`${t} -.-> ${i}`:"related"===e.type?`${t} -.- ${i}`:null}function hi(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var gi=C({"src/core/mermaid.ts"(){}}),yi={};async function wi(e){try{if(e.baseline_id&&e.as_of)return Ht(yt("baseline_id and as_of are mutually exclusive"));const t=await Se();let i,r,n;if(e.baseline_id){const r=await Pt(t,e.baseline_id);if(!r)return Ht(yt(`Baseline ${e.baseline_id} not found`));if(r.project_id!==e.project_id)return Ht(yt("Baseline does not belong to this project"));i=r.snapshot_at}else e.as_of&&(i=e.as_of);if(i){r=(await Lt(t,e.project_id,i)).map(Nt).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),n=Wt(r,[])}else{const{data:i,error:a}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);r=i??[];const{data:s,error:o}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);n=Wt(r,s??[])}return Ot(_t(function(e){const t=e.items,i=e.relationships??[],r=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${hi(e.emptyLabel??"No items in project")}]`,node_count:0,edge_count:0};const n=new Map(t.map(e=>[e.id,e])),a=function(e,t,i,r){if(i)return[i];const n=new Set(t.filter(e=>"child"===e.type).map(e=>e.to_id));return e.filter(e=>!n.has(e.id)).filter(e=>r||"test-case"!==e.type).map(e=>e.id)}(t,i,e.rootItemId,e.includeTests),s=a.map(e=>({id:e,depth:0})),o=new Set,d=new Set,c=[],l=[];for(;s.length>0;){const{id:t,depth:a}=s.shift();if(o.has(t)||a>r)continue;const m=n.get(t);if(m&&(e.includeTests||"test-case"!==m.type)){o.add(t),c.push(` ${_i(t)}${ui(m)}`);for(const c of i){if(c.from_id!==t)continue;const i=n.get(c.to_id);if(!i)continue;if(!e.includeTests&&"test-case"===i.type)continue;if(a+1>r)continue;const m=fi(c);if(!m)continue;const p=`${c.from_id}:${c.type}:${c.to_id}`;d.has(p)||(d.add(p),l.push(` ${m}`),o.has(c.to_id)||s.push({id:c.to_id,depth:a+1}))}}}return{mermaid:["graph TD",...c,...l].join("\n"),node_count:o.size,edge_count:d.size}}({items:r,relationships:n,rootItemId:e.root_item_id,depth:e.depth,includeTests:e.include_tests,emptyLabel:"No items in project"})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(yi,{exportMermaidHandler:()=>wi});var bi=C({"src/tools/export-mermaid.ts"(){Ce(),Bt(),Ct(),gi()}}),vi={};function ji(e){const t=pt(e??"");return"sub-system"===t?"subsystem":t}async function Si(e,t){const{data:i}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:i?.domains??[],levels:i?.levels??[]}}async function xi(e,t,i,r){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:i,levels:r},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function ki(e,t,i){const r=pt(i??""),n=ji(r);if(!r)return!1;try{const{domains:i,levels:a}=await Si(e,t);return!a.some(e=>ji(e)===n)&&(await xi(e,t,i,[...a,r]),!0)}catch{return!1}}async function Ii(e){try{const t=await Se(),{levels:i}=await Si(t,e.project_id),{data:r}=await t.from("items").select("data").eq("project_id",e.project_id).is("deleted_at",null),n={};for(const e of r??[]){const t=e.data?.tags,i=ji(t?.level);i&&(n[i]=(n[i]??0)+1)}return Ot(_t({levels:i.map((e,t)=>({name:e,prefix:`L${t}`,item_count:n[ji(e)]??0})),total:i.length,note:"L# is the level's position in this list (0-based). Names are user-defined."}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Ei(e){try{const t=await Se();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const{domains:i,levels:r}=await Si(t,e.project_id),n=pt(e.name),a=ji(n);if(!n)return Ht(yt("Level name cannot be empty."));if(r.some(e=>ji(e)===a))return Ht(yt(`Level "${n}" already exists in this project.`));const s=r.length;return await xi(t,e.project_id,i,[...r,n]),Ot(_t({level:{name:n,prefix:`L${s}`},message:`Level "${n}" registered as L${s}. Tag items with level="${n}".`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(vi,{createLevelHandler:()=>Ei,ensureLevelRegistered:()=>ki,listLevelsHandler:()=>Ii});var Ai=C({"src/tools/levels.ts"(){Ce(),Ct()}}),Oi={};async function Hi(e,t){const{data:i}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();return(i?.fields??[]).filter(e=>e&&"string"==typeof e.name&&e.name.length>0)}function Di(e,t){const i=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!i.has(e.toLowerCase()))}function Ci(e,t){const i=new Map(e.map(e=>[e.name.toLowerCase(),e.name])),r={};for(const[e,n]of Object.entries(t))r[i.get(e.toLowerCase())??e]=n;return r}async function Ri(e){try{const t=await Se(),i=await Hi(t,e.project_id),{data:r}=await t.from("items").select("data").eq("project_id",e.project_id).is("deleted_at",null),n={};for(const e of i)n[e.name]=0;const a=new Map(i.map(e=>[e.name.toLowerCase(),e.name]));for(const e of r??[]){const t=e.data?.fields??{};for(const[e,i]of Object.entries(t)){const t=a.get(e.toLowerCase());t&&"string"==typeof i&&i.length>0&&n[t]++}}return Ot(_t({fields:i.map(e=>({name:e.name,item_count:n[e.name]??0})),total:i.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Ui(e){try{const t=await Se();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const{data:i}=await t.from("metadata").select("domains, levels, fields").eq("project_id",e.project_id).maybeSingle(),r=i?.domains??[],n=i?.levels??[],a=i?.fields??[],s=e.name.trim();if(!s)return Ht(yt("Field name cannot be empty."));if(s.length>60)return Ht(yt("Field name must be 60 characters or fewer."));const o=a.find(e=>e.name.toLowerCase()===s.toLowerCase());if(o)return Ht(yt(`Field "${o.name}" already exists (field names are unique case-insensitively; "${s}" collides with it).`));const{error:d}=await t.from("metadata").upsert({project_id:e.project_id,domains:r,levels:n,fields:[...a,{name:s}]},{onConflict:"project_id"});if(d)throw new Error(d.message);return Ot(_t({field:{name:s},message:`Field "${s}" defined. Set values with atoms_update_item fields={"${s}": "<value>"}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Oi,{canonicalizeFieldKeys:()=>Ci,createFieldHandler:()=>Ui,findUnknownFieldNames:()=>Di,getProjectFields:()=>Hi,listFieldsHandler:()=>Ri});var qi=C({"src/tools/fields.ts"(){Ce(),Ct()}}),Mi={};async function Ti(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=(e.domains??[]).map(pt).filter(e=>e.length>0),n=void 0!==e.level?pt(e.level):void 0;if(r.length>0){const{data:i}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),n=i?.domains??[];if(n.length>0){const e=new Set(n.map(pt).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return Ht(yt(`Unknown domain${t.length>1?"s":""}: ${t.join(", ")}. Registered: ${n.join(", ")}. Add new domains via Taxonomy Management in the ATOMS web app first.`))}}let a;if(e.fields&&Object.keys(e.fields).length>0){const{getProjectFields:i,findUnknownFieldNames:r,canonicalizeFieldKeys:n}=await Promise.resolve().then(()=>(qi(),Oi)),s=await i(t,e.project_id),o=r(s,e.fields);if(o.length>0)return Ht(yt(`Unknown field${o.length>1?"s":""}: ${o.join(", ")}. Defined: ${s.length>0?s.map(e=>e.name).join(", "):"(none)"}. Define fields first with atoms_create_field.`));a=n(s,e.fields)}const s=await Vt(t,e.project_id,e.type),o=(new Date).toISOString(),d={id:s,type:e.type,title:e.title,summary:e.summary,body:e.body,tags:{domains:r,level:n??""},ownership:{primary:null,additional:[]},relationships:{parents:e.parent_ids??[],children:[],related:[],verifies:[],verified_by:[]},links:[],...a?{fields:a}:{},metadata:{created_at:o,created_by:i,updated_at:o,updated_by:i}},{error:c}=await t.rpc("save_item_with_revision",{p_item_id:s,p_project_id:e.project_id,p_type:e.type,p_title:e.title,p_data:d,p_user_id:i,p_event_source:"mcp",p_event_session_id:da()??null,p_diff_summary:null});if(c)throw new Error(c.message);if(n&&await ki(t,e.project_id,n),e.parent_ids&&e.parent_ids.length>0)for(const r of e.parent_ids){const{error:n}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:s,p_to_id:r,p_type:"parent",p_action:"add",p_user_id:i,p_event_source:"mcp"});n&&process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${r}: ${n.message}\n`)}return await t.from("change_history").insert({item_id:s,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:d,actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===e.echo?Ot(_t({id:s,type:e.type})):Ot(_t({id:s,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",domains:r,level:n??"",project_id:e.project_id}))}catch(e){return Ht(It(e))}}R(Mi,{createItemHandler:()=>Ti});var $i=C({"src/tools/create-item.ts"(){Ce(),Bt(),ma(),Ct(),Ai()}}),Pi={};async function Ni(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=async(r,n,a,s)=>{const o=await Tt(t,e.project_id,r);if(!o)return{updated_fields:[],error:`Item "${r}" not found`};const d=void 0!==n.domains?n.domains.map(pt).filter(e=>e.length>0):void 0,c=void 0!==n.level?pt(n.level):void 0;if(void 0!==d&&d.length>0){const{data:i}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),r=i?.domains??[];if(r.length>0){const e=new Set(r.map(pt).filter(e=>e.length>0)),t=d.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const l={...o.data},m={...o.data},p=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==n.title&&_(o.data.title,n.title)&&(m.title=n.title,p.push("title")),void 0!==n.body&&_(o.data.body,n.body)&&(m.body=n.body,p.push("body")),void 0!==n.summary&&_(o.data.summary,n.summary)&&(m.summary=n.summary,p.push("summary")),void 0!==d&&_(o.data.tags?.domains??[],d)&&(m.tags={...m.tags,domains:d},p.push("domains")),void 0!==c&&_(o.data.tags?.level,c)&&(m.tags={...m.tags,level:c},p.push("level")),void 0!==n.status&&_(o.data.status,n.status)&&(m.status=n.status,p.push("status")),void 0!==n.fields&&Object.keys(n.fields).length>0){const{getProjectFields:i,findUnknownFieldNames:r,canonicalizeFieldKeys:a}=await Promise.resolve().then(()=>(qi(),Oi)),s=await i(t,e.project_id),d=r(s,n.fields);if(d.length>0)return{updated_fields:[],error:`Unknown field${d.length>1?"s":""}: ${d.join(", ")}. Defined: ${s.length>0?s.map(e=>e.name).join(", "):"(none)"}. Define fields first with atoms_create_field.`};const c=a(s,o.data.fields??{});for(const[e,t]of Object.entries(a(s,n.fields)))""===t?delete c[e]:c[e]=t;_(o.data.fields??{},c)&&(m.fields=c,p.push("fields"))}if(0===p.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};m.metadata={...m.metadata,updated_at:(new Date).toISOString(),updated_by:i};const u=n.title??o.title,{data:f,error:h}=await t.rpc("save_item_with_revision",{p_item_id:r,p_project_id:e.project_id,p_type:o.type,p_title:u,p_data:m,p_user_id:i,p_event_source:"mcp",p_event_session_id:da()??null,p_diff_summary:null,p_expected_updated_at:n.expected_updated_at??o.updated_at});if(h)return{updated_fields:[],error:h.message};if(!f)return{updated_fields:[],error:`Update silently failed for "${r}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};p.includes("level")&&c&&await ki(t,e.project_id,c);const g={item_id:r,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:l,new_data:m,actor:ca(),session_id:da()};return a&&(g.batch_id=a),s&&(g.reason=s),await t.from("change_history").insert(g).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),{updated_fields:p,updatedData:m,itemType:o.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),i=!0===e.continue_on_error,n=[],a=[];for(const s of e.updates){const{updated_fields:o,error:d}=await r(s.item_id,s,t,e.reason);if(d){if(!i)return xt(d)?Ht(It(new Error(d))):Ht(yt(`Batch stopped at "${s.item_id}": ${d}. ${n.length} item(s) already updated.`));a.push({item_id:s.item_id,error:d})}else n.push({id:s.item_id,updated_fields:o})}return Ot(_t({batch_id:t,updated:n.length,results:!1===e.echo?void 0:n,errors:a}))}if(!e.item_id)return Ht(yt("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:n,updatedData:a,itemType:s,error:o}=await r(e.item_id,{title:e.title,body:e.body,summary:e.summary,domains:e.domains,level:e.level,status:e.status,fields:e.fields,expected_updated_at:e.expected_updated_at},void 0,e.reason);if(o)return o.includes("not found")?Ht(ht("Item",e.item_id)):o.includes("Unknown domain")||o.includes("Unknown field")?Ht(yt(o)):xt(o)?Ht(It(new Error(o))):Ht(Et(o));if(!1===e.echo)return Ot(_t({id:e.item_id,updated_fields:n}));const d=a??{};return Ot(_t({id:e.item_id,type:s,title:d.title??"",summary:d.summary??"",body:d.body??"",domains:d.tags?.domains??[],level:d.tags?.level??"",updated_fields:n}))}catch(e){return Ht(It(e))}}R(Pi,{updateItemHandler:()=>Ni});var Li,Fi,Wi=C({"src/tools/update-item.ts"(){Ce(),Bt(),ma(),Ct(),Ai()}});function Vi(e){const t=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(t){const i=t.toLowerCase();if("1"===i||"true"===i||"all"===i)return!0;if(t.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!B().require_confirmation_for.includes(e)}function Bi(e,t=Li){const i=Date.now()+t,r={...e,exp:i},n=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${n}.${l.createHmac("sha256",Fi).update(n).digest("base64url")}`,expires_at:new Date(i).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function zi(e,t){if("string"!=typeof e||!e.includes("."))return{valid:!1,reason:"Token format invalid"};const[i,r]=e.split(".");if(!i||!r)return{valid:!1,reason:"Token format invalid"};const n=l.createHmac("sha256",Fi).update(i).digest("base64url"),a=Buffer.from(r,"utf8"),s=Buffer.from(n,"utf8");if(a.length!==s.length||!l.timingSafeEqual(a,s))return{valid:!1,reason:"Token signature invalid"};let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return{valid:!1,reason:"Token payload malformed"}}return"number"!=typeof o.exp||o.exp<Date.now()?{valid:!1,reason:"Token expired"}:o.tool!==t.tool?{valid:!1,reason:"Token issued for a different tool"}:o.project_id!==t.project_id?{valid:!1,reason:"Token issued for a different project"}:o.target!==t.target?{valid:!1,reason:"Token issued for a different target"}:{valid:!0}}function Ji(e){if(Array.isArray(e))return e.map(Ji);if(null!==e&&"object"==typeof e){const t={};for(const i of Object.keys(e).sort())t[i]=Ji(e[i]);return t}return e}function Qi(e){const t=JSON.stringify(Ji(e));return l.createHash("sha256").update(t).digest("base64url").slice(0,16)}var Gi,Yi=C({"src/middleware/confirmation.ts"(){z(),Li=6e4,Fi=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:l.randomBytes(32).toString("base64url")})()}}),Ki={};function Zi(e){return"mitigated_by"===e.type?{rowId:e.from_id,reqId:e.to_id,role:e.role??null}:{rowId:e.to_id,reqId:e.from_id,role:e.role??null}}async function Xi(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=await async function(e,t,i){const{data:r,error:n}=await e.from("items").select("*").eq("id",i).eq("project_id",t).maybeSingle();if(n)throw new Error(n.message);return r}(t,e.project_id,e.item_id);if(!r)return Ht(ht("Item",e.item_id));if(r.deleted_at)return Ht(yt(`Item ${e.item_id} is already deleted`));if(Vi(Gi)){const t={tool:Gi,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const i=Bi(t);return Ot(_t({status:"confirmation_required",preview:{id:e.item_id,title:r.title,type:r.type,would_soft_delete:!0},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_delete_item with the same project_id, item_id, and confirmation_token within ${i.expires_in_seconds}s to execute.`}))}const i=zi(e.confirmation_token,t);if(!i.valid)return Ht(yt(`confirmation_token rejected: ${i.reason}`))}await async function(e,t,i,r){const[n,a]=await Promise.all([e.from("item_relationships").select("from_id, to_id, type, role").eq("project_id",t).in("type",["mitigated_by","mitigates"]).eq("from_id",i),e.from("item_relationships").select("from_id, to_id, type, role").eq("project_id",t).in("type",["mitigated_by","mitigates"]).eq("to_id",i)]);if(n.error)throw new Error(n.error.message);if(a.error)throw new Error(a.error.message);const s=new Map;for(const e of[...n.data??[],...a.data??[]]){const t=Zi(e);s.set(`${t.rowId}|${t.reqId}`,t)}for(const i of s.values()){const{error:n}=await e.rpc("apply_link_change",{p_project_id:t,p_from_id:i.rowId,p_to_id:i.reqId,p_type:"mitigated_by",p_action:"remove",p_user_id:r,p_event_source:"mcp"});if(n)throw new Error(n.message);await e.from("change_history").insert({item_id:i.rowId,project_id:t,changed_by:r,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"remove",type:"mitigated_by",from:i.rowId,to:i.reqId,reason:"endpoint_deleted",...i.role?{role:i.role}:{}}},actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: mitigation unlink history log failed: ${e.message}\n`)})}}(t,e.project_id,e.item_id,i);const{error:n}=await t.from("items").update({deleted_at:(new Date).toISOString()}).eq("id",e.item_id).eq("project_id",e.project_id);if(n)throw new Error(n.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"deleted",old_data:r.data,new_data:null,actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Ot(_t({id:e.item_id,title:r.title,type:r.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return Ht(It(e))}}R(Ki,{deleteItemHandler:()=>Xi});var er=C({"src/tools/delete-item.ts"(){Ce(),Bt(),ma(),Yi(),Ct(),Gi="atoms_delete_item"}}),tr={};async function ir(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const{data:r,error:n}=await t.from("items").select("*").eq("id",e.item_id).eq("project_id",e.project_id).maybeSingle();if(n)throw new Error(n.message);if(!r)return Ht(ht("Item",e.item_id));if(!r.deleted_at)return Ht(ft(`Item ${e.item_id} is not deleted and cannot be restored.`,["Use atoms_get_item to view the current item state","Use atoms_delete_item first if you intended to delete it"]));const{error:a}=await t.rpc("save_item_with_revision",{p_item_id:e.item_id,p_project_id:e.project_id,p_type:r.type,p_title:r.title,p_data:r.data,p_user_id:i,p_event_source:"restore",p_event_session_id:da()??null,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:r.updated_at});if(a)throw new Error(a.message);return await t.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:e.project_id,p_item_id:e.item_id}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: relationship repair failed: ${e.message}\n`)}),await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"restored",old_data:null,new_data:r.data,actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Ot(_t({id:e.item_id,title:r.title,type:r.type,restored:!0,message:`Item ${e.item_id} restored successfully.`}))}catch(e){return Ht(It(e))}}R(tr,{restoreItemHandler:()=>ir});var rr=C({"src/tools/restore-item.ts"(){Ce(),ma(),Ct()}}),nr={};async function ar(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=async(r,n,a)=>{const s=await Tt(t,e.project_id,r.from_id);if(!s)throw new Error(`Item "${r.from_id}" not found`);const o=await Tt(t,e.project_id,r.to_id);if(!o)throw new Error(`Item "${r.to_id}" not found`);const{error:d}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r.from_id,p_to_id:r.to_id,p_type:r.type,p_action:r.action,p_user_id:i,p_event_source:"mcp",p_expected_from_updated_at:r.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:r.expected_to_updated_at??o.updated_at});if(d)throw new Error(d.message);const c={item_id:r.from_id,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:null,new_data:{relationship_change:{action:r.action,type:r.type,from:r.from_id,to:r.to_id}},actor:ca(),session_id:da()};n&&(c.batch_id=n),a&&(c.reason=a),await t.from("change_history").insert(c).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})};if(e.operations&&Array.isArray(e.operations)){for(const t of e.operations)if(t.from_id===t.to_id)return Ht(yt(`Self-reference in batch: "${t.from_id}"`));const i=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],{data:n}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",i),a=new Set((n??[]).map(e=>e.id)),s=i.filter(e=>!a.has(e));if(s.length>0)return Ht(ht("Items",s.join(", ")));const{data:o}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),d=new Map;for(const e of o??[])"parent"===e.type&&(d.has(e.from_id)||d.set(e.from_id,new Set),d.get(e.from_id).add(e.to_id));for(const t of e.operations){if("parent"!==t.type&&"child"!==t.type)continue;const[e,i]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?d.get(e)?.delete(i):(d.has(e)||d.set(e,new Set),d.get(e).add(i))}const c=0,l=1,m=2,p=new Map,_=new Set;for(const[e,t]of d){_.add(e);for(const e of t)_.add(e)}const u=e=>{if((p.get(e)??c)!==c)return null;const t=[],i=[],r=e=>{p.set(e,l),i.push(e),t.push({node:e,parents:[...d.get(e)??[]],idx:0})};for(r(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){p.set(e.node,m),i.pop(),t.pop();continue}const n=e.parents[e.idx];e.idx++;const a=p.get(n)??c;if(a===l){const e=i.indexOf(n);return[...i.slice(e),n]}a!==m&&r(n)}return null};for(const e of _){const t=u(e);if(t)return Ht(yt(`Batch would create a cycle: ${t.join(" -> ")}. No changes applied.`))}const f=crypto.randomUUID(),h=e.operations.filter(e=>"remove"===e.action),g=e.operations.filter(e=>"add"===e.action);for(const t of[...h,...g])await r(t,f,e.reason);return Ot(_t({batch_id:f,processed:e.operations.length,operations:!1===e.echo?void 0:e.operations}))}return e.from_id&&e.to_id&&e.type&&e.action?e.from_id===e.to_id?Ht(yt("Cannot create a relationship between an item and itself")):(await r({action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type,expected_from_updated_at:e.expected_from_updated_at,expected_to_updated_at:e.expected_to_updated_at},void 0,e.reason),!1===e.echo?Ot(_t({action:e.action,from_id:e.from_id,to_id:e.to_id})):Ot(_t({action:e.action,type:e.type,from_id:e.from_id,to_id:e.to_id,message:`Relationship ${"add"===e.action?"added":"removed"}: ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`}))):Ht(yt("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."))}catch(e){return Ht(It(e))}}R(nr,{linkItemsHandler:()=>ar});var sr=C({"src/tools/link-items.ts"(){Ce(),Bt(),ma(),Ct()}}),or=C({"src/core/bulk-parent-links.ts"(){}}),dr={};async function cr(e){try{if(!e.items||0===e.items.length)return Ht(yt("items array must contain at least 1 item"));if(e.items.length>100)return Ht(yt(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=await async function(e,t,i){const{data:r}=await e.from("metadata").select("domains").eq("project_id",t).maybeSingle(),n=r?.domains??[],a=n.length>0?new Set(n.map(pt).filter(e=>e.length>0)):null,s=Qi(n.map(pt).filter(e=>e.length>0).sort()),o=[],d=new Set,c={};for(let e=0;e<i.length;e++){const t=i[e];if(c[t.type]=(c[t.type]??0)+1,!a)continue;const r=(t.domains??[]).map(pt).filter(e=>e.length>0);if(0===r.length)continue;const s=r.filter(e=>!a.has(e));s.length>0&&(d.add(e),o.push({index:e,title:t.title,error:`Unknown domain${s.length>1?"s":""}: ${s.join(", ")}. Registered: ${n.join(", ")}.`}))}return{registeredDomains:n,registeredDomainHash:s,invalidDomainIndexes:d,errors:o,typeBreakdown:c}}(t,e.project_id,e.items);if(Vi("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:Qi({items:e.items,registered_domain_hash:r.registeredDomainHash})};if(!e.confirmation_token){const i=Bi(t);return Ot(_t({status:"confirmation_required",preview:{total_items:e.items.length,by_type:r.typeBreakdown,sample_titles:e.items.slice(0,5).map(e=>e.title),would_fail:r.errors.length>0,errors:r.errors,registered_domain_hash:r.registeredDomainHash},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_bulk_import with the same project_id, items array, and confirmation_token within ${i.expires_in_seconds}s to execute. Changing items or project domains will invalidate the token.`}))}const i=zi(e.confirmation_token,t);if(!i.valid)return Ht(yt(`confirmation_token rejected: ${i.reason}`))}const n=(new Date).toISOString(),a=da(),s=[],o=[...r.errors],d=[];for(let i=0;i<e.items.length;i++){const n=e.items[i];if(r.invalidDomainIndexes.has(i))continue;const a=(n.domains??[]).map(pt).filter(e=>e.length>0),s=void 0!==n.level?pt(n.level):void 0;try{const r=await Vt(t,e.project_id,n.type);d.push({itemId:r,input:n,sanitizedDomains:a,sanitizedLevel:s,index:i})}catch(e){o.push({index:i,title:n.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===d.length)return Ot(_t({created:0,items:[],errors:o}));const c=[],l=new Map;for(const{itemId:t,input:r,sanitizedDomains:a,sanitizedLevel:s}of d){const o={id:t,type:r.type,title:r.title,summary:r.summary,body:r.body,tags:{domains:a,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:r.parent_id?[r.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:n,created_by:i,updated_at:n,updated_by:i}};l.set(t,o),c.push({id:t,project_id:e.project_id,type:r.type,title:r.title,data:o,created_by:i,updated_by:i})}const m=c.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:p}=await t.rpc("bulk_save_items_with_revisions",{p_project_id:e.project_id,p_items:m,p_user_id:i,p_event_source:"mcp"});if(p)for(const{itemId:r,input:n,index:l}of d){const d=c.find(e=>e.id===r);if(!d)continue;const{error:m}=await t.rpc("save_item_with_revision",{p_item_id:d.id,p_project_id:e.project_id,p_type:d.type,p_title:d.title,p_data:d.data,p_user_id:i,p_event_source:"mcp",p_event_session_id:a,p_diff_summary:null});m?o.push({index:l,title:n.title,error:m.message}):s.push({id:r,title:n.title,type:n.type})}else for(const{itemId:e,input:t}of d)s.push({id:e,title:t.title,type:t.type});const _=d.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:t,input:i})=>({from_id:t,to_id:i.parent_id,type:"parent",project_id:e.project_id}));await async function(e){for(const t of e.links){const{error:i}=await e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:t.from,p_to_id:t.to,p_type:"parent",p_action:"add",p_user_id:e.userId,p_event_source:"mcp"});i&&e.warn(`bulk parent link sync failed for ${t.to}: ${i.message??"unknown error"}`)}}({client:t,projectId:e.project_id,links:_.map(e=>({from:e.from_id,to:e.to_id})),userId:i,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const u=s.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:l.get(t.id)??null,actor:ca(),session_id:a}));u.length>0&&await t.from("change_history").insert(u).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const f=new Set(s.map(e=>e.id)),h=new Set(d.filter(({itemId:e,sanitizedLevel:t})=>t&&f.has(e)).map(({sanitizedLevel:e})=>e));for(const i of h)await ki(t,e.project_id,i);return Ot(_t({created:s.length,items:s,errors:o.length>0?o:[],project_id:e.project_id}))}catch(e){return Ht(It(e))}}R(dr,{bulkImportHandler:()=>cr});var lr=C({"src/tools/bulk-import.ts"(){Ce(),Bt(),ma(),Yi(),Ct(),or(),Ai()}}),mr={};async function pr(e){try{const t=await Se(),i=Ee(),r=Ae();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const n=await Tt(t,e.project_id,e.item_id);if(!n)return Ht(ht("Item",e.item_id));if("test-case"!==n.type)return Ht(yt(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const a=(e.asset??"").trim(),s=(new Date).toISOString(),{data:o,error:d}=await t.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:r||i,p_actor_user_id:i,p_results:[{result:e.result,note:e.note,asset:a||void 0,date:s}]});if(d)throw new Error(d.message);const c=Array.isArray(o)?o[0]:o?.[0];await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:s,note:e.note,asset:a||null},actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const l=a?` (asset: ${a})`:"";return Ot(_t({item_id:e.item_id,result:e.result,run_at:s,run_by:r||i,note:e.note??null,asset:a||null,asset_id:c?.asset_id??null,asset_created:c?.asset_created??!1,message:`Test result '${e.result}' recorded for ${e.item_id}${l}`}))}catch(e){return Ht(It(e))}}R(mr,{recordTestResultHandler:()=>pr});var _r=C({"src/tools/record-test-result.ts"(){Ce(),Bt(),ma(),Ct()}}),ur={};async function fr(e){try{const t=await Se(),i=Ee(),r=Ae();if(!Array.isArray(e.results)||0===e.results.length)return Ht(yt("results must be a non-empty array"));if(e.results.length>100)return Ht(yt(`results must have at most 100 entries (got ${e.results.length})`));try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const n=await Tt(t,e.project_id,e.item_id);if(!n)return Ht(ht("Item",e.item_id));if("test-case"!==n.type)return Ht(yt(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const{data:a,error:s}=await t.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:r||i,p_actor_user_id:i,p_results:e.results});if(s)throw new Error(s.message);return t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"test_result_recorded",old_data:null,new_data:{bulk:!0,count:e.results.length,results:a},actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Ot(_t({item_id:e.item_id,count:e.results.length,results:a,message:`Recorded ${e.results.length} test results for ${e.item_id}`}))}catch(e){return Ht(It(e))}}R(ur,{recordTestResultsBulkHandler:()=>fr});var hr,gr,yr,wr,br=C({"src/tools/record-test-results-bulk.ts"(){Ce(),Bt(),ma(),Ct()}});function vr(e){return Math.min(Math.max(e??5,1),10)}var jr=C({"src/core/trace-graph.ts"(){hr=200,gr=new Set(["parent","verifies","mitigated_by"]),yr=new Set(["child","verified_by","mitigates"]),wr={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"}}}),Sr={};async function xr(e){try{const t=vr(e.depth),i=await Se(),r=await Tt(i,e.project_id,e.item_id);if(!r)return Ht(ht("Item",e.item_id));const{data:n,error:a}=await i.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);const{data:s,error:o}=await i.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);const d=Wt(n??[],s??[]);return Ot(_t(function(e){const t=vr(e.depth),i=e.relationshipTypes?.length?new Set(e.relationshipTypes):null,r=new Map(e.items.map(e=>[e.id,e]));r.has(e.rootItemId)||r.set(e.rootItemId,e.rootItem);const n=new Map,a=(e,t,i)=>{n.has(e)||n.set(e,[]),n.get(e).push({neighbor:t,relType:i})};for(const t of e.relationships){const r=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(!gr.has(r)||i&&!i.has(r)||a(t.from_id,t.to_id,r),yr.has(r))){const e=wr[r]??r;i&&!i.has(e)||a(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!yr.has(r)||i&&!i.has(r)||a(t.from_id,t.to_id,r),gr.has(r))){const e=wr[r]??r;i&&!i.has(e)||a(t.to_id,t.from_id,e)}"related"!==r||i&&!i.has("related")||(a(t.from_id,t.to_id,"related"),a(t.to_id,t.from_id,"related"))}const s=new Set([e.rootItemId]),o=[],d=[],c=[];for(const t of n.get(e.rootItemId)??[])c.push({id:t.neighbor,depth:1,relType:t.relType,from:e.rootItemId});for(;c.length>0&&o.length<hr;){const{id:e,depth:i,relType:a,from:l}=c.shift();if(s.has(e)||i>t)continue;s.add(e);const m=r.get(e);if(m&&(o.push({id:e,title:m.title,type:m.type,relationship:a,depth:i,from:l}),d.push({from:l,to:e,type:a}),i<t))for(const t of n.get(e)??[])s.has(t.neighbor)||c.push({id:t.neighbor,depth:i+1,relType:t.relType,from:e})}const l={id:e.rootItemId,title:e.rootItem.title,type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId};return{root:e.rootItemId,project_id:e.projectId,direction:e.direction,depth_limit:t,items:[l,...o],edges:d,total_count:o.length+1,...o.length>=hr?{truncated:!0,truncation_message:`Results capped at ${hr} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown"},items:n??[],relationships:d??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Sr,{traceHandler:()=>xr});var kr=C({"src/tools/trace.ts"(){Ce(),Bt(),jr(),Ct()}}),Ir={};async function Er(e){try{let t=(await Se()).from("assets").select("id, name, archived_at, created_at").eq("project_id",e.project_id).order("name");e.include_archived||(t=t.is("archived_at",null));const{data:i,error:r}=await t;if(r)throw new Error(r.message);return Ot(_t({assets:i||[],total:(i||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Ir,{listAssetsHandler:()=>Er});var Ar=C({"src/tools/assets.ts"(){Ce(),Ct()}}),Or={};async function Hr(e,t,i,r){if(i&&r)throw new Error("baseline_id and as_of are mutually exclusive");if(r)return r;if(!i)return null;const{data:n,error:a}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",i).maybeSingle();if(a)throw new Error(a.message);if(!n||n.project_id!==t||n.deleted_at)throw new Error("Baseline not found for this project");return n.snapshot_at}async function Dr(e,t,i){if(i){const{data:r,error:n}=await e.rpc("variables_at",{p_project_id:t,p_snapshot_at:i});if(n)throw new Error(n.message);return r??[]}const{data:r,error:n}=await e.from("project_variables").select("*").eq("project_id",t).order("name");if(n)throw new Error(n.message);return r??[]}async function Cr(e,t,i,r){const{data:n,error:a}=await e.rpc("save_variable_with_revision",{p_project_id:t.project_id,p_name:t.name,p_value:t.value,p_unit:t.unit??null,p_description:t.description??null,p_is_signal:t.is_signal??!1,p_range_min:t.range_min??null,p_range_max:t.range_max??null,p_rate_ms:t.rate_ms??null,p_user_id:i,p_event_source:r,p_variable_id:t.id??null});if(a)throw new Error(a.message);return n}async function Rr(e){try{const t=await Se(),i=await Hr(t,e.project_id,e.baseline_id,e.as_of),r=await Dr(t,e.project_id,i);return Ot(_t({variables:r,total:r.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Ur(e){try{const t=await Se(),i=await Hr(t,e.project_id,e.baseline_id,e.as_of),r=(await Dr(t,e.project_id,i)).find(t=>t.name===e.variable_name)??null;if(!r)return Ht(ht("Variable",e.variable_name));const{data:n}=await t.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null),a=`{${e.variable_name}}`,s=(n||[]).filter(e=>(e.data?.body||"").includes(a));return Ot(_t({variable:r,referenced_by:s.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:s.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function qr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(!r.data)return Ht(ht("Variable",e.variable_name));const n={updated_by:i,updated_at:(new Date).toISOString()};return void 0!==e.value&&(n.value=e.value),void 0!==e.unit&&(n.unit=e.unit||null),void 0!==e.description&&(n.description=e.description||null),Ot(_t({variable:await Cr(t,{...r.data,...n,project_id:e.project_id,name:e.variable_name,value:n.value??r.data.value,unit:n.unit??r.data.unit,description:n.description??r.data.description},i,"mcp")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Mr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const n=e.variables.filter(e=>!r.test(e.name));if(n.length>0)return Ht(yt(`Invalid variable name(s): ${n.map(e=>e.name).join(", ")}. Use letters, digits, underscores; must start with letter or underscore.`));const a=e.variables.map(e=>e.name),s=a.filter((e,t)=>a.indexOf(e)!==t);if(s.length>0)return Ht(yt(`Duplicate names in batch: ${[...new Set(s)].join(", ")}`));const{data:o}=await t.from("project_variables").select("name").eq("project_id",e.project_id).in("name",a),d=(o??[]).map(e=>e.name);if(d.length>0)return Ht(yt(`Variable(s) already exist: ${d.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const c=e.variables.map(t=>({project_id:e.project_id,name:t.name,value:t.value,unit:t.unit??null,description:t.description??null,created_by:i,updated_by:i})),l=await async function(e,t,i,r){const{data:n,error:a}=await e.rpc("bulk_save_variables_with_revisions",{p_project_id:t,p_variables:i,p_user_id:r,p_event_source:"mcp"});if(a)throw new Error(a.message);return n??[]}(t,e.project_id,c,i);return Ot(_t({batch_id:crypto.randomUUID(),created:(l??[]).length,variables:!1===e.echo?(l??[]).map(e=>({name:e.name})):l??[],message:`${(l??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`}))}if(!e.name||!e.value)return Ht(yt("Provide either (name, value) for single variable or variables[] for batch."));if(!r.test(e.name))return Ht(yt(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const{data:n}=await t.from("project_variables").select("name").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(n)return Ht(yt(`Variable "${e.name}" already exists in this project.`));const a=await Cr(t,{project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null},i,"mcp");return!1===e.echo?Ot(_t({name:e.name})):Ot(_t({variable:a,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Tr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const{data:r}=await t.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!r)return Ht(ht("Variable",e.name));const{data:n}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->>body","ilike",`%{${e.name}}%`),a=(n??[]).length;if(a>0&&!e.force)return Ht(yt(`Variable "${e.name}" is referenced in ${a} item${a>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(Vi("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const i=Bi(t);return Ot(_t({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:a,would_orphan_references:a>0},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_delete_variable with the same project_id, name, and confirmation_token within ${i.expires_in_seconds}s to execute.`}))}const i=zi(e.confirmation_token,t);if(!i.valid)return Ht(yt(`confirmation_token rejected: ${i.reason}`))}const s=await async function(e,t,i,r){const{data:n,error:a}=await e.rpc("delete_variable_with_revision",{p_project_id:t,p_variable_id:i,p_user_id:r,p_event_source:"mcp"});if(a)throw new Error(a.message);return Boolean(n)}(t,e.project_id,r.id,i);return s?Ot(_t({deleted:!0,name:e.name,referenced_by_items:a,warning:a>0?`${a} item${a>1?"s":""} still contain {${e.name}} — those references are now unresolved.`:void 0})):Ht(ht("Variable",e.name))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Or,{createVariableHandler:()=>Mr,deleteVariableHandler:()=>Tr,getVariableHandler:()=>Ur,listVariablesHandler:()=>Rr,updateVariableHandler:()=>qr});var $r=C({"src/tools/variables.ts"(){Ce(),Yi(),Ct()}}),Pr={};async function Nr(e,t){const{data:i}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:i?.domains??[],levels:i?.levels??[]}}async function Lr(e,t,i,r){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:i,levels:r},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function Fr(e){try{const t=await Se(),{domains:i}=await Nr(t,e.project_id),{counts:r,orphans:n}=await async function(e,t,i){const{data:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null),n={};for(const e of i)n[e]=0;const a={};for(const e of r??[]){const t=e.data?.tags?.domains??[];for(const e of t)a[e]=(a[e]??0)+1,e in n&&n[e]++}const s=new Set(i),o={};for(const[e,t]of Object.entries(a))s.has(e)||(o[e]=t);return{counts:n,orphans:o}}(t,e.project_id,i),a=i.map(e=>({name:e,registered:!0,item_count:r[e]??0})),s=Object.entries(n).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),o=[...a,...s];return Ot(_t({domains:o,total:o.length,registered_count:a.length,unregistered_count:s.length,note:s.length>0?`${s.length} unregistered tag(s) found on items. Use atoms_create_domain to register them, or atoms_update_item to remove them.`:void 0}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Wr(e){try{const t=await Se();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const{domains:i,levels:r}=await Nr(t,e.project_id),n=e.name.trim().toLowerCase();return n?i.includes(n)?Ht(yt(`Domain "${n}" already exists in this project.`)):(await Lr(t,e.project_id,[...i,n],r),Ot(_t({domain:{name:n},message:`Domain "${n}" registered. You can now tag items with domains=["${n}"].`}))):Ht(yt("Domain name cannot be empty."))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Vr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const{domains:r,levels:n}=await Nr(t,e.project_id),a=e.name.trim().toLowerCase(),s=e.new_name.trim().toLowerCase();if(!s)return Ht(yt("new_name cannot be empty."));const o=r.includes(a);if(!o){const{data:i}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a])).limit(1);if(!i||0===i.length)return Ht(ht("Domain",a))}if(s!==a&&r.includes(s))return Ht(yt(`Domain "${s}" already exists. Choose a different name.`));const{data:d,error:c}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(c)throw new Error(c.message);const l=(d??[]).length;if(e.dry_run)return Ot(_t({dry_run:!0,rename:{from:a,to:s},items_affected:l,message:`Dry run: renaming "${a}" → "${s}" would update ${l} item${1!==l?"s":""}. Call again with dry_run=false to apply.`}));let m;m=o?r.map(e=>e===a?s:e):r.includes(s)?r:[...r,s],await Lr(t,e.project_id,m,n);const{error:p}=await t.rpc("apply_domain_change",{p_project_id:e.project_id,p_old_domain:a,p_new_domain:s,p_user_id:i,p_event_source:"mcp"});if(p)throw new Error(p.message);return Ot(_t({domain:{name:s},renamed_from:a,items_updated:l,message:`Domain renamed "${a}" → "${s}". ${l} item${1!==l?"s":""} updated.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}async function Br(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const{domains:r,levels:n}=await Nr(t,e.project_id),a=e.name.trim().toLowerCase(),s=r.includes(a),{data:o,error:d}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(d)throw new Error(d.message);const c=(o??[]).length;if(!s&&0===c)return Ht(ht("Domain",a));if(c>0&&!e.force)return Ht(yt(`Domain "${a}" is used by ${c} item${c>1?"s":""}. Use force=true to delete and strip the domain from all items, or re-tag them first.`));if(Vi("atoms_delete_domain")){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:a};if(!e.confirmation_token){const e=Bi(t);return Ot(_t({status:"confirmation_required",preview:{domain_name:a,items_using_count:c,would_strip_from_items:c>0},confirmation_token:e.token,expires_at:e.expires_at,expires_in_seconds:e.expires_in_seconds,message:`Re-call atoms_delete_domain with the same project_id, name, and confirmation_token within ${e.expires_in_seconds}s to execute.`}))}const i=zi(e.confirmation_token,t);if(!i.valid)return Ht(yt(`confirmation_token rejected: ${i.reason}`))}const l=s?r.filter(e=>e!==a):r;if(await Lr(t,e.project_id,l,n),c>0){const{error:r}=await t.rpc("apply_domain_change",{p_project_id:e.project_id,p_old_domain:a,p_new_domain:null,p_user_id:i,p_event_source:"mcp"});if(r)throw new Error(r.message)}return Ot(_t({deleted:!0,name:a,items_updated:c,message:c>0?`Domain "${a}" deleted and stripped from ${c} item${c>1?"s":""}.`:`Domain "${a}" deleted.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Pr,{createDomainHandler:()=>Wr,deleteDomainHandler:()=>Br,listDomainsHandler:()=>Fr,updateDomainHandler:()=>Vr});var zr=C({"src/tools/domains.ts"(){Ce(),Yi(),Ct()}}),Jr={};async function Qr(e){try{const t=await Se(),{data:i,error:r}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle(),n=i?.name??null,a=r?.message??null,{data:s,error:o}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(o)throw new Error(o.message);const d=s??[];if(!n&&0===d.length){if(a)throw new Error(a);return Ht(ht("Project",e.project_id))}const c={requirements:0,test_cases:0,notes:0},l=[],m=[];for(const e of d)if("requirement"===e.type){c.requirements++;const t=e.data?.tags?.domains??[];m.push({id:e.id,domains:t})}else"test-case"===e.type?(c.test_cases++,l.push(e.id)):"note"===e.type&&c.notes++;const p={passed:0,failed:0,blocked:0,not_run:0};if(l.length>0){const{data:i,error:r}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(r)throw new Error(r.message);const n=new Map;for(const e of i??[])n.has(e.item_id)||n.set(e.item_id,e.result);for(const e of l){const t=n.get(e);t&&"not-run"!==t?"passed"===t?p.passed++:"failed"===t?p.failed++:"blocked"===t?p.blocked++:p.not_run++:p.not_run++}}const{data:_,error:u}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(u)throw new Error(u.message);const f=Wt(s??[],_??[]),h=new Set;for(const e of f)"verifies"===e.type?h.add(e.to_id):"verified_by"===e.type&&h.add(e.from_id);const g=m.filter(e=>h.has(e.id)).length,y=m.length,w={covered:g,uncovered:y-g,total:y,percent:y>0?Math.round(g/y*1e3)/10:100},b=new Map;for(const e of m){const t=e.domains.length>0?e.domains:["(untagged)"],i=h.has(e.id);for(const e of t){b.has(e)||b.set(e,{covered:0,total:0});const t=b.get(e);t.total++,i&&t.covered++}}const v=Array.from(b.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:t.total>0?Math.round(t.covered/t.total*1e3)/10:100})),j=new Date;j.setDate(j.getDate()-7);const{count:S,error:x}=await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",j.toISOString());if(x)throw new Error(x.message);return Ot(_t({project_id:e.project_id,project_name:n??`Project ${e.project_id.slice(0,8)}`,counts:c,test_status:p,coverage:w,coverage_by_domain:v,recent_changes:S??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Jr,{projectSummaryHandler:()=>Qr});var Gr,Yr=C({"src/tools/project-summary.ts"(){Ce(),Bt(),Ct()}}),Kr={};async function Zr(e){try{const t=await Se();let i,r;if(e.query&&e.query.trim().length>0){const n=await Ft(t,e.project_id,e.query,{type:e.type,limit:e.limit});i=n.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=n.totalCount}else{const n=await Mt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});i=n.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=n.totalCount}const n=await async function(e,t){const{data:i,error:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(r)throw new Error(r.message);const n=new Set,a=new Set;for(const e of i??[]){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)n.add(t);const i=t.level;i&&a.add(i)}}return{domains:[...n].sort(),levels:[...a].sort()}}(t,e.project_id);return Ot(_t({items:i,filters:{domains:n.domains,levels:n.levels,types:Gr},project_id:e.project_id},ut(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(Kr,{browseHandler:()=>Zr});var Xr,en,tn,rn,nn=C({"src/tools/browse.ts"(){Ce(),Bt(),Ct(),Gr=["requirement","test-case","note","table"]}}),an={};async function sn(e){try{const t=e.direction??"downstream",i=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await Se(),n=await Tt(r,e.project_id,e.item_id);if(!n)return Ht(ht("Item",e.item_id));const{data:a,error:s}=await r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(s)throw new Error(s.message);const{data:o,error:d}=await r.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(d)throw new Error(d.message);const c=new Map;for(const e of o??[])c.set(e.id,{title:e.title,type:e.type});const l=new Map,m=(e,t,i)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:i})};for(const e of a??[]){const i=e.type;"upstream"!==t&&"both"!==t||(en.includes(i)&&m(e.from_id,e.to_id,i),tn.includes(i)&&m(e.to_id,e.from_id,rn[i]??i)),"downstream"!==t&&"both"!==t||(tn.includes(i)&&m(e.from_id,e.to_id,i),en.includes(i)&&m(e.to_id,e.from_id,rn[i]??i)),"related"===i&&(m(e.from_id,e.to_id,"related"),m(e.to_id,e.from_id,"related"))}const p=new Set;p.add(e.item_id);const _=[];let u=0;const f=[];for(const t of l.get(e.item_id)??[])f.push({id:t.neighbor,depth:1,path:[{from_id:e.item_id,to_id:t.neighbor,relationship_type:t.relType}]});for(;f.length>0&&_.length<Xr;){const{id:e,depth:t,path:r}=f.shift();if(p.has(e))continue;if(null!==i&&t>i)continue;p.add(e);const n=c.get(e);if(n&&(_.push({item_id:e,title:At(n.title),type:n.type,depth:t,relationship_path:r}),t>u&&(u=t),null===i||t<i))for(const i of l.get(e)??[])p.has(i.neighbor)||f.push({id:i.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:i.neighbor,relationship_type:i.relType}]})}let h=0;if(e.include_variable_refs){const{data:t}=await r.from("variable_references").select("variable_id").eq("item_id",e.item_id).eq("project_id",e.project_id),i=[...new Set((t??[]).map(e=>e.variable_id))];if(i.length>0){const{data:t}=await r.from("project_variables").select("id, name").in("id",i),n=new Map((t??[]).map(e=>[e.id,e.name])),{data:a}=await r.from("variable_references").select("variable_id, item_id").in("variable_id",i).eq("project_id",e.project_id).neq("item_id",e.item_id);for(const t of a??[]){const i=t.item_id;if(p.has(i))continue;if(_.length>=Xr)break;p.add(i);const r=c.get(i);if(!r)continue;const a=n.get(t.variable_id)??t.variable_id;_.push({item_id:i,title:At(r.title),type:r.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:i,relationship_type:`variable_ref:${a}`}]}),h++}}}const g={};for(const e of _)g[e.type]=(g[e.type]??0)+1;const y=c.get(e.item_id);return Ot(_t({root:{item_id:e.item_id,title:At(y?.title??n.title),type:y?.type??n.type},impacted_items:_,summary:{total_impacted:_.length,by_type:g,max_depth_reached:u,...h>0?{variable_impact_count:h}:{},..._.length>=Xr?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):Ht(Et(e instanceof Error?e.message:String(e)))}}R(an,{impactAnalysisHandler:()=>sn});var on=C({"src/tools/impact-analysis.ts"(){Ce(),Bt(),Ct(),Xr=200,en=["parent","verifies","traces_to","allocated_from","decomposed_from"],tn=["child","verified_by","allocated_to","decomposes_to","traced_by"],rn={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related",traces_to:"traced_by",traced_by:"traces_to",allocated_to:"allocated_from",allocated_from:"allocated_to",decomposes_to:"decomposed_from",decomposed_from:"decomposes_to"}}}),dn=C({"src/core/relationship-sync.ts"(){}}),cn={};function ln(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ht(wt()):null}async function mn(e,t,i){const{data:r,error:n}=await e.from("items").select("id, deleted_at").eq("project_id",t).eq("id",i).maybeSingle();if(n)throw new Error(n.message);if(a=r,!Boolean(a?.id&&null===a.deleted_at))return;var a;const{error:s}=await e.rpc("sync_item_relationships_from_jsonb",{p_project_id:t,p_item_id:i});if(s)throw new Error(s.message)}async function pn(e,t,i,r){if(await mn(e,t,i.id),"test-case"===i.type){const{error:n}=await e.rpc("sync_test_results_for_item",{p_project_id:t,p_item_id:i.id,p_actor_user_id:r});if(n)throw new Error(n.message)}}async function _n(e,t,i,r){await e.from("change_history").insert({item_id:i.id,project_id:t,changed_by:r,event_type:"restored",old_data:i.oldData,new_data:i.data,actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})}async function un(e,t,i){const{data:r,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n)return Ht(Et(n.message));if(!r)return Ht(ht("Project",t));const{data:a,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?Ht(Et(s.message)):!0!==(a?.feature_flags??{})[i]?Ht(ft(`Feature '${i}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function fn(e){try{const t=await Se(),i=await async function(e,t){const{data:i,error:r}=await e.from("baselines").select("id, project_id, name, description, snapshot_at, created_at, created_by, locked_at, locked_by").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1});if(r)throw new Error(`listBaselines: ${r.message}`);return i??[]}(t,e.project_id),r=Math.max(e.offset??0,0),n=Math.min(Math.max(e.limit??50,1),100);return Ot(_t({baselines:i.slice(r,r+n).map(e=>({id:e.id,name:e.name,description:e.description,snapshot_at:e.snapshot_at,created_at:e.created_at,created_by:e.created_by,locked:null!==e.locked_at,locked_at:e.locked_at})),total:i.length,offset:r,limit:n}))}catch(e){return ln(e)??Ht(Et(e instanceof Error?e.message:String(e)))}}async function hn(e){try{const t=await Se(),i=await un(t,e.project_id,"baselines_enabled");if(i)return i;const{data:r,error:n}=await t.from("baselines").insert({project_id:e.project_id,name:e.name.trim(),description:e.description??null,snapshot_at:(new Date).toISOString()}).select().single();return n?"23505"===n.code?Ht(ft(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):Ht(Et(n.message)):Ot(_t({id:r.id,name:r.name,description:r.description,snapshot_at:r.snapshot_at,created_at:r.created_at,locked:!1}))}catch(e){return ln(e)??Ht(Et(e instanceof Error?e.message:String(e)))}}async function gn(e){try{const t=await Se(),i=await Pt(t,e.baseline_id);if(!i)return Ht(ht("Baseline",e.baseline_id));const r=await un(t,i.project_id,"baselines_enabled");if(r)return r;if(null!==i.locked_at)return Ht(ft("Baseline is already locked",["Locks are one-way; nothing to do"]));const{data:n}=await t.from("projects").select("org_id").eq("id",i.project_id).maybeSingle();if(!n)return Ht(ht("Project",i.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ht(wt());const{data:o}=await t.from("org_members").select("role").eq("user_id",s).eq("org_id",n.org_id).maybeSingle();if(!o||"admin"!==o.role)return Ht(ft("Only admins can lock baselines",["Ask an org admin to lock this baseline"]));const{data:d,error:c}=await t.from("baselines").update({locked_at:(new Date).toISOString(),locked_by:s}).eq("id",e.baseline_id).select().single();return c?Ht(Et(c.message)):Ot(_t({id:d.id,locked_at:d.locked_at,locked_by:d.locked_by}))}catch(e){return ln(e)??Ht(Et(e instanceof Error?e.message:String(e)))}}async function yn(e){try{const t=await Se(),[i,r]=await Promise.all([Pt(t,e.baseline_a_id),Pt(t,e.baseline_b_id)]);if(!i||!r)return Ht(ht("Baseline","one of the baseline_ids"));if(i.project_id!==r.project_id)return Ht(ft("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[n,a]=await Promise.all([Lt(t,i.project_id,i.snapshot_at),Lt(t,r.project_id,r.snapshot_at)]),s=new Map(n.map(e=>[e.id,e])),o=new Map(a.map(e=>[e.id,e])),d=Array.from(new Set([...s.keys(),...o.keys()])).sort(),c=[];let l=0,m=0,p=0;for(const e of d){const t=s.get(e),i=o.get(e);if(!t&&i)l++,c.push({item_id:e,change_type:"added"});else if(t&&!i)m++,c.push({item_id:e,change_type:"removed"});else if(t&&i){const r=[];t.title!==i.title&&r.push("title"),t.type!==i.type&&r.push("type");JSON.stringify(t.data??{})!==JSON.stringify(i.data??{})&&r.push("data"),r.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:r}))}}const _=Math.max(e.offset??0,0),u=Math.min(Math.max(e.limit??50,1),200),f=e.detail?c.slice(_,_+u):c.slice(_,_+u).map(({item_id:e,change_type:t,fields_changed:i})=>({item_id:e,change_type:t,fields_changed:i}));return Ot(_t({summary:{added:l,removed:m,modified:p,total_compared:d.length},items:f,page_info:{offset:_,limit:u,total:c.length},baselines:{a:{id:i.id,name:i.name,snapshot_at:i.snapshot_at},b:{id:r.id,name:r.name,snapshot_at:r.snapshot_at}}}))}catch(e){return ln(e)??Ht(Et(e instanceof Error?e.message:String(e)))}}async function wn(e){try{const t=await Se(),i=await Pt(t,e.baseline_id);if(!i)return Ht(ht("Baseline",e.baseline_id));const r=await un(t,i.project_id,"baselines_enabled");if(r)return r;const{data:n}=await t.from("projects").select("org_id").eq("id",i.project_id).maybeSingle();if(!n)return Ht(ht("Project",i.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ht(wt());const{data:o}=await t.from("org_members").select("role").eq("user_id",s).eq("org_id",n.org_id).maybeSingle();if(!o||"admin"!==o.role)return Ht(ft("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const d=await Lt(t,i.project_id,i.snapshot_at),c=d.map(e=>e.id),{data:l,error:m}=c.length>0?await t.from("items").select("*").eq("project_id",i.project_id).in("id",c):{data:[],error:null};if(m)return Ht(Et(m.message));const p=function(e,t){const i=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=i.get(e.id),r=[];var n,a;return t?(null!==t.deleted_at&&r.push("deleted_at"),t.type!==e.type&&r.push("type"),t.title!==e.title&&r.push("title"),n=t.data,a=e.data,JSON.stringify(n??{})!==JSON.stringify(a??{})&&r.push("data")):r.push("missing"),0===r.length?[]:[{id:e.id,type:e.type,title:e.title,data:e.data??{},diff_summary:{changed_fields:r,restored:!0},oldData:t?.data??null}]})}(d,l??[]),{data:_,error:u}=await t.rpc("variables_at",{p_project_id:i.project_id,p_snapshot_at:i.snapshot_at});if(u)return Ht(Et(u.message));const f=_??[];if(!0!==e.confirm)return Ot(_t({preview:!0,items_to_restore:p.length,variables_to_restore:f.length}));let h=0;if(p.length>0){const e=p.map(({oldData:e,...t})=>t),{data:r,error:n}=await t.rpc("bulk_save_items_with_revisions",{p_project_id:i.project_id,p_items:e,p_user_id:s,p_event_source:"restore"});if(n)return Ht(Et(n.message));h="number"==typeof r?r:p.length;for(const e of p)await pn(t,i.project_id,e,s),await _n(t,i.project_id,e,s)}if(f.length>0){const{error:e}=await t.rpc("bulk_save_variables_with_revisions",{p_project_id:i.project_id,p_variables:f,p_user_id:s,p_event_source:"restore"});if(e)return Ht(Et(e.message))}return Ot(_t({ok:!0,items_restored:h,variables_restored:f.length}))}catch(e){return ln(e)??Ht(Et(e instanceof Error?e.message:String(e)))}}R(cn,{createBaselineHandler:()=>hn,diffBaselinesHandler:()=>yn,listBaselinesHandler:()=>fn,lockBaselineHandler:()=>gn,restoreBaselineHandler:()=>wn,syncRestoredItemRelationships:()=>mn});var bn,vn,jn,Sn,xn,kn,In,En,An,On,Hn=C({"src/tools/baselines.ts"(){Ce(),ma(),Ct(),Bt(),dn()}});function Dn(e){const t=e?.severity||"",i=e?.exposure||"",r=e?.controllability||"";return t&&i&&r?"S0"===t||"E0"===i||"C0"===r?"QM":jn[`${t}-${i}-${r}`]||bn:bn}function Cn(e){const t=parseInt(e?.severity||"",10),i=parseInt(e?.occurrence||"",10),r=parseInt(e?.detection||"",10);return Number.isNaN(t)||Number.isNaN(i)||Number.isNaN(r)?bn:String(t*i*r)}function Rn(e,t){return"hara"===e?Dn(t):Cn(t)}function Un(e,t,i){if(i)return!1;if("hara"===e){const e=Dn(t);return"C"===e||"D"===e}const r=parseInt(Cn(t),10);return!Number.isNaN(r)&&r>=200}function qn(e,t,i){if(!e?.approved||!e.approved_at)return!1;const r=Date.parse(e.approved_at);return!Number.isNaN(r)&&[...e.source_req?[e.source_req]:[],...t].some(e=>{const t=i(e),n=t?Date.parse(t):NaN;return!Number.isNaN(n)&&n>r})}var Mn,Tn,$n=C({"src/core/analysis.ts"(){bn="—",vn=["prevention","detection","mitigation"],jn={"S1-E1-C1":"QM","S1-E1-C2":"QM","S1-E1-C3":"QM","S1-E2-C1":"QM","S1-E2-C2":"QM","S1-E2-C3":"QM","S1-E3-C1":"QM","S1-E3-C2":"QM","S1-E3-C3":"A","S1-E4-C1":"QM","S1-E4-C2":"A","S1-E4-C3":"B","S2-E1-C1":"QM","S2-E1-C2":"QM","S2-E1-C3":"QM","S2-E2-C1":"QM","S2-E2-C2":"QM","S2-E2-C3":"A","S2-E3-C1":"QM","S2-E3-C2":"A","S2-E3-C3":"B","S2-E4-C1":"A","S2-E4-C2":"B","S2-E4-C3":"C","S3-E1-C1":"QM","S3-E1-C2":"QM","S3-E1-C3":"A","S3-E2-C1":"QM","S3-E2-C2":"A","S3-E2-C3":"B","S3-E3-C1":"A","S3-E3-C2":"B","S3-E3-C3":"C","S3-E4-C1":"B","S3-E4-C2":"C","S3-E4-C3":"D"},xn={hara:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea:{severity:Sn=["1","2","3","4","5","6","7","8","9","10"],occurrence:Sn,detection:Sn}},kn={hara:["failure_mode","operating_scenario","severity","exposure","controllability","safe_state","ftti","rationale"],dfmea:["failure_mode","cause","severity","occurrence","detection","rationale"]},In={hara:"safety-goal",dfmea:"failure-mode"},En={hara:"SG",dfmea:"FM"},An={hara:"HARA",dfmea:"DFMEA"},On={hara:"hara_iso26262",dfmea:"dfmea_rpn"}}}),Pn={};function Nn(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}async function Ln(e,t,i){const{data:r,error:n}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:i});if(n)throw new Error(`ID generation failed: ${n.message}`);return r}function Fn(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function Wn(e){return JSON.parse(JSON.stringify(e??{}))}async function Vn(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=e.source_req_ids??[];if(r.length>50)return Ht(yt("source_req_ids supports at most 50 entries per call"));if(r.length>0){const{data:i,error:n}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null).in("id",r);if(n)throw new Error(n.message);const a=new Map((i??[]).map(e=>[e.id,e])),s=r.filter(e=>!a.has(e));if(s.length>0)return Ht(ht("Source requirement(s)",s.join(", ")));const o=r.filter(e=>{const t=a.get(e);return"requirement"!==t.type||Mn.has(t.data?.req_type)});if(o.length>0)return Ht(yt(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${o.join(", ")}`))}const n=e.subtype,a=await Ln(t,e.project_id,An[n]),s=e.title??("hara"===n?"New HARA":"New DFMEA"),o=e.revision??"1.0",d=In[n],c=(new Date).toISOString(),l={id:a,type:"analysis",title:s,body:"",tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis:{subtype:n,scheme:On[n],revision:o},metadata:{created_at:c,created_by:i,updated_at:c,updated_by:i}},{error:m}=await t.rpc("save_item_with_revision",{p_item_id:a,p_project_id:e.project_id,p_type:"analysis",p_title:s,p_data:l,p_user_id:i,p_event_source:"mcp",p_event_session_id:da()??null,p_diff_summary:null});if(m)throw new Error(m.message);const p=[],_=[];for(const s of r){const r=await Ln(t,e.project_id,En[n]),o={id:r,type:"requirement",title:"",body:"",req_type:d,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[a],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:{source_req:s,approved:!1,approved_at:null,field_source:{}},metadata:{created_at:c,created_by:i,updated_at:c,updated_by:i}},{error:l}=await t.rpc("save_item_with_revision",{p_item_id:r,p_project_id:e.project_id,p_type:"requirement",p_title:"",p_data:o,p_user_id:i,p_event_source:"mcp",p_event_session_id:da()??null,p_diff_summary:null});if(l)throw new Error(l.message);const{error:m}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r,p_to_id:a,p_type:"parent",p_action:"add",p_user_id:i,p_event_source:"mcp"});m&&(process.stderr.write(`[atoms-mcp] Warning: analysis row parent link sync failed for ${r}: ${m.message}\n`),_.push({row_id:r,source_req:s,message:m.message})),await t.from("change_history").insert({item_id:r,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:o,actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),p.push({id:r,source_req:s})}return await t.from("change_history").insert({item_id:a,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:l,actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Ot(_t({id:a,subtype:n,title:At(s),revision:o,rows:p,..._.length>0?{link_warnings:_,warning:`${_.length} row(s) were created but could not be attached to the analysis and will not appear in atoms_get_analysis. Repair: for each row in link_warnings, call atoms_link_items with type 'parent', from_id=<row id>, to_id=${a}.`}:{}}))}catch(e){return Ht(It(e))}}async function Bn(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}const r=await Tt(t,e.project_id,e.row_id);if(!r)return Ht(ht("Analysis row",e.row_id));const n=r.data,a=Nn(n?.req_type);if(!a)return Ht(yt(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const s=new Set([...kn[a],"effect"]);"hara"===a&&s.add("title");const o=Object.keys(e.fields??{});if(0===o.length)return Ht(yt("fields must contain at least one key"));const d=o.filter(e=>!s.has(e));if(d.length>0)return Ht(yt(`Unknown field(s) for ${a}: ${d.join(", ")}. Allowed: ${[...s].sort().join(", ")}`));const c=xn[a],l={};for(const t of o){const i=e.fields[t];if(c[t]){const e="number"==typeof i&&"dfmea"===a?String(i):i;if("string"!=typeof e||!c[t].includes(e))return Ht(yt(`Invalid ${t} value ${JSON.stringify(i)} for ${a}. Allowed: ${c[t].join(", ")}`));l[t]=e}else{if("string"!=typeof i)return Ht(yt(`Field '${t}' must be a string`));l[t]=i}}const m=n?.analysis_props??null,p=Wn(n);p.analysis_props&&"object"==typeof p.analysis_props||(p.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const _=p.analysis_props;_.field_source&&"object"==typeof _.field_source||(_.field_source={});let u=r.title;for(const[e,t]of Object.entries(l))"effect"===e?p.body=t:"title"===e?(p.title=t,u=t):(_[e]=t,"failure_mode"===e&&"dfmea"===a&&(p.title=t,u=t)),_.field_source[e]="mcp";const f=(new Date).toISOString();p.metadata={...p.metadata??{},updated_at:f,updated_by:i};const{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:r.id,p_project_id:e.project_id,p_type:r.type,p_title:u,p_data:p,p_user_id:i,p_event_source:"mcp",p_event_session_id:da()??null,p_diff_summary:null,p_expected_updated_at:r.updated_at});if(g)throw new Error(g.message);if(!h)return Ht(ft(`Fill silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await t.from("change_history").insert({item_id:r.id,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:n,new_data:p,actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=Rn(a,_),w=[];if("hara"===a){const n=Rn("hara",m),a=Fn(p);if(a.length>0&&y!==bn&&y!==n)for(const n of a){const a=await Tt(t,e.project_id,n);if(!a)continue;const s=a.data;if(s?.asil===y&&s?.asil_source===r.id)continue;const o=s?.asil??null,d=s?.asil_source??null,c=Wn(s);c.asil=y,c.asil_source=r.id,c.metadata={...c.metadata??{},updated_at:f,updated_by:i};const{error:l}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:c,p_user_id:i,p_event_source:"mcp",p_event_session_id:da()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});if(l)throw new Error(l.message);await t.from("change_history").insert({item_id:a.id,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:{asil:o,asil_source:d},new_data:{asil:y,asil_source:r.id},actor:ca(),session_id:da(),reason:`ASIL propagated from ${r.id} (rating change via atoms_fill_row)`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),w.push(n)}}return Ot(_t({row_id:r.id,subtype:a,written_fields:Object.keys(l),computed_level:y,...w.length>0?{asil_propagated_to:w}:{}}))}catch(e){return Ht(It(e))}}async function zn(e,t,i){const r=await Tt(e,t,i);if(!r)return{ok:!1,result:Ht(ht("Analysis",i))};if("analysis"!==r.type)return{ok:!1,result:Ht(yt(`Item ${i} is not an analysis (type='${r.type}')`))};const n=r.data,a=Nn("hara"===n?.analysis?.subtype?"safety-goal":"dfmea"===n?.analysis?.subtype?"failure-mode":null);if(!a)return{ok:!1,result:Ht(yt(`Analysis ${i} is missing a valid analysis.subtype`))};const s=In[a],o=Array.isArray(n?.relationships?.children)?n.relationships.children.filter(e=>"string"==typeof e):[];let d=[];if(o.length>0){const{data:i,error:r}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",o);if(r)throw new Error(r.message);const n=new Map((i??[]).filter(e=>!e.deleted_at&&o.includes(e.id)&&e.data?.req_type===s).map(e=>[e.id,e]));d=o.map(e=>n.get(e)).filter(e=>Boolean(e))}const c=new Set;for(const e of d){const t=e.data?.analysis_props??{};"string"==typeof t.source_req&&t.source_req&&c.add(t.source_req);for(const t of Fn(e.data))c.add(t)}const l=new Map;if(c.size>0){const{data:i,error:r}=await e.from("items").select("id, updated_at").eq("project_id",t).is("deleted_at",null).in("id",[...c]);if(r)throw new Error(r.message);for(const e of i??[])l.set(e.id,e.updated_at)}const m=d.map(e=>{const t=e.data?.analysis_props??{},i=Fn(e.data).filter(e=>l.has(e)),r=i.length>0,n=Rn(a,t),s=function(e,t,i){if(i)return null;if("hara"===e){const e=Dn(t);return"QM"!==e&&e!==bn?`asil ${e} unmitigated`:null}const r=parseInt(Cn(t),10),n=parseInt(t?.severity||"",10);return!Number.isNaN(r)&&r>=100?"rpn >= 100":!Number.isNaN(n)&&n>=9?"severity >= 9":null}(a,t,r),o={id:e.id,title:At("string"==typeof e.title?e.title:""),source_req:"string"==typeof t.source_req?t.source_req:null,effect:At("string"==typeof e.data?.body?e.data.body:""),computed_level:n,is_gap:null!==s,gap_rule:s,is_critical:Un(a,t,r),is_stale:qn(t,i,e=>l.get(e)??null),mitigated_by:i,link_roles:t.link_roles??{},approved:!0===t.approved,approved_at:t.approved_at??null,mcp_fields:Object.entries(t.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort()};for(const e of kn[a]){const i=t[e]??null;o[e]=Tn.has(e)&&"string"==typeof i?At(i):i}return o});return{ok:!0,analysis:{id:r.id,title:At("string"==typeof r.title?r.title:""),subtype:a,scheme:"string"==typeof n?.analysis?.scheme?n.analysis.scheme:On[a],revision:"string"==typeof n?.analysis?.revision?n.analysis.revision:"1.0"},rows:m,counts:{rows:m.length,gaps:m.filter(e=>e.is_gap).length,critical:m.filter(e=>e.is_critical).length,stale:m.filter(e=>e.is_stale).length,approved:m.filter(e=>e.approved).length,linked:m.filter(e=>e.mitigated_by.length>0).length}}}async function Jn(e){try{const t=await Se(),i=await zn(t,e.project_id,e.analysis_id);return i.ok?Ot(_t({analysis:i.analysis,rows:i.rows,counts:i.counts})):i.result}catch(e){return Ht(It(e))}}async function Qn(e){try{const n=await Se(),a=Ee();try{await Oe(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ht(gt("Viewer"));throw e}if(e.row_id===e.req_id)return Ht(yt("row_id and req_id must be different items"));const s=await Tt(n,e.project_id,e.row_id);if(!s)return Ht(ht("Analysis row",e.row_id));const o=s.data,d=Nn(o?.req_type);if(!d)return Ht(yt(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const c=await Tt(n,e.project_id,e.req_id);if(!c)return Ht(ht("Requirement",e.req_id));const l=c.data;if("requirement"!==c.type||Mn.has(l?.req_type))return Ht(yt(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));if("dfmea"===d&&!e.role)return Ht(yt(`role is required for dfmea mitigation links. Choose one of: ${vn.join(", ")}`));if("hara"===d&&e.role)return Ht(yt("role is not applicable to hara mitigation links; omit it (roles are a dfmea concept)"));let m=bn;if("hara"===d){m=Rn("hara",o?.analysis_props);const n=l?.asil;if(m!==bn&&"string"==typeof n&&n.length>0&&n!==m&&!0!==e.override)return Ht((i=m,{...ft(`ASIL conflict: the target requirement already carries asil '${t=n}' but ${r=s.id} computes '${i}'.`,["Pass override=true to apply the HARA value; the override is history-logged like a dialog accept","Or align the row's S/E/C ratings with the existing ASIL before linking"]),details:{code:"asil_conflict",current_value:t,incoming_value:i,source_row:r,hint:"pass override=true to apply the HARA value; the override is history-logged like a dialog accept"}}))}const p="dfmea"===d?e.role:null,{error:_}=await n.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:e.row_id,p_to_id:e.req_id,p_type:"mitigated_by",p_action:"add",p_user_id:a,p_event_source:"mcp",p_expected_from_updated_at:s.updated_at,p_expected_to_updated_at:c.updated_at,p_role:p});if(_)throw new Error(_.message);let u;if(await n.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"add",type:"mitigated_by",from:e.row_id,to:e.req_id,...p?{role:p}:{}}},actor:ca(),session_id:da()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),"hara"===d&&m!==bn){const t=await Tt(n,e.project_id,e.req_id);if(t){const i=t.data,r=i?.asil??null,o=i?.asil_source??null,d=Wn(i);d.asil=m,d.asil_source=s.id;const c=(new Date).toISOString();d.metadata={...d.metadata??{},updated_at:c,updated_by:a};const{error:l}=await n.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:d,p_user_id:a,p_event_source:"mcp",p_event_session_id:da()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});if(l)throw new Error(l.message);await n.from("change_history").insert({item_id:t.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{asil:r,asil_source:o},new_data:{asil:m,asil_source:s.id},actor:ca(),session_id:da(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${r??"unset"}', now '${m}' from ${s.id})`:`ASIL set via atoms_link_mitigation from ${s.id}`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),u=m}}return Ot(_t({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:p,...u?{asil_written:u}:{}}))}catch(e){return Ht(It(e))}var t,i,r}async function Gn(e){try{const t=await Se(),i=await zn(t,e.project_id,e.analysis_id);if(!i.ok)return i.result;const r=i.rows.filter(e=>e.is_gap).map(e=>({id:e.id,title:e.title,source_req:e.source_req,computed_level:e.computed_level,rule:e.gap_rule}));return Ot(_t({analysis_id:i.analysis.id,subtype:i.analysis.subtype,gaps:r,count:r.length}))}catch(e){return Ht(It(e))}}R(Pn,{createAnalysisHandler:()=>Vn,fillRowHandler:()=>Bn,getAnalysisHandler:()=>Jn,getGapsHandler:()=>Gn,linkMitigationHandler:()=>Qn});var Yn,Kn,Zn,Xn,ea,ta,ia,ra,na=C({"src/tools/analysis.ts"(){Ce(),Bt(),ma(),Ct(),$n(),Mn=new Set(["safety-goal","failure-mode"]),Tn=new Set(["failure_mode","cause","operating_scenario","safe_state","ftti","rationale"])}}),aa={};function sa(t){G(t.toolName)&&function(t,i){const r=`ui://${i.toolName}/${i.htmlFile}`,n=function(e,t){const i=u(import.meta.url),r=s.dirname(i);return s.resolve(r,"apps","src","apps",e,t)}(i.appName,i.htmlFile),a=[...Dt.resourceDomains,...i.extraResourceDomains??[]];g(t,i.toolName,{title:i.title,description:i.description,inputSchema:i.inputSchema,annotations:i.annotations,_meta:{ui:{resourceUri:r}}},i.handler),y(t,`${i.title} UI`,r,{mimeType:w},async()=>{const t=await e.readFile(n,"utf-8");return{contents:[{uri:r,mimeType:w,text:t,_meta:{ui:{csp:{resourceDomains:a}}}}]}})}(Xn,t)}function oa(e,t){return async i=>{const r=M(B(),e);if(!r.allowed)return Ht(ft(`Tool ${e} is blocked by org policy.`,[$(r.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=Ke();if(!t)return;if("object"!=typeof e||null===e)return;const i=e.project_id;if("string"==typeof i&&i!==t)throw new Qe(t,i)}(i)}catch(e){if(e instanceof Qe)return Ht(vt(e.expectedProjectId));throw e}{const e=B(),t=i?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return Ht(ft("Tool call rejected: project_id is outside your org's MCP project scope.",[`Allowed projects: ${e.project_scope.length} project${1===e.project_scope.length?"":"s"} configured by your admin`,"Use atoms_list_projects to see which projects you can access in this session"]))}let n,a;try{a=await Se(),n=Ee()}catch{return t(i)}const s=await async function(e,t){const i=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Ve,r=new Date,n=new Date(r.getTime()-Be);try{const{count:a,error:s}=await t.from("mcp_rate_limits").select("id",{count:"exact",head:!0}).eq("user_id",e).gte("requested_at",n.toISOString());if(s)throw new Error(s.message);if((a??0)>=i){const{data:i,error:a}=await t.from("mcp_rate_limits").select("requested_at").eq("user_id",e).gte("requested_at",n.toISOString()).order("requested_at",{ascending:!0}).limit(1).maybeSingle();if(a)throw new Error(a.message);const s=(i?new Date(i.requested_at).getTime():r.getTime())+Be-r.getTime();return{allowed:!1,retryAfterSeconds:Math.max(1,Math.ceil(s/1e3))}}t.from("mcp_rate_limits").insert({user_id:e,requested_at:r.toISOString()}).then(({error:e})=>{e&&process.stderr.write(`[rate-limiter] insert failed: ${e.message}\n`)});const o=new Date(r.getTime()-2*Be);return t.from("mcp_rate_limits").delete().eq("user_id",e).lt("requested_at",o.toISOString()).then(()=>{}),{allowed:!0}}catch(e){return process.stderr.write(`[rate-limiter] DB check failed (${e instanceof Error?e.message:String(e)}), falling back to allow.\n`),{allowed:!0}}}(n,a);if(!s.allowed)return Ht(jt(s.retryAfterSeconds));if("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN){const e=i?.project_id;if("string"==typeof e)try{const{requireWriteAccess:t}=await Promise.resolve().then(()=>(Ce(),je));await t(a,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(Ct(),lt));return Ht(e("Viewer (lockdown mode: read access requires editor or admin)"))}}}const o=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let d,c="success";try{const e=await t(i),r=e;if(!0===r?.isError){c="error";const e=r?.content;if(e?.[0]?.text)try{d=JSON.parse(e[0].text).message}catch{}}return e}catch(e){throw c="error",d=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:i,status:c,duration_ms:o(),error_msg:d,project_id:i.project_id,session_id:ta,client_name:ia};try{!function(e,t,i){const r=We(i.params);e.from("mcp_audit_log").insert({user_id:t,tool_name:i.tool_name,params:r,status:i.status,duration_ms:i.duration_ms,error_msg:i.error_msg??null,project_id:i.project_id??null,session_id:i.session_id??null,client_name:i.client_name??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await Se(),n,t)}catch{}}}}function da(){return ta}function ca(){return ra}function la(){return ia}R(aa,{ATOMS_MCP_SERVER_VERSION:()=>Zn,getMcpActor:()=>ca,getMcpClientName:()=>la,getMcpSessionId:()=>da,server:()=>Xn});var ma=C({"src/server.ts"(){Ge(),Ye(),Z(),Xe(),z(),W(),ot(),dt(),Ce(),Ct(),Rt(),Yn=v(import.meta.url),Kn=Yn("../package.json"),Zn=Kn.version,Xn=new b({name:"atoms-mcp-server",version:Zn}),ea=(e,t,i)=>{if(G(e))return Xn.registerTool(e,t,i)},ta=m(),ia=et(process.env.ATOMS_CLIENT_NAME),ra=function(){const e=et(ia);return"cursor"===e?"mcp_cursor":"copilot"===e?"mcp_copilot":"mcp_claude"}(),ea("atoms_status",{title:"ATOMS MCP Health Check",description:'Check the health and authentication status of the ATOMS MCP server.\n\nCall this FIRST if other atoms tools fail or return auth errors.\nThis tool works WITHOUT authentication — it checks whether credentials\nexist and are valid, and tells the user exactly what to do if not.\n\nArgs: None\n\nReturns:\n { status: "authenticated"|"not_authenticated"|"expired", email, message, next_steps }\n\nExamples:\n - "Is ATOMS MCP working?" → atoms_status()\n - "Why are atoms tools failing?" → atoms_status()',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{try{const{readCredentials:e,isTokenValid:t}=await Promise.resolve().then(()=>(ce(),X)),i=await e();if(!i)return{content:[{type:"text",text:JSON.stringify({status:"not_authenticated",message:"No ATOMS credentials found. You need to login first.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp login","3. Complete the login in your browser","4. Restart Claude Desktop (quit and reopen)","5. Try your query again"]},null,2)}]};if(!t(i))try{const{getValidToken:e}=await Promise.resolve().then(()=>(ve(),_e)),{email:t}=await e(),{invalidateClient:i}=await Promise.resolve().then(()=>(Ce(),je));return i(),{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:t,message:"Token was expired but has been refreshed. You're good to go!"},null,2)}]}}catch{return{content:[{type:"text",text:JSON.stringify({status:"expired",email:i.user_email??"unknown",message:"Your session has expired and could not be refreshed.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp logout","3. Run: npx @atoms-tech/atoms-mcp login","4. Complete the login in your browser","5. Restart Claude Desktop (quit and reopen)"]},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:i.user_email??"unknown",message:"ATOMS MCP is connected and authenticated. All tools are ready."},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({status:"error",message:`Health check failed: ${e instanceof Error?e.message:String(e)}`,next_steps:["1. Open a terminal","2. Run: npx @atoms-tech/atoms-mcp login","3. Restart Claude Desktop"]},null,2)}]}}}),ea("atoms_list_projects",{title:"List ATOMS Projects",description:'List all projects the authenticated user has access to.\n\nThis is the ENTRY POINT tool. Call this first to discover project IDs,\nthen use those IDs with all other tools.\n\nArgs: None\n\nReturns:\n { status: "success", data: [{ id, name, description, org_id, created_at }] }\n\nExamples:\n - "What projects do I have?" → atoms_list_projects()\n - "Show my projects" → atoms_list_projects()\n\nWorkflow:\n atoms_list_projects → atoms_list_items(project_id) → atoms_get_item(project_id, item_id)',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(Qt(),zt));return e()})),ea("atoms_list_items",{title:"List ATOMS Items",description:'List items in an ATOMS project with optional type/domain/level filters.\n\nThis is the primary ENTRY POINT for discovering items. Use it to browse\nproject contents before drilling into specific items with atoms_get_item.\n\nArgs:\n - project_id (string, UUID): The project to list items from\n - type (string, optional): Filter: requirement|test-case|note|table\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - limit (number, optional): Max results, 1-200 (default 50)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { status: "success", data: [{ id, title, type, status, domains, level }], meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me all requirements" → atoms_list_items(project_id, type="requirement")\n - "What test cases exist?" → atoms_list_items(project_id, type="test-case")\n\nErrors:\n - "Project not found" → verify project_id\n - "Access denied" → check org membership',inputSchema:{project_id:h.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:h.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:h.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:h.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:h.number().int().min(0).default(0).describe("Pagination offset (default 0)"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:h.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns items as they were at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(Kt(),Gt));return t(e)})),ea("atoms_get_item",{title:"Get ATOMS Item Details",description:'Get full details of a single item including relationships, test history, and ownership.\n\nUse after atoms_list_items or atoms_search to drill into a specific item.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID (e.g., "REQ-001", "TC-050")\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\nExamples:\n - "Show me requirement REQ-001" → atoms_get_item(project_id, "REQ-001")\n - "Get test case details" → atoms_get_item(project_id, "TC-050")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID. Returns the item as it was at that baseline's moment. Mutually exclusive with as_of."),as_of:h.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns the item as it was at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(ei(),Zt));return t(e)})),ea("atoms_search",{title:"Search ATOMS Items",description:'Full-text search across items in a project. Searches title, body, and summary.\n\nAlternative entry point to atoms_list_items when you know what you\'re looking for.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Search text (max 1000 chars)\n - type (string, optional): Filter by type\n - asset (string, optional): Filter to items with at least one run on the given asset\n (VIN, module, lot, ...). Case-sensitive exact match.\n - limit (number, optional): Max results, 1-100 (default 25)\n\nReturns:\n Matching items with @basic fields, ranked by relevance.\n\nExamples:\n - "Find braking requirements" → atoms_search(project_id, "braking system")\n - "Search for safety tests" → atoms_search(project_id, "safety", type="test-case")\n - "Tests that ran on this VIN" → atoms_search(project_id, "", asset="WEV...0005")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),query:h.string().min(1).max(1e3).describe("Search text"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),asset:h.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:h.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID. Searches within the project state at that baseline's moment.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(ri(),ti));return t(e)})),ea("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:'Meaning-based search across items using pgvector embeddings (GTE-small, 384d).\n\nUse when atoms_search (exact/substring) misses conceptually related items.\nBest for natural-language concept queries; atoms_search is better for exact phrases or IDs.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Natural-language concept query (max 1000 chars)\n - type (string, optional): Filter by type\n - limit (number, optional): Max results, 1-50 (default 10)\n\nReturns:\n Semantically similar items ranked by cosine similarity.\n\nExamples:\n - "Find braking-related requirements" → atoms_semantic_search(project_id, "braking deceleration stopping distance")\n - "Safety-related test cases" → atoms_semantic_search(project_id, "hazard risk mitigation safety", type="test-case")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),query:h.string().min(1).max(1e3).describe("Natural-language concept query"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:h.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(si(),ni));return t(e)})),sa({appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:'Find requirements without linked test cases (coverage gaps).\n\nEssential for compliance reporting in safety-critical industries.\n\nIn MCP App hosts (Claude, ChatGPT), renders a visual coverage heatmap.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to analyze\n - domain (string, optional): Filter by domain\n - level (string, optional): Filter by level\n - baseline_id (string, UUID, optional): coverage at that baseline\'s moment\n - as_of (string ISO 8601, optional): coverage at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n { covered, uncovered, total, coverage_percent, uncovered_items: [...] }\n\nExamples:\n - "What\'s our test coverage?" → atoms_get_coverage(project_id)\n - "Safety coverage gaps?" → atoms_get_coverage(project_id, domain="Safety")\n - "Coverage at PDR submission" → atoms_get_coverage(project_id, baseline_id="...")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),domain:h.string().max(64).optional().describe("Filter by domain tag"),level:h.string().max(32).optional().describe("Filter by level"),baseline_id:h.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:h.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:oa("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(ci(),oi));return t(e)})}),ea("atoms_get_history",{title:"Get Item Change History",description:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_<client>) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID"),limit:h.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(pi(),li));return t(e)})),sa({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Shows parent-child relationships\nand requirement-to-test-case verification links.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive pan/zoom diagram.\nFalls back to Mermaid text for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to visualize\n - root_item_id (string, optional): Start node (default: all roots)\n - depth (number, optional): Max depth (default 3, max 10)\n - include_tests (boolean, optional): Show test case links (default true)\n - baseline_id (string, UUID, optional): render the graph at that baseline's moment\n - as_of (string ISO 8601, optional): render the graph at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n Mermaid graph string.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),root_item_id:h.string().max(20).optional().describe("Root item ID to start from"),depth:h.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:h.boolean().default(!0).describe("Include test case links"),baseline_id:h.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:h.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:oa("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(bi(),yi));return t(e)})}),ea("atoms_create_item",{title:"Create ATOMS Item",description:'Create a new requirement, test case, or note in a project.\n\nRequires editor or admin role. Changes are logged with AI actor attribution.\n\nArgs:\n - project_id (string, UUID): Target project\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_ids (string[], optional): Parent item IDs to link\n - fields (object, optional): Project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field first.\n\nReturns:\n Created item with generated ID (e.g., "REQ-058")\n\nSide effects:\n - Logs to change_history with actor=\'mcp_<client>\'\n - Creates relationships if parent_ids provided',inputSchema:{project_id:h.string().uuid().describe("UUID of the target project"),type:h.enum(["requirement","test-case","note"]).describe("Item type"),title:h.string().min(1).max(500).describe("Item title"),body:h.string().max(5e4).optional().describe("Rich text body"),summary:h.string().max(2e3).optional().describe("Brief summary"),domains:h.array(h.string().max(64)).max(20).optional().describe("Domain tags"),level:h.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:h.array(h.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:h.record(h.string().max(60),h.string().max(1e4)).optional().describe("Project-field values keyed by defined field name"),echo:h.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>($i(),Mi));return t(e)})),ea("atoms_update_item",{title:"Update ATOMS Item",description:'Update an existing item\'s fields. Only provided fields are changed.\n\nRequires editor or admin role. Logs old/new data diff to change history.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to update\n - title, body, summary, domains, level, status: Fields to update (all optional)\n - fields (object, optional): Project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field; merged per key, "" clears a key\n - expected_updated_at (string, optional): Pass metadata.updated_at from atoms_get_item to reject stale writes\n\nReturns:\n Updated item.',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).optional().describe("Item ID (single form)"),title:h.string().min(1).max(500).optional().describe("New title"),body:h.string().max(5e4).optional().describe("New body"),summary:h.string().max(2e3).optional().describe("New summary"),domains:h.array(h.string().max(64)).max(20).optional().describe("New domain tags"),level:h.string().max(32).optional().describe("New level"),status:h.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status"),fields:h.record(h.string().max(60),h.string().max(1e4)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),expected_updated_at:tt.optional().describe("metadata.updated_at value from atoms_get_item; rejects stale writes"),echo:h.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:h.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:h.array(h.object({item_id:h.string().min(1).max(20),title:h.string().min(1).max(500).optional(),body:h.string().max(5e4).optional(),summary:h.string().max(2e3).optional(),domains:h.array(h.string().max(64)).max(20).optional(),level:h.string().max(32).optional(),status:h.enum(["passed","failed","blocked","not-run"]).optional(),fields:h.record(h.string().max(60),h.string().max(1e4)).optional(),expected_updated_at:tt.optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:h.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:h.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(Wi(),Pi));return t(e)})),ea("atoms_delete_item",{title:"Delete ATOMS Item",description:'Soft-delete an item (sets deleted_at, preserves for audit trail).\n\nRequires editor or admin role. The item is never truly removed.\n\nWhen ATOMS_MCP_REQUIRE_CONFIRMATION is set on the server, this tool uses a\ntwo-step flow: the first call returns a preview + confirmation_token; the\nsecond call (with the token) executes. Tokens expire in 60s and are bound\nto (tool, project_id, item_id).\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to delete\n - confirmation_token (string, optional): Token from a prior preview call\n\nReturns:\n Confirmation with deleted item summary, or { status: "confirmation_required",\n preview, confirmation_token } when the confirmation gate is active.',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},oa("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(er(),Ki));return t(e)})),ea("atoms_restore_item",{title:"Restore ATOMS Item",description:'Undo a soft-delete — restores an item that was previously deleted with atoms_delete_item.\n\nOnly works on items that have been soft-deleted (still in the database with deleted_at set).\nHas no effect if the item is not deleted. Logs the restoration to change_history.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): ID of the deleted item to restore\n\nReturns:\n Confirmation with the restored item\'s title and type.\n\nExamples:\n - "Restore the deleted requirement REQ-042" → atoms_restore_item(project_id, "REQ-042")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().max(256).describe("ID of the soft-deleted item to restore")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(rr(),tr));return t(e)})),ea("atoms_link_items",{title:"Link ATOMS Items",description:"Add or remove relationships between items.\n\nSupports: parent, child, related, verifies, verified_by.\nUpdates both items' JSONB data and the shadow table.\n\nArgs:\n - project_id (string, UUID): Project containing both items\n - from_id (string): Source item\n - to_id (string): Target item\n - type (string): parent|child|related|verifies|verified_by\n - action (string): add|remove\n - expected_from_updated_at / expected_to_updated_at (string, optional): pass metadata.updated_at values from atoms_get_item to reject stale link commands\n\nReturns:\n Updated relationship state for both items.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),from_id:h.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:h.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:h.enum(["parent","child","related","verifies","verified_by"]).optional().describe("Relationship type"),action:h.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:tt.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:tt.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:h.boolean().optional().describe("false → lean response"),reason:h.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:h.array(h.object({action:h.enum(["add","remove"]),from_id:h.string().min(1).max(20),to_id:h.string().min(1).max(20),type:h.enum(["parent","child","related","verifies","verified_by"]),expected_from_updated_at:tt.optional(),expected_to_updated_at:tt.optional()})).optional().describe("Array form: batch relationship ops. Always atomic with DAG cycle detection."),idempotency_key:h.string().max(128).optional().describe("Safe retry key (24h TTL)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(sr(),nr));return t(e)})),sa({appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:"Bulk create multiple items in a single tool call. Essential for AI agents\nthat generate 20+ requirements at once.\n\nChecks write access once, generates sequential IDs, batch inserts all items,\nand reports per-item errors without aborting the entire batch.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive results table.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Target project\n - items (array): Up to 100 items to create, each with:\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_id (string, optional): Parent item ID to link\n\nReturns:\n { created: number, items: [{ id, title, type }], errors: [] }\n\nLimits:\n - Maximum 100 items per call\n - If any item fails, others still succeed — errors reported separately\n\nSide effects:\n - Logs to change_history with actor='mcp_<client>' for each created item\n - Creates parent relationships for items with parent_id",inputSchema:{project_id:h.string().uuid().describe("UUID of the target project"),items:h.array(h.object({type:h.enum(["requirement","test-case","note"]).describe("Item type"),title:h.string().min(1).max(500).describe("Item title"),body:h.string().max(5e4).optional().describe("Rich text body"),summary:h.string().max(2e3).optional().describe("Brief summary"),domains:h.array(h.string().max(64)).max(20).optional().describe("Domain tags"),level:h.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:h.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:oa("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(lr(),dr));return t(e)})}),ea("atoms_record_test_result",{title:"Record Test Result",description:"Record a pass/fail/blocked result for a test case.\n\nAppends to canonical items.data.runs and projects test_results from that\nhistory. Use atoms_get_item to see all results.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., \"TC-001\")\n - result (string): passed|failed|blocked|not-run\n - note (string, optional): Reason or comment for this result\n - asset (string, optional): Asset identifier this run was executed against\n (VIN, module ID, lot number, serial number, etc). Max 200 chars.\n Auto-trimmed; empty/whitespace is treated as omitted. If the asset\n name does not yet exist in the project, it is auto-registered.\n\nReturns:\n Recorded result with timestamp. When asset is provided, also returns\n asset_id and asset_created.\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts into assets table if asset name is new in this project\n - Logs to change_history with actor='mcp_<client>'",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:h.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:h.string().max(1e3).optional().describe("Reason or comment for this result"),asset:h.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new.")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(_r(),mr));return t(e)})),ea("atoms_record_test_results",{title:"Record Test Results (bulk)",description:'Record many runs on one test case in a single atomic call.\n\nOptimized for multi-asset campaigns. Each entry can have its own asset and\nresult. Asset lookup-or-create happens per entry; new asset names are\nauto-registered. Runs are appended to canonical items.data.runs, then\ntest_results is projected from that history. The whole call is one DB\ntransaction; any entry failure rolls back the rest.\n\nUse the singular atoms_record_test_result for one-off runs.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., "TC-001")\n - results (array, 1-100 entries): Each entry has:\n - asset (string, optional): Asset identifier (VIN, module ID, lot)\n - result (string, required): passed|failed|blocked|not-run\n - note (string, optional): Run note\n - date (string, optional): ISO 8601 datetime, default now()\n\nReturns:\n Per-entry outcomes with asset_id, asset_created, run_at, ok flags.\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts new rows into assets for any asset name not already registered\n - Logs a single change_history entry summarizing the batch',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:h.array(h.object({asset:h.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:h.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:h.string().max(500).optional().describe("Run note"),date:h.string().optional().describe("ISO 8601 datetime (default: now())")})).min(1).max(100).describe("1 to 100 result entries on this test case")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_record_test_results",async e=>{const{recordTestResultsBulkHandler:t}=await Promise.resolve().then(()=>(br(),ur));return t(e)})),sa({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:'Walk the traceability graph from a starting item.\n\nAnswers questions like "which requirements does TC-003 verify?" or\n"if I change REQ-001, what\'s affected downstream?"\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive graph visualization.\nFalls back to flat list for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Starting item ID\n - direction (string): upstream|downstream|both\n - upstream: follow parent/verifies links (dependencies)\n - downstream: follow child/verified_by links (dependents)\n - both: trace in both directions\n - depth (number, optional): Max traversal depth (default 5, max 10)\n - relationship_types (string[], optional): Filter to specific types (parent, child, related, verifies, verified_by, mitigated_by, mitigates)\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], total_count }\n\nExamples:\n - "What does TC-003 verify?" → atoms_trace(project_id, "TC-003", "upstream")\n - "What\'s affected by REQ-001?" → atoms_trace(project_id, "REQ-001", "downstream")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Starting item ID"),direction:h.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:h.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:h.array(h.enum(["parent","child","related","verifies","verified_by","mitigated_by","mitigates"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:oa("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(kr(),Sr));return t(e)})}),ea("atoms_list_assets",{title:"List Project Assets",description:"List asset identifiers registered in a project.\n\nAssets are free-form per-instance IDs (VINs, module names, lot numbers,\nserial numbers) that test runs are tagged against. They are auto-registered\nthe first time they appear on a run via atoms_record_test_result.\n\nArgs:\n - project_id (string, UUID): Project to list assets for\n - include_archived (boolean, optional): Include archived assets (default false)\n\nReturns:\n { assets: [{ id, name, archived_at, created_at }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),include_archived:h.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(Ar(),Ir));return t(e)})),ea("atoms_list_variables",{title:"List Project Variables",description:"List all parameterized variables defined in a project.\n\nVariables are shared values (e.g., backup_camera_latency = 2s) that can be\nreferenced in requirement bodies as {variable_name}.\n\nArgs:\n - project_id (string, UUID): Project to list variables for\n - baseline_id (string, UUID, optional): list variables as they were at that baseline\n - as_of (string ISO 8601, optional): list variables as they were at that moment\n\nReturns:\n { variables: [{ id, name, value, unit, description }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:h.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>($r(),Or));return t(e)})),ea("atoms_get_variable",{title:"Get Project Variable",description:'Get a specific variable by name, including which items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name (e.g., "backup_camera_latency")\n - baseline_id (string, UUID, optional): get the variable as it was at that baseline\n - as_of (string ISO 8601, optional): get the variable as it was at that moment\n\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),variable_name:h.string().min(1).max(64).describe("Variable name"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:h.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>($r(),Or));return t(e)})),ea("atoms_update_variable",{title:"Update Project Variable",description:"Update a variable's value, unit, or description.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name\n - value (string, optional): New value\n - unit (string, optional): Unit abbreviation (e.g., 's', 'Hz')\n - description (string, optional): Human-readable description\n\nReturns:\n { variable }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),variable_name:h.string().min(1).max(64).describe("Variable name"),value:h.string().max(500).optional().describe("New value"),unit:h.string().max(32).optional().describe("Unit abbreviation"),description:h.string().max(2e3).optional().describe("Description")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>($r(),Or));return t(e)})),ea("atoms_create_variable",{title:"Create Project Variable",description:'Create one or many parameterized variables for a project.\n\nSingle form: provide name + value.\nArray form: provide variables[] for bulk creation (one atomic INSERT).\n\nVariables can then be embedded in requirement bodies as {variable_name}.\n\nArgs (single form):\n - project_id (string, UUID): Project to add the variable to\n - name (string): Variable name, letters, digits, underscores; must start with letter/underscore\n - value (string): Initial value (e.g., "100", "true", "nominal")\n - unit (string, optional): Unit abbreviation (e.g., "Hz", "ms", "m/s²")\n - description (string, optional): Human-readable description\n - echo (bool, optional): false → lean {name} response (default true)\n\nArgs (array form):\n - project_id (string, UUID): Project UUID\n - variables[]: Array of { name, value, unit?, description? }\n - echo (bool, optional): false → lean {name} list (default true)\n - idempotency_key (string, optional): Dedup key\n\nReturns (single): { variable, message }\nReturns (array): { batch_id, created, variables, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).optional().describe("Variable name (single form)"),value:h.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:h.string().max(32).optional().describe("Unit abbreviation"),description:h.string().max(2e3).optional().describe("Description"),echo:h.boolean().optional().describe("false → lean response (default true)"),variables:h.array(h.object({name:h.string().min(1).max(64).describe("Variable name"),value:h.string().min(1).max(500).describe("Initial value"),unit:h.string().max(32).optional().describe("Unit abbreviation"),description:h.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:h.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>($r(),Or));return t(e)})),ea("atoms_delete_variable",{title:"Delete Project Variable",description:"Delete a project variable. Refuses by default if any items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - name (string): Variable name to delete\n - force (bool, optional): Delete even if items still reference it (default false)\n\nReturns:\n { deleted, name, referenced_by_items, warning? }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Variable name to delete"),force:h.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},oa("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>($r(),Or));return t(e)})),ea("atoms_list_domains",{title:"List Project Domains",description:"List all domain tags registered in a project's taxonomy, with item counts.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { domains: [{ name, item_count }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(zr(),Pr));return t(e)})),ea("atoms_create_domain",{title:"Create Project Domain",description:'Register a new domain tag in the project taxonomy.\n\nOnce created, items can be tagged with this domain via atoms_create_item or atoms_update_item.\n\nArgs:\n - project_id (string, UUID): Project to add the domain to\n - name (string): Domain name (lowercased automatically, e.g., "safety", "can-bus")\n\nReturns:\n { domain: { name }, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(zr(),Pr));return t(e)})),ea("atoms_list_levels",{title:"List Project Levels",description:"List the project's level taxonomy in order, with each level's L# (positional index) and item count.\n\nArgs:\n - project_id (string, UUID): Project to list levels for\n\nReturns:\n { levels: [{ name, prefix, item_count }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(Ai(),vi));return t(e)})),ea("atoms_create_level",{title:"Create Project Level",description:'Register a new level in the project taxonomy so items can be tagged with it and it shows in the Strata view. Appended to the ordered level list; its L# is the next index. Names are user-defined labels (lowercased automatically); matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID): Project to add the level to\n - name (string): Level name, e.g. "feature", "system", "subsystem"\n\nReturns:\n { level: { name, prefix }, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(Ai(),vi));return t(e)})),ea("atoms_list_fields",{title:"List Project Fields",description:'List the project\'s custom field definitions (project-scoped key-value slots on items, e.g. "Verification Method"), with counts of items carrying a value.\n\nField values are set per item via atoms_create_item / atoms_update_item fields.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { fields: [{ name, item_count }], total }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(qi(),Oi));return t(e)})),ea("atoms_create_field",{title:"Create Project Field",description:'Define a project custom field so items can carry a value for it (shown as a Matrix column, e.g. "Verification Method").\n\nThe name keeps its casing; uniqueness is case-insensitive. Fields hold string values only; they never carry validation rules, permissions, or workflow logic.\n\nArgs:\n - project_id (string, UUID): Project to define the field in\n - name (string): Field name, 1-60 characters (e.g. "Verification Method", "Essential Output?")\n\nReturns:\n { field: { name }, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(60).describe("Field name (display name, 1-60 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(qi(),Oi));return t(e)})),ea("atoms_update_domain",{title:"Rename Project Domain",description:"Rename a domain tag. Updates the taxonomy and propagates to all tagged items.\n\nUse dry_run=true first to see how many items will be affected before committing.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Current domain name\n - new_name (string): New domain name\n - dry_run (bool, optional): If true, return impact count without making changes (default false)\n\nReturns (dry_run=false):\n { domain: { name }, renamed_from, items_updated, message }\n\nReturns (dry_run=true):\n { dry_run: true, rename: { from, to }, items_affected, message }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Current domain name"),new_name:h.string().min(1).max(64).describe("New domain name"),dry_run:h.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(zr(),Pr));return t(e)})),ea("atoms_delete_domain",{title:"Delete Project Domain",description:"Delete a domain tag from the project taxonomy.\n\nRefuses by default if any items are tagged with it. With force=true, deletes the\ndomain and strips the tag from all items.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Domain name to delete\n - force (bool, optional): Strip from items and delete anyway (default false)\n\nReturns:\n { deleted, name, items_updated, message }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Domain name to delete"),force:h.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},oa("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(zr(),Pr));return t(e)})),sa({appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:'One-call project health and compliance dashboard.\n\nReturns item counts by type, test execution status, requirement coverage\n(overall and by domain), and recent change activity.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive dashboard with charts.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project to summarize\n\nReturns:\n { project_name, counts, test_status, coverage, coverage_by_domain, recent_changes, last_updated }\n\nExamples:\n - "Give me a compliance snapshot" → atoms_project_summary(project_id)\n - "How\'s our test coverage?" → atoms_project_summary(project_id)',inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:oa("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(Yr(),Jr));return t(e)})}),sa({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:'View and filter items in an ATOMS project with a visual browser.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive filterable list\nwith expandable item details. Falls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to browse\n - type (string, optional): Filter by type (requirement, test-case, note, table)\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - query (string, optional): Full-text search query\n - limit (number, optional): Max results (default 25, max 100)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { items: [...], filters: { domains, levels, types }, meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me the requirements" → atoms_browse(project_id, type="requirement")\n - "Browse safety items" → atoms_browse(project_id, domain="Safety")\n - "Find braking requirements" → atoms_browse(project_id, query="braking")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:h.string().max(64).optional().describe("Filter by domain tag"),level:h.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:h.string().max(1e3).optional().describe("Full-text search query"),limit:h.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:h.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:oa("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(nn(),Kr));return t(e)})}),ea("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:'Analyze the blast radius of changing a specific item.\n\nTraverses the relationship graph from the given item and returns every item that\nwould be affected by a change — with their types, depths, and full relationship paths.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to analyze (e.g., "REQ-001")\n - direction (string, optional): "downstream" (default) | "upstream" | "both"\n - downstream: what this item affects (children, verified_by)\n - upstream: what affects this item (parents, verifies)\n - both: full bidirectional traversal\n - depth (integer, optional): Max traversal depth. Omit for full depth (all reachable nodes).\n - include_variable_refs (boolean, optional): Reserved for future variable-aware impact. Default true.\n\nReturns:\n { root: { item_id, title, type }, impacted_items: [{ item_id, title, type, depth, relationship_path }], summary: { total_impacted, by_type, max_depth_reached } }\n\nExamples:\n - "What breaks if I change REQ-001?" → atoms_impact_analysis(project_id, "REQ-001")\n - "What\'s upstream of TC-005?" → atoms_impact_analysis(project_id, "TC-005", direction="upstream")\n - "Show direct dependencies only" → atoms_impact_analysis(project_id, "REQ-001", depth=1)\n\nErrors:\n - "Item not found" → verify item_id exists in the project',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:h.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:h.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:h.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(on(),an));return t(e)})),ea("atoms_list_baselines",{title:"List ATOMS Baselines",description:"List named baselines (named project snapshots) for a project, newest first.\n\nA baseline is a labeled moment in time. Use atoms_create_baseline to make one,\natoms_diff_baselines to compare two, and atoms_restore_baseline to roll back.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),limit:h.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:h.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(Hn(),cn));return t(e)})),ea("atoms_create_baseline",{title:"Create ATOMS Baseline",description:"Create a named baseline (snapshot label) at the current moment for a project.\n\nThe baseline records a name + timestamp. It does NOT copy item data; the project\nstate at that moment is reconstructed via temporal queries against item_revisions.\nNames must be unique per project (case-insensitive).",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:h.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(Hn(),cn));return t(e)})),ea("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:"Lock a baseline so it becomes audit-grade immutable. Admin only. One-way: there is no unlock.\n\nAfter locking, the baseline's name, description, and snapshot_at cannot be changed,\nand it cannot be deleted. Use for regulatory submissions and DRBs.",inputSchema:{baseline_id:h.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(Hn(),cn));return t(e)})),ea("atoms_diff_baselines",{title:"Diff ATOMS Baselines",description:"Compute the diff between two baselines: which items were added, removed, or modified.\n\nReturns a summary plus a paginated items array. Pass detail=true to include\nper-item field-level diffs (slower for large projects).",inputSchema:{baseline_a_id:h.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:h.string().uuid().describe("UUID of the second (newer) baseline"),detail:h.boolean().default(!1).describe("Include per-item field-level diffs (default false)"),limit:h.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:h.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(Hn(),cn));return t(e)})),ea("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:"Restore project state to a baseline. Admin only. Preview-by-default.\n\nCall with confirm=false (default) for a dry run that returns items_to_restore count.\nCall with confirm=true to execute: each item present at the baseline gets a new\nrevision matching its historical state, event_source='restore'. Items added AFTER\nthe baseline are NOT deleted. Always recoverable via further history.",inputSchema:{baseline_id:h.string().uuid().describe("UUID of the baseline to restore from"),confirm:h.boolean().default(!1).describe("Set true to execute; false (default) returns a preview")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},oa("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(Hn(),cn));return t(e)})),ea("atoms_create_analysis",{title:"Create HARA / DFMEA Analysis",description:'Create a new safety analysis (HARA or DFMEA) with one empty row per source requirement.\n\nRequires editor or admin role. Structure matches analyses created in the ATOMS web app.\n\nArgs:\n - project_id (string, UUID): Target project\n - subtype (string): hara | dfmea\n - title (string, optional): Analysis title (default "New HARA" / "New DFMEA")\n - source_req_ids (string[], optional, max 50): Requirement IDs to seed rows from.\n Each must exist, be a plain requirement, and not itself be an analysis row.\n - revision (string, optional): Revision label (default "1.0")\n\nReturns:\n { id (e.g. "HARA-001" / "DFMEA-001"), subtype, title, revision, rows: [{ id, source_req }],\n link_warnings?: [{ row_id, source_req, message }], warning? }\n rows lists every created row. If any row could not be attached to the analysis, it is\n named in link_warnings and warning explains the repair (atoms_link_items with type\n \'parent\', from_id=<row id>, to_id=<analysis id>); such rows will not appear in\n atoms_get_analysis until relinked.\n\nSide effects:\n - Creates the analysis parent item plus one row item (SG-nnn / FM-nnn) per source requirement\n - Links each row to the parent (dual-written to the relationship shadow table)\n - Logs each created item to change_history with actor=\'mcp_<client>\'',inputSchema:{project_id:h.string().uuid().describe("UUID of the target project"),subtype:h.enum(["hara","dfmea"]).describe("Analysis subtype"),title:h.string().min(1).max(500).optional().describe("Analysis title"),source_req_ids:h.array(h.string().min(1).max(20)).max(50).optional().describe("Requirement IDs to seed rows from (0-50)"),revision:h.string().min(1).max(32).optional().describe("Revision label (default 1.0)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},oa("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(na(),Pn));return t(e)})),ea("atoms_fill_row",{title:"Fill Analysis Row Fields",description:"Fill fields on one HARA / DFMEA analysis row (SG-nnn / FM-nnn).\n\nRequires editor or admin role. Written fields are marked as MCP-sourced so the\nweb app shows their provenance. The computed level (ASIL / RPN) is derived and\nnever stored.\n\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. \"SG-001\", \"FM-003\")\n - fields (object): Field name to value map. Allowed keys:\n hara: failure_mode, operating_scenario, severity (S0-S3), exposure (E0-E4),\n controllability (C0-C3), safe_state, ftti, rationale, effect, title\n dfmea: failure_mode, cause, severity (1-10), occurrence (1-10), detection (1-10),\n rationale, effect\n 'effect' writes the row's long text body. dfmea failure_mode also becomes the row title.\n dfmea ratings accept numbers and are stored as strings.\n\nReturns:\n { row_id, subtype, written_fields, computed_level, asil_propagated_to? }\n\nSide effects:\n - Saves the row with stale-write protection and logs to change_history\n - hara only: if the row is linked and its computed ASIL changed, updates each\n linked requirement's asil / asil_source (each update is history-logged)",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),row_id:h.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),fields:h.record(h.string().max(64),h.union([h.string().max(5e4),h.number()])).describe("Field name to value map (see description for allowed keys per subtype)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(na(),Pn));return t(e)})),ea("atoms_get_analysis",{title:"Get HARA / DFMEA Analysis",description:'Get a full analysis view: every row with its computed level (ASIL / RPN) and\ngap / critical / stale classifications, plus summary counts.\n\nClassifications match the ATOMS web app exactly (same rules, same thresholds).\n\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "DFMEA-002")\n\nReturns:\n { analysis: { id, title, subtype, scheme, revision },\n rows: [{ id, title, source_req, effect, <subtype fields>, computed_level, is_gap, gap_rule,\n is_critical, is_stale, mitigated_by, link_roles, approved, approved_at, mcp_fields }],\n counts: { rows, gaps, critical, stale, approved, linked } }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),analysis_id:h.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, DFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(na(),Pn));return t(e)})),ea("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:'Link a HARA / DFMEA row to the technical requirement that mitigates it.\n\nRequires editor or admin role.\n\nArgs:\n - project_id (string, UUID): Project containing both items\n - row_id (string): Analysis row ID (e.g. "SG-001", "FM-003")\n - req_id (string): Target requirement ID (must be a plain requirement, not an analysis row)\n - role (string, dfmea only, REQUIRED for dfmea): prevention | detection | mitigation.\n Must be omitted for hara rows.\n - override (boolean, optional, default false): hara only. When the target already\n carries a different asil, the call fails with a structured error\n (details.code=\'asil_conflict\') unless override=true; the override is\n history-logged like a dialog accept.\n\nReturns:\n { row_id, req_id, type: "mitigated_by", role, asil_written? }\n\nSide effects:\n - Adds the mitigated_by/mitigates relationship (JSONB + shadow table, one transaction)\n - hara only: writes the row\'s computed ASIL onto the target requirement\n (data.asil + data.asil_source) with a history entry recording previous/new values\n - dfmea: never modifies any field on the target requirement',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),row_id:h.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:h.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:h.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows; must be omitted for hara rows."),override:h.boolean().optional().describe("hara only: apply the row's ASIL over a conflicting existing value (history-logged)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(na(),Pn));return t(e)})),ea("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:'List only the gap rows of a HARA / DFMEA analysis, each naming the rule that matched.\n\nGap rules (identical to the web app):\n hara: unmitigated row with ASIL A-D ("asil <X> unmitigated")\n dfmea: unmitigated row with RPN >= 100 ("rpn >= 100") or severity >= 9 ("severity >= 9")\n\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "DFMEA-002")\n\nReturns:\n { analysis_id, subtype, gaps: [{ id, title, source_req, computed_level, rule }], count }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),analysis_id:h.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, DFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},oa("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(na(),Pn));return t(e)}))}});Z(),z(),Ce(),V();var pa=v(import.meta.url)("../package.json"),_a=process.argv.slice(2)[0];(async function(){switch(_a){case"login":{const{login:e}=await Promise.resolve().then(()=>(Le(),Re));try{const{email:t}=await e();process.stderr.write(`\n [32m✓[0m Authenticated as ${t}\n`),process.stderr.write(" [32m✓[0m Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" [1mNext steps:[0m\n"),process.stderr.write(" [36m$[0m claude mcp add atoms -- npx -y @atoms-tech/atoms-mcp\n"),process.stderr.write("\n Or add to Claude Desktop (Settings → MCP → Edit Config):\n"),process.stderr.write(' [90m{\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp"]\n }\n }\n }[0m\n\n')}catch(e){process.stderr.write(`\n [31m✗[0m ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>(ve(),_e));try{const{email:t,user_id:i}=await e();process.stderr.write(`\n [32m✓[0m Logged in as ${t}\n [90mUser ID: ${i}[0m\n\n`)}catch(e){process.stderr.write("\n [31m✗[0m Not authenticated.\n Run: npx @atoms-tech/atoms-mcp login\n\n"),process.exit(1)}break}case"logout":{const{clearCredentials:e}=await Promise.resolve().then(()=>(ce(),X));await e(),process.stderr.write("Logged out. Credentials removed.\n"),process.stderr.write("Run 'npx @atoms-tech/atoms-mcp login' to authenticate again.\n");break}case"--version":case"-v":process.stderr.write(`@atoms-tech/atoms-mcp v${pa.version}\n`);break;case"--help":case"-h":process.stderr.write("ATOMS MCP Server — AI agent integration for requirements management\n\nUsage:\n npx @atoms-tech/atoms-mcp Start MCP server (stdio)\n npx @atoms-tech/atoms-mcp login Authenticate with ATOMS.tech\n npx @atoms-tech/atoms-mcp logout Switch account / clear credentials\n npx @atoms-tech/atoms-mcp whoami Show current user\n npx @atoms-tech/atoms-mcp --version Show version\n");break;default:{process.stderr.write("[atoms-mcp] Starting MCP server via stdio...\n");try{const{getValidToken:e}=await Promise.resolve().then(()=>(ve(),_e)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch{process.stderr.write("[atoms-mcp] No credentials found. Starting login flow...\n");try{const{login:e}=await Promise.resolve().then(()=>(Le(),Re)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch(e){process.stderr.write(`[atoms-mcp] Login failed: ${e instanceof Error?e.message:String(e)}\n[atoms-mcp] Starting server without auth. Tools will fail until you run: npx @atoms-tech/atoms-mcp login\n`)}}try{const t=await Se(),i=Ee(),r=await async function(e,t){const i=process.env.ATOMS_MCP_ORG_ID?.trim();if(i)return i;const{data:r,error:n}=await e.from("org_members").select("org_id, joined_at").eq("user_id",t).order("joined_at",{ascending:!0}).limit(1).maybeSingle();return n?(process.stderr.write(`[atoms-mcp] Could not resolve session org: ${n.message}\n`),null):r?.org_id??null}(t,i),n=await async function(e,t,i){if(!i)return{role:null,is_member:!1,effective:P};const{data:r,error:n}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:i});return n?(process.stderr.write(`[atoms-mcp] mcp_resolve_policy failed (${n.code}): ${n.message}. Falling back to fail-closed policy.\n`),{role:null,is_member:!1,effective:N}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:P};const t=e,i="string"==typeof t.role?t.role:null,r=!0===t.is_member,n=t.effective??{},a=(e,t)=>Array.isArray(e)?e.filter(e=>"string"==typeof e):t,s=(e,t)=>"boolean"==typeof e?e:t,o=n.project_scope,d=Array.isArray(o)&&o.length>0?o.filter(e=>"string"==typeof e):null;return{role:i,is_member:r,effective:{read_only:s(n.read_only,P.read_only),lockdown:s(n.lockdown,P.lockdown),block_destructive:s(n.block_destructive,P.block_destructive),block_bulk_import:s(n.block_bulk_import,P.block_bulk_import),cross_project_browse:s(n.cross_project_browse,P.cross_project_browse),allowed_toolsets:a(n.allowed_toolsets,P.allowed_toolsets),forbidden_tools:a(n.forbidden_tools,P.forbidden_tools),project_scope:d,require_confirmation_for:a(n.require_confirmation_for,P.require_confirmation_for)}}}(r)}(t,i,r);e={effective:n.effective,role:n.role,org_id:r},L=e.effective,F=e.org_id,n.is_member&&r?process.stderr.write(`[atoms-mcp] Org policy loaded: org=${r.slice(0,8)}… role=${n.role??"?"} read_only=${n.effective.read_only} lockdown=${n.effective.lockdown}\n`):process.stderr.write("[atoms-mcp] No org membership detected — running with permissive default policy.\n")}catch(e){process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). Running with permissive default — RLS still enforces row-level access.\n`)}process.stderr.write(`[atoms-mcp] Tool registry: ${function(){const e=Q(),t=J(),i=[];i.push(e?"read-only":"read+write"),null===t?i.push("all toolsets"):(i.push(`toolsets=${[...t.allowed].sort().join(",")||"(none — only always-on tools)"}`),t.unknown.length>0&&i.push(`unknown=${t.unknown.join(",")}`));const r=process.env.ATOMS_MCP_PROJECT_ID?.trim();return r&&i.push(`project_scope=${r.slice(0,8)}…`),("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN)&&i.push("lockdown=on"),i.join(" | ")}()}\n`);const{server:t}=await Promise.resolve().then(()=>(ma(),aa)),i=new j;await t.connect(i),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}var e})().catch(e=>{process.stderr.write(`[atoms-mcp] Fatal: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)});
|
|
2
|
+
import e,{readFile as t,mkdir as i,writeFile as r,unlink as n}from"fs/promises";import{homedir as a}from"os";import s,{join as o}from"path";import{createClient as d}from"@supabase/supabase-js";import{createServer as c}from"http";import l,{randomUUID as m,randomBytes as p,createHash as _}from"crypto";import{fileURLToPath as u,URL as f}from"url";import{z as h}from"zod";import{registerAppTool as g,registerAppResource as y,RESOURCE_MIME_TYPE as w}from"@modelcontextprotocol/ext-apps/server";import{McpServer as b}from"@modelcontextprotocol/sdk/server/mcp.js";import{createRequire as v}from"module";import{StdioServerTransport as j}from"@modelcontextprotocol/sdk/server/stdio.js";var S,x,k,I,E,A,O,H=Object.defineProperty,D=Object.getOwnPropertyNames,R=(e,t,i)=>function(){if(i)throw i[0];try{return e&&(t=(0,e[D(e)[0]])(e=0)),t}catch(e){throw i=[e],e}},C=(e,t)=>{for(var i in t)H(e,i,{get:t[i],enumerable:!0})};function U(e){return O.get(e)}var M=R({"src/core/tool-catalog.ts"(){S=new Set(["atoms_status","atoms_list_projects"]),x=new Set(["atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_link_items","atoms_bulk_import","atoms_record_test_result","atoms_record_test_results","atoms_create_variable","atoms_update_variable","atoms_delete_variable","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_create_level","atoms_create_field","atoms_delete_field","atoms_create_baseline","atoms_lock_baseline","atoms_restore_baseline","atoms_create_analysis","atoms_fill_row","atoms_link_mitigation"]),k=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_field","atoms_restore_baseline"]),I=new Set(["atoms_bulk_import"]),E={items:["atoms_list_items","atoms_get_item","atoms_search","atoms_semantic_search","atoms_browse","atoms_get_history","atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_bulk_import"],traceability:["atoms_trace","atoms_link_items","atoms_export_mermaid","atoms_impact_analysis"],coverage:["atoms_get_coverage","atoms_record_test_result","atoms_record_test_results","atoms_project_summary","atoms_list_assets"],variables:["atoms_list_variables","atoms_get_variable","atoms_create_variable","atoms_update_variable","atoms_delete_variable"],domains:["atoms_list_domains","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_list_levels","atoms_create_level","atoms_list_fields","atoms_create_field","atoms_delete_field"],baselines:["atoms_list_baselines","atoms_create_baseline","atoms_lock_baseline","atoms_diff_baselines","atoms_restore_baseline"],analysis:["atoms_create_analysis","atoms_fill_row","atoms_get_analysis","atoms_link_mitigation","atoms_get_gaps"]},A=Object.keys(E),O=new Map;for(const[e,t]of Object.entries(E))for(const i of t)O.set(i,e)}});function T(e,t){if(S.has(t))return{allowed:!0};if(e.lockdown&&!new Set(["atoms_list_items","atoms_get_item","atoms_search","atoms_browse"]).has(t))return{allowed:!1,reason:"lockdown"};if(e.forbidden_tools.includes(t))return{allowed:!1,reason:"forbidden_tool"};if(e.read_only&&x.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&k.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&I.has(t))return{allowed:!1,reason:"block_bulk_import"};const i=U(t);return void 0===i||e.allowed_toolsets.includes(i)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function q(e,t){return T(e,t).allowed}function P(e){switch(e){case"lockdown":return"MCP is in lockdown mode for your role — only read-only browse is available.";case"read_only":return"Your org policy puts MCP in read-only mode. Mutating tools are not exposed.";case"block_destructive":return"Your org policy blocks destructive operations (delete tools).";case"block_bulk_import":return"Your org policy blocks bulk import.";case"forbidden_tool":return"This tool is on your org's forbidden list.";case"toolset_disabled":return"This tool's toolset is not enabled in your org policy."}}var $,N,L,F,W=R({"src/core/policy.ts"(){M()}}),V=R({"src/core/types.ts"(){$={read_only:!1,lockdown:!1,block_destructive:!1,block_bulk_import:!1,cross_project_browse:!0,allowed_toolsets:["items","traceability","coverage","variables","domains","baselines"],forbidden_tools:[],project_scope:null,require_confirmation_for:[]},N={read_only:!0,lockdown:!0,block_destructive:!0,block_bulk_import:!0,cross_project_browse:!1,allowed_toolsets:[],forbidden_tools:[],project_scope:[],require_confirmation_for:[]}}});function B(){return L}var z=R({"src/middleware/session-policy.ts"(){V(),L=$,F=null}});function J(){const e=process.env.ATOMS_MCP_TOOLSETS?.trim();if(!e)return null;const t=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===t.length)return null;const i=new Set,r=[];for(const e of t)A.includes(e)?i.add(e):r.push(e);return{allowed:i,unknown:r}}function Q(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function G(e){if(Q()&&x.has(e))return!1;if(S.has(e))return!0;const t=J();if(null===t)return q(B(),e);const i=U(e);return!!i&&!!t.allowed.has(i)&&q(B(),e)}var Y,K,Z=R({"src/middleware/tool-registry.ts"(){M(),W(),z()}}),X={};async function ee(){try{const e=await t(K,"utf-8"),i=JSON.parse(e);return i.access_token&&i.refresh_token?i:null}catch{return null}}async function te(e){await i(Y,{recursive:!0,mode:448}),await r(K,JSON.stringify(e,null,2),{mode:384})}async function ie(){const e=await ee();return!!e&&e.expires_at>Date.now()+6e4}function re(e){return e.expires_at>Date.now()+6e4}async function ne(){try{await n(K)}catch{}}function ae(){return K}C(X,{clearCredentials:()=>ne,getCredentialsPath:()=>ae,hasValidCredentials:()=>ie,isTokenValid:()=>re,readCredentials:()=>ee,writeCredentials:()=>te});var se,oe,de,ce=R({"src/auth/token-store.ts"(){Y=o(a(),".atoms"),K=o(Y,"credentials.json")}}),le={};function me(e){return e.trim().replace(/\/+$/,"")}C(le,{ATOMS_APP_URL:()=>de,ATOMS_SUPABASE_ANON_KEY:()=>oe,ATOMS_SUPABASE_URL:()=>se,resolveUrl:()=>me});var pe=R({"src/config.ts"(){se=me(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),oe=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",de=process.env.ATOMS_APP_URL??"https://atoms.tech"}}),_e={};async function ue(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=fe(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await ee();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' to connect your ATOMS account.");if(t.expires_at>Date.now()+6e4){const e=fe(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}process.stderr.write("[atoms-mcp] Refreshing access token...\n");const i=d(se,oe),{data:r,error:n}=await i.auth.refreshSession({refresh_token:t.refresh_token});if(n||!r.session)throw new Error(`Token refresh failed: ${n?.message??"No session returned"}. Re-run 'npx @atoms-tech/atoms-mcp login'.`);const a=r.session;return await te({access_token:a.access_token,refresh_token:a.refresh_token,expires_at:Date.now()+1e3*(a.expires_in??3600),user_email:a.user?.email}),{access_token:a.access_token,refresh_token:a.refresh_token,user_id:a.user?.id??"",email:a.user?.email??""}}function fe(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const i=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),r=JSON.parse(Buffer.from(i,"base64").toString("utf-8"));if(!r.sub)throw new Error("JWT missing 'sub' claim");return r}C(_e,{getValidToken:()=>ue});var he,ge,ye,we,be,ve=R({"src/auth/refresh.ts"(){ce(),pe()}}),je={};async function Se(){if(he)try{const e=await ee();e&&e.expires_at>be&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),xe())}catch{}if(he&&we>Date.now()+6e4)return he;he&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:i}=await ue(),r=e.split(".");if(3===r.length)try{const e=JSON.parse(Buffer.from(r[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());we=1e3*(e.exp??0)}catch{we=Date.now()+36e5}try{const e=await ee();be=e?.expires_at??0}catch{be=0}const n=d(se,oe,{global:{headers:{Authorization:`Bearer ${e}`}}});return ge=t,ye=i,he=n}function xe(){he=null,ge=null,ye=null,we=0,be=0}function ke(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const i=e;t="string"==typeof i.message?i.message:"string"==typeof i.code?i.code:String(e)}else null!=e&&(t=String(e));return/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)}async function Ie(e){try{return await e()}catch(t){if(!ke(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),xe(),await e()}}function Ee(){if(!ge)throw new Error("Not authenticated. Call getClient() first.");return ge}function Ae(){return ye??""}async function Oe(e,t){const i=Ee(),{data:r,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n||!r)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",i).eq("org_id",r.org_id).maybeSingle();if(s||!a){const{data:t}=await e.rpc("is_platform_admin");if(!0===t)return"admin";throw new Error("Not a member of this project's organization")}if("viewer"===a.role)throw new Error("VIEWER_ROLE");return a.role}async function He(e,t){const i=Ee(),{data:r,error:n}=await e.from("projects").select("org_id, created_by").eq("id",t).maybeSingle();if(n||!r)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",i).eq("org_id",r.org_id).maybeSingle();if(s||!a)throw new Error("Not a member of this project's organization");if("admin"===a.role)return"admin";if(r.created_by===i)return"owner";throw new Error("PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED")}C(je,{getClient:()=>Se,getUserEmail:()=>Ae,getUserId:()=>Ee,invalidateClient:()=>xe,isJwtExpiredError:()=>ke,requireProjectFieldDefinitionAccess:()=>He,requireWriteAccess:()=>Oe,withJwtRetry:()=>Ie});var De,Re,Ce=R({"src/db/client.ts"(){ve(),ce(),pe(),he=null,ge=null,ye=null,we=0,be=0}}),Ue={};async function Me(){const e=p(32).toString("base64url"),t=_("sha256").update(e).digest("base64url"),i=`http://localhost:${De}${Re}`,r=new f(`${de}/auth/mcp-consent`);return r.searchParams.set("redirect_uri",i),r.searchParams.set("code_challenge",t),r.searchParams.set("code_challenge_method","S256"),new Promise((t,i)=>{let n;function a(){clearTimeout(n)}const s=c(async(r,n)=>{const o=new f(r.url??"/",`http://localhost:${De}`);if(o.pathname!==Re)return n.writeHead(404),void n.end("Not found");try{if("access_denied"===o.searchParams.get("error"))return n.writeHead(200,{"Content-Type":"text/html"}),n.end(qe("Authorization was cancelled.")),a(),s.close(),void i(new Error("Authorization cancelled by user."));const r=o.searchParams.get("code");if(r){const o=await fetch(`${se}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:oe},body:JSON.stringify({auth_code:r,code_verifier:e})}),d=await o.json();if(!o.ok||!d.access_token){const e=d.error_description??d.msg??"Unknown error";return n.writeHead(200,{"Content-Type":"text/html"}),n.end(qe(`Code exchange failed: ${e}`)),a(),s.close(),void i(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(d.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(se,oe,{global:{headers:{Authorization:`Bearer ${d.access_token}`}}}),{data:p,error:_}=await m.from("org_members").select("org_id").limit(1);return _||!p||0===p.length?(n.writeHead(200,{"Content-Type":"text/html"}),n.end(qe('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://atoms.tech">atoms.tech</a> first, then run this login command again.')),a(),s.close(),void i(new Error("No ATOMS account found. Sign up at atoms.tech first."))):(await te({access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Date.now()+1e3*(d.expires_in??3600),user_email:c}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(Te(c)),a(),s.close(),void t({email:c}))}const d=o.searchParams.get("access_token"),c=o.searchParams.get("refresh_token"),l=parseInt(o.searchParams.get("expires_in")??"3600",10);d&&c?(await te({access_token:d,refresh_token:c,expires_at:Date.now()+1e3*l}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(Te("authenticated")),a(),s.close(),t({email:"authenticated"})):(n.writeHead(200,{"Content-Type":"text/html"}),n.end("<!DOCTYPE html>\n<html>\n<head><title>ATOMS MCP Login</title></head>\n<body>\n <h1>Completing login...</h1>\n <script>\n const hash = window.location.hash.substring(1);\n const params = new URLSearchParams(hash);\n const data = {\n access_token: params.get('access_token'),\n refresh_token: params.get('refresh_token'),\n expires_in: params.get('expires_in'),\n user_email: ''\n };\n if (data.access_token) {\n // Decode JWT to get email\n try {\n const payload = JSON.parse(atob(data.access_token.split('.')[1]));\n data.user_email = payload.email || '';\n } catch(e) {}\n fetch('/token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data)\n }).then(() => {\n document.body.innerHTML = '<h1>Login successful! You can close this tab.</h1>';\n }).catch(() => {\n document.body.innerHTML = '<h1>Login failed. Please try again.</h1>';\n });\n } else {\n document.body.innerHTML = '<h1>Login failed — no tokens received.</h1>';\n }\n <\/script>\n</body>\n</html>"))}catch(e){n.writeHead(500),n.end("Authentication failed"),a(),s.close(),i(e)}});s.on("request",async(e,r)=>{if("POST"===e.method&&"/token"===e.url){let n="";e.on("data",e=>{n+=e.toString()}),e.on("end",async()=>{try{const e=JSON.parse(n);await te({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0})),a(),s.close(),t({email:e.user_email??"authenticated"})}catch(e){r.writeHead(500),r.end("Failed to store credentials"),a(),s.close(),i(e)}})}}),s.listen(De,"127.0.0.1",async()=>{process.stderr.write("\nOpening browser for ATOMS login...\n"),process.stderr.write(`If the browser doesn't open, visit:\n${r.toString()}\n\n`);try{const{default:e}=await import("open");await e(r.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),n=setTimeout(()=>{s.close(),i(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function Te(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Authorized</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #052e16;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 {\n font-size: 22px;\n font-weight: 600;\n margin-bottom: 8px;\n color: #22c55e;\n }\n .email {\n font-size: 14px;\n color: #a3a3a3;\n margin-bottom: 32px;\n }\n .permissions {\n text-align: left;\n background: #0a0a0a;\n border: 1px solid #262626;\n border-radius: 12px;\n padding: 20px;\n margin-bottom: 24px;\n }\n .permissions h3 {\n font-size: 12px;\n font-weight: 600;\n color: #737373;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n margin-bottom: 12px;\n }\n .perm-item {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 6px 0;\n font-size: 14px;\n color: #d4d4d4;\n }\n .perm-item .dot {\n width: 6px;\n height: 6px;\n background: #22c55e;\n border-radius: 50%;\n flex-shrink: 0;\n }\n .closing {\n font-size: 13px;\n color: #525252;\n }\n .closing span { color: #a3a3a3; font-variant-numeric: tabular-nums; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#22c55e" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1>Authorization Granted</h1>\n <p class="email">${e}</p>\n\n <div class="permissions">\n <h3>ATOMS MCP can now</h3>\n <div class="perm-item"><span class="dot"></span> Read your projects and requirements</div>\n <div class="perm-item"><span class="dot"></span> Create and edit requirements and test cases</div>\n <div class="perm-item"><span class="dot"></span> Record test results (pass/fail)</div>\n <div class="perm-item"><span class="dot"></span> Manage traceability relationships</div>\n <div class="perm-item"><span class="dot"></span> Export coverage reports and diagrams</div>\n </div>\n\n <p class="closing">This tab will close in <span id="countdown">5</span>s</p>\n </div>\n\n <script>\n let seconds = 5;\n const el = document.getElementById('countdown');\n const timer = setInterval(() => {\n seconds--;\n el.textContent = seconds;\n if (seconds <= 0) {\n clearInterval(timer);\n window.close();\n // If window.close() is blocked (not opened by script), update message\n setTimeout(() => {\n document.querySelector('.closing').textContent = 'You can close this tab now.';\n }, 500);\n }\n }, 1000);\n <\/script>\n</body>\n</html>`}function qe(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Failed</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #450a0a;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 { font-size: 22px; font-weight: 600; margin-bottom: 16px; color: #ef4444; }\n .reason { font-size: 14px; color: #a3a3a3; line-height: 1.6; }\n .reason a { color: #7c3aed; text-decoration: underline; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#ef4444" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1>Authorization Failed</h1>\n <p class="reason">${e}</p>\n </div>\n</body>\n</html>`}C(Ue,{login:()=>Me});var Pe,$e,Ne,Le,Fe=R({"src/auth/login.ts"(){ce(),pe(),De=19275,Re="/callback"}});function We(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Ne)if(t.test(e.trim()))return"[redacted]";return e.length>Le?e.slice(0,Le)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>We(e,t+1));if(null!==e&&"object"==typeof e){const i={};for(const[r,n]of Object.entries(e)){const e=r.toLowerCase();Pe.has(e)?i[r]="[redacted]":$e.has(e)?i[r]="string"==typeof n?"[content]":We(n,t+1):i[r]=We(n,t+1)}return i}return e}function Ve(e){return We(e)}var Be,ze,Je,Qe,Ge,Ye=R({"src/middleware/audit.ts"(){Pe=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),$e=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Ne=[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,/^bearer\s+\S+$/i,/^(sk|pk|npm|gh|glpat|xoxb|xoxp|rk|SG\.)[-_][A-Za-z0-9_-]{16,}/,/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/],Le=200}}),Ke=R({"src/middleware/rate-limiter.ts"(){Be=60,ze=6e4}});function Ze(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?Je.test(e)?e:(Qe||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),Qe=!0),null):null}var Xe,et=R({"src/middleware/project-scope.ts"(){Je=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Qe=!1,Ge=class extends Error{expectedProjectId;receivedProjectId;constructor(e,t){super("Tool call rejected: project_id is outside the configured ATOMS_MCP_PROJECT_ID scope."),this.name="ProjectScopeError",this.expectedProjectId=e,this.receivedProjectId=t}}}});function tt(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?Xe:t:Xe}var it,rt,nt,at,st,ot,dt=R({"src/core/client-identity.ts"(){Xe="claude_desktop"}}),ct=R({"src/core/timestamps.ts"(){it=h.string().datetime({offset:!0})}}),lt=R({"src/core/errors.ts"(){}}),mt={};function pt(e,t=nt){if("string"!=typeof e)return"";const i=e.replace(st,"").replace(ot,"");return i.length<=t?i:i.slice(0,t)+"..."}function _t(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function ut(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function ft(e,t,i){return{total_count:e,limit:t,offset:i,has_more:i+t<e}}function ht(e,t){return{status:"error",message:e,next_steps:t}}function gt(e,t){return ht(`${e} '${pt(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function yt(e){return ht(`${e} role cannot modify project data`,["Contact your org admin to upgrade your role to editor","Use read-only tools (atoms_list_items, atoms_get_item, atoms_search) instead"])}function wt(e){return ht(`Validation error: ${pt(e,at)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function bt(){return ht("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' first.",["Run: npx @atoms-tech/atoms-mcp login","Or set ATOMS_ACCESS_TOKEN environment variable"])}function vt(){return ht("Your ATOMS session token expired and could not be refreshed automatically.",["Call atoms_status() — it will refresh the token if possible","If that still reports 'expired', restart Claude Desktop (quit and reopen)","If the problem persists, run: npx @atoms-tech/atoms-mcp logout && npx @atoms-tech/atoms-mcp login"])}function jt(e){return ht("Tool call rejected: project_id is outside the configured ATOMS_MCP_PROJECT_ID scope.",[`This MCP session is bound to project ${e}`,"Pass that project_id, or restart without ATOMS_MCP_PROJECT_ID to access other projects"])}function St(e){return ht("Rate limited: too many requests to ATOMS API.",[e?`Wait ${e} seconds before retrying.`:"Wait a few seconds before retrying.","Reduce the frequency of back-to-back tool calls"])}function xt(e){return ht(`Parse error: ${pt(e,at)}`,["Check that body/title/summary fields contain valid text (no unexpected control characters)","If the content was generated programmatically, validate the string before passing it","Simplify the content and retry — if it succeeds, the original content has a malformed character"])}function kt(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function It(){return ht("Stale write rejected: this item changed after it was read.",["Call atoms_get_item again and use the returned metadata.updated_at value","Review the current item before retrying so you do not overwrite newer work","Retry atoms_update_item or atoms_link_items with the fresh expected timestamp"])}function Et(){return ht("Save paused because this item is already being written.",["Wait a few seconds, read the item again, and retry once","Do not repeatedly retry the same stale payload"])}function At(){return ht("Item saves are temporarily paused by an ATOMS operator.",["Keep your local draft and wait for the operator to re-enable saves","Do not repeatedly retry while the safety brake is active"])}function Ot(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e),i=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return/not authenticated/i.test(t)?bt():function(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const i=e;t="string"==typeof i.message?i.message:"string"==typeof i.code?i.code:String(e)}else null!=e&&(t=String(e));return/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)}(e)?vt():/rate.?limit|too many requests|429/i.test(t)?St():kt(t)?It():/save_temporarily_unavailable/i.test(t)?At():"55P03"===i||"57014"===i||/item_save_busy|statement timeout|request timeout|upstream request timeout/i.test(t)?Et():"42501"===i&&/project_field/i.test(t)?yt("Project admin or owner"):"P0002"===i&&/project_field/i.test(t)?ht("Project field not found.",["Refresh the field list and retry with an existing field name"]):["22023","23505","23514"].includes(i)&&/project_field/i.test(t)?wt(t.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?xt(t):Dt(t)}function Ht(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??""),i=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return["40001","55P03","57014"].includes(i)||/stale_item_write|soft_deleted_item_write|save_temporarily_unavailable|item_save_busy|statement timeout|request timeout|upstream request timeout|fetch failed|network error|connection (?:closed|reset|refused)/i.test(t)}function Dt(e){return/row.level security|permission denied for/i.test(e)?ht("Permission denied: your account does not have write access to this project.",["Verify you have editor or admin role in this project","Contact your org admin to upgrade your permissions","Use atoms_list_projects to confirm the project_id is one you have access to"]):ht(`Database error: ${pt(e,at)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function Rt(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function Ct(e){const t=JSON.stringify(e,null,2);if(t.length>rt&&"success"===e.status&&Array.isArray(e.data)){const t=Math.max(1,Math.floor(e.data.length/2)),i={...e,data:e.data.slice(0,t),meta:{...e.meta,truncated:!0,truncation_message:`Response truncated from ${e.data.length} to ${t} items. Use 'offset' parameter or add filters to see more results.`}};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}}return{content:[{type:"text",text:t}],structuredContent:e}}function Ut(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}C(mt,{CHARACTER_LIMIT:()=>rt,accessDeniedError:()=>yt,authError:()=>bt,classifyError:()=>Ot,dbError:()=>Dt,errorResponse:()=>ht,formatErrorResult:()=>Ut,formatToolResult:()=>Ct,isItemSaveStopError:()=>Ht,isStaleWriteErrorMessage:()=>kt,jwtExpiredError:()=>vt,notFoundError:()=>gt,paginationMeta:()=>ft,parseError:()=>xt,rateLimitError:()=>St,sanitizeForEcho:()=>pt,sanitizeTagOrLevel:()=>_t,saveBusyError:()=>Et,saveUnavailableError:()=>At,scopeError:()=>jt,staleWriteError:()=>It,success:()=>ut,validationError:()=>wt,wrapUserContent:()=>Rt});var Mt,Tt=R({"src/tools/_base.ts"(){lt(),rt=25e3,nt=50,at=200,st=new RegExp("[\\u0000-\\u001F\\u007F]","g"),ot=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g")}});var qt=R({"src/apps/register.ts"(){Mt={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function Pt(e){return function(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(`*${t=e,t.replace(/[\\%_*]/g,e=>`\\${e}`)}*`);var t}var $t=R({"src/core/postgrest.ts"(){}});async function Nt(e,t,i){let r=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0});i.type&&(r=r.eq("type",i.type)),i.domain&&(r=r.filter("data->tags->domains","cs",JSON.stringify([i.domain]))),i.level&&(r=r.filter("data->tags->>level","eq",i.level)),r=r.range(i.offset,i.offset+i.limit-1);const{data:n,error:a,count:s}=await r;if(a)throw new Error(a.message);return{items:n??[],totalCount:s??0}}async function Lt(e,t,i){const{data:r,error:n}=await e.from("items").select("*").eq("id",i).eq("project_id",t).is("deleted_at",null).maybeSingle();if(n)throw new Error(n.message);return r}async function Ft(e,t){if(t.baseline_id&&t.as_of)throw new Error("baseline_id and as_of are mutually exclusive");if(t.as_of)return t.as_of;if(t.baseline_id){const{data:i,error:r}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",t.baseline_id).maybeSingle();if(r)throw new Error(`resolveSnapshotAt: ${r.message}`);if(!i||null!==i.deleted_at)throw new Error(`Baseline not found: ${t.baseline_id}`);if(i.project_id!==t.project_id)throw new Error("Baseline does not belong to this project");return i.snapshot_at}return null}async function Wt(e,t){const{data:i,error:r}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, deleted_at").eq("id",t).maybeSingle();if(r)throw new Error(`getBaselineById: ${r.message}`);return i&&null===i.deleted_at?i:null}function Vt(e){return{id:e.id,project_id:e.project_id,type:e.type,title:e.title,data:e.data,created_by:e.changed_by,updated_by:e.changed_by,created_at:e.valid_from,updated_at:e.valid_from,deleted_at:null}}async function Bt(e,t,i){const{data:r,error:n}=await e.rpc("project_state_at",{p_project_id:t,p_snapshot_at:i});if(n)throw new Error(`projectStateAt: ${n.message}`);return r??[]}async function zt(e,t,i,r){const n=i.trim();if(!n)return{items:[],totalCount:0};let a=null;if(r.asset&&r.asset.trim()){const{data:i,error:n}=await e.from("test_results").select("item_id").eq("project_id",t).eq("asset",r.asset.trim());if(n)throw new Error(n.message);const s=new Set;for(const e of i??[])s.add(e.item_id);if(a=Array.from(s),0===a.length)return{items:[],totalCount:0}}let s=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${Pt(n)},data->>body.ilike.${Pt(n)},data->>summary.ilike.${Pt(n)}`).limit(r.limit);r.type&&(s=s.eq("type",r.type)),a&&(s=s.in("id",a));const{data:o,error:d,count:c}=await s;if(d)throw new Error(d.message);return{items:o??[],totalCount:c??0}}function Jt(e,t){const i=new Set(e.map(e=>e.id)),r=new Set,n=[],a=(e,t,a)=>{if(e===t)return;if(!i.has(e)||!i.has(t))return;const s=`${e}|${t}|${a}`;r.has(s)||(r.add(s),n.push({from_id:e,to_id:t,type:a}))};for(const e of t)a(e.from_id,e.to_id,e.type);for(const t of e){const e=t.data?.relationships??{},i=t=>Array.isArray(e[t])?e[t].filter(e=>"string"==typeof e):[];for(const e of i("parents"))a(t.id,e,"parent");for(const e of i("children"))a(t.id,e,"child");for(const e of i("related"))a(t.id,e,"related");for(const e of i("verifies"))a(t.id,e,"verifies");for(const e of i("verified_by"))a(t.id,e,"verified_by");for(const e of i("mitigated_by"))a(t.id,e,"mitigated_by");for(const e of i("mitigates"))a(t.id,e,"mitigates")}return n}async function Qt(e,t,i){const r="requirement"===i?"REQ":"test-case"===i?"TC":"note"===i?"NOTE":"TABLE",{data:n,error:a}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(a)throw new Error(`ID generation failed: ${a.message}`);return n}var Gt=R({"src/db/queries.ts"(){$t()}}),Yt={};async function Kt(){try{const e=await Ie(async()=>{const e=await Se();return await async function(e){const{data:t,error:i}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(i)throw new Error(i.message);return(t??[]).map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.organizations?.name??"Unknown",created_at:e.created_at}))}(e)}),t=Ze(),i=F,r=B().project_scope,n=r?new Set(r):null;return Ct(ut(e.filter(e=>!i||e.org_id===i).filter(e=>!t||e.id===t).filter(e=>!n||n.has(e.id)).map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.org_name,created_at:e.created_at}))))}catch(e){return Ut(Ot(e))}}C(Yt,{listProjectsHandler:()=>Kt});var Zt=R({"src/tools/list-projects.ts"(){Ce(),Gt(),et(),z(),Tt()}}),Xt={};async function ei(e){try{const t=await Se();let i,r,n=null;try{n=await Ft(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ut(Dt(e.message))}if(n){const a=(await Bt(t,e.project_id,n)).filter(t=>{if(e.type&&t.type!==e.type)return!1;const i=t.data??{};if(e.domain){const t=i?.tags?.domains??[];if(!Array.isArray(t)||!t.includes(e.domain))return!1}return!e.level||i?.tags?.level===e.level});r=a.length,i=a.slice(e.offset,e.offset+e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const n=await Nt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});i=n.items,r=n.totalCount}return Ct(ut(i.map(e=>({id:e.id,title:Rt(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ft(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(Xt,{listItemsHandler:()=>ei});var ti=R({"src/tools/list-items.ts"(){Ce(),Gt(),Tt()}}),ii={};async function ri(e){try{const i=await Se();let r=null;try{r=await Ft(i,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ut(ht(e.message,["Pass baseline_id OR as_of, not both"]))}const n=r?await async function(e,t,i,r){const{data:n,error:a}=await e.rpc("item_state_at",{p_item_id:i,p_project_id:t,p_snapshot_at:r});if(a)throw new Error(`itemStateAt: ${a.message}`);return(n??[])[0]??null}(i,e.project_id,e.item_id,r).then(e=>e?Vt(e):null):await Lt(i,e.project_id,e.item_id);if(!n)return Ut(gt("Item",e.item_id));const a={parents:[],children:[],related:[],verified_by:[],verifies:[],mitigated_by:[],mitigates:[]};if(r){const e=n.data?.relationships??{};for(const t of Object.keys(a)){const i=e[t];Array.isArray(i)&&(a[t]=i.slice())}}else{const t=await async function(e,t,i){const{data:r,error:n}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${i},to_id.eq.${i}`);if(n)throw new Error(n.message);return r??[]}(i,e.project_id,e.item_id),r={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",mitigated_by:"mitigated_by",mitigates:"mitigates"},s={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"},o=(e,t)=>{if(!(e in a))return;const i=a[e];i.includes(t)||i.push(t)},d=new Set([e.item_id]);for(const e of t)d.add(e.from_id),d.add(e.to_id);const c=n.data?.relationships??{};for(const e of Object.keys(a)){const t=c[e];if(Array.isArray(t))for(const e of t)"string"==typeof e&&d.add(e)}let l=new Set([e.item_id]);const m=Array.from(d);if(m.length>0){const{data:t,error:r}=await i.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",m);if(r)throw new Error(r.message);l=new Set((t??[]).map(e=>e.id)),l.add(e.item_id)}const p=e=>l.has(e);for(const i of t)if(i.from_id===e.item_id){if(!p(i.to_id))continue;o(r[i.type]??i.type,i.to_id)}else{if(!p(i.from_id))continue;o(s[i.type]??i.type,i.from_id)}for(const t of Object.keys(a)){const i=c[t];if(Array.isArray(i))for(const r of i)"string"==typeof r&&r!==e.item_id&&p(r)&&o(t,r)}}let s=[];if("test-case"===n.type)if(r)s=(n.data?.runs??[]).map(e=>({result:e.result??"not-run",run_by:e.by??e.run_by??null,run_at:e.date??e.run_at??"",note:e.note??null})).filter(e=>"string"==typeof e.run_at&&e.run_at.length>0).sort((e,t)=>t.run_at.localeCompare(e.run_at)).slice(0,20).map(e=>({result:e.result,run_by:e.run_by,run_at:e.run_at,note:e.note}));else{const{data:t,error:r}=await i.from("test_results").select("result, run_by, run_at, note").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);!r&&t&&(s=t)}return Ct(ut({id:n.id,type:n.type,title:Rt(n.title),summary:Rt(n.data?.summary),body:Rt(n.data?.body),tags:n.data?.tags??{domains:[]},ownership:n.data?.ownership??{primary:null,additional:[]},relationships:a,links:n.data?.links??[],fields:(t=n.data?.fields,!t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>"string"==typeof e[1]).map(([e,t])=>[e,Rt(t)]))),status:n.data?.status,..."test-case"===n.type?{latest_result:s[0]?.result??"not-run",test_results:s}:{},metadata:{created_at:n.created_at,created_by:n.created_by,updated_at:n.updated_at,updated_by:n.updated_by,source_id:n.data?.metadata?.source_id}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}var t}C(ii,{getItemHandler:()=>ri});var ni=R({"src/tools/get-item.ts"(){Ce(),Gt(),Tt()}}),ai={};async function si(e){try{const t=await Se();let i,r,n=null;try{n=await Ft(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return Ut(Dt(e.message))}if(n){const a=await Bt(t,e.project_id,n),s=e.query.trim().toLowerCase(),o=0===s.length?[]:a.filter(t=>{if(e.type&&t.type!==e.type)return!1;const i=t.data??{};return[t.title,i?.body,i?.summary].filter(e=>"string"==typeof e).map(e=>e.toLowerCase()).some(e=>e.includes(s))});r=o.length,i=o.slice(0,e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const n=await zt(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});i=n.items,r=n.totalCount}return Ct(ut(i.map(e=>({id:e.id,title:Rt(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ft(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(ai,{searchHandler:()=>si});var oi=R({"src/tools/search.ts"(){Ce(),Gt(),Tt()}}),di={};async function ci(e){try{const t=await Se(),{access_token:i}=await ue(),{items:r,totalCount:n}=await async function(e,t,i,r){const{ATOMS_SUPABASE_URL:n,ATOMS_SUPABASE_ANON_KEY:a}=await Promise.resolve().then(()=>(pe(),le)),s=await fetch(`${n}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`,apikey:a},body:JSON.stringify({input:i})});if(!s.ok)throw new Error(`Embed function failed: ${s.status}`);const{embedding:o}=await s.json(),{data:d,error:c}=await e.rpc("semantic_search",{query_embedding:o,p_project_id:t,match_threshold:.3,match_count:r.limit,p_type:r.type||null});if(c)throw new Error(c.message);return{items:d??[],totalCount:(d??[]).length,method:"semantic"}}(t,e.project_id,e.query,{type:e.type,limit:e.limit,accessToken:i});return Ct(ut(r.map(e=>({id:e.id,title:Rt(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ft(n,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(di,{semanticSearchHandler:()=>ci});var li=R({"src/tools/semantic-search.ts"(){Ce(),ve(),Gt(),Tt()}}),mi={};async function pi(e){try{if(e.baseline_id&&e.as_of)return Ut(wt("baseline_id and as_of are mutually exclusive"));const t=await Se();let i;if(e.baseline_id){const r=await Wt(t,e.baseline_id);if(!r)return Ut(wt(`Baseline ${e.baseline_id} not found`));if(r.project_id!==e.project_id)return Ut(wt("Baseline does not belong to this project"));i=r.snapshot_at}else e.as_of&&(i=e.as_of);const{covered:r,uncovered:n,total:a}=await async function(e,t,i){let r,n,a;if(i.snapshotAt){const s=(await Bt(e,t,i.snapshotAt)).map(Vt);r=s.filter(e=>"requirement"===e.type),n=s.map(e=>({id:e.id,data:e.data})),a=[]}else{const{data:i,error:s}=await e.from("items").select("*").eq("project_id",t).eq("type","requirement").is("deleted_at",null);if(s)throw new Error(s.message);r=i??[];const{data:o,error:d}=await e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null);if(d)throw new Error(d.message);n=o??[];const{data:c,error:l}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t);if(l)throw new Error(l.message);a=c??[]}const s=r.filter(e=>!(i.domain&&!(e.data?.tags?.domains??[]).includes(i.domain)||i.level&&e.data?.tags?.level!==i.level)),o=Jt(n,a),d=new Set;for(const e of o)"verifies"===e.type?d.add(e.to_id):"verified_by"===e.type&&d.add(e.from_id);return{covered:s.filter(e=>d.has(e.id)),uncovered:s.filter(e=>!d.has(e.id)),total:s.length}}(t,e.project_id,{domain:e.domain,level:e.level,snapshotAt:i}),s=n.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level}));return Ct(ut({covered:r.length,uncovered:n.length,total:a,coverage_percent:a>0?Math.round(r.length/a*1e3)/10:100,uncovered_items:s}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(mi,{getCoverageHandler:()=>pi});var _i=R({"src/tools/get-coverage.ts"(){Ce(),Gt(),Tt()}}),ui={};async function fi(e){try{const t=await Se(),i=await async function(e,t,i,r){const{data:n,error:a}=await e.from("change_history").select("*").eq("item_id",i).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r);if(a)throw new Error(a.message);return n??[]}(t,e.project_id,e.item_id,e.limit),r=i.map(e=>{const t=[],i=e.old_data,r=e.new_data;if(i&&r){const e=new Set([...Object.keys(i),...Object.keys(r)]);for(const n of e)JSON.stringify(i[n])!==JSON.stringify(r[n])&&t.push(n)}else r?t.push("(created)"):i&&t.push("(deleted)");return{id:e.id,event_type:e.event_type,changed_by:e.changed_by??null,changed_at:e.changed_at,actor:e.actor??"user",session_id:e.session_id??null,fields_changed:t}});return Ct(ut(r,ft(r.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(ui,{getHistoryHandler:()=>fi});var hi=R({"src/tools/get-history.ts"(){Ce(),Gt(),Tt()}});function gi(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function yi(e){const t=bi(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:`["${t}"]`}function wi(e){const t=gi(e.from_id),i=gi(e.to_id);return"child"===e.type?`${t} --\x3e ${i}`:"verified_by"===e.type?`${t} -.-> ${i}`:"related"===e.type?`${t} -.- ${i}`:null}function bi(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var vi=R({"src/core/mermaid.ts"(){}}),ji={};async function Si(e){try{if(e.baseline_id&&e.as_of)return Ut(wt("baseline_id and as_of are mutually exclusive"));const t=await Se();let i,r,n;if(e.baseline_id){const r=await Wt(t,e.baseline_id);if(!r)return Ut(wt(`Baseline ${e.baseline_id} not found`));if(r.project_id!==e.project_id)return Ut(wt("Baseline does not belong to this project"));i=r.snapshot_at}else e.as_of&&(i=e.as_of);if(i){r=(await Bt(t,e.project_id,i)).map(Vt).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),n=Jt(r,[])}else{const{data:i,error:a}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);r=i??[];const{data:s,error:o}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);n=Jt(r,s??[])}return Ct(ut(function(e){const t=e.items,i=e.relationships??[],r=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${bi(e.emptyLabel??"No items in project")}]`,node_count:0,edge_count:0};const n=new Map(t.map(e=>[e.id,e])),a=function(e,t,i,r){if(i)return[i];const n=new Set(t.filter(e=>"child"===e.type).map(e=>e.to_id));return e.filter(e=>!n.has(e.id)).filter(e=>r||"test-case"!==e.type).map(e=>e.id)}(t,i,e.rootItemId,e.includeTests),s=a.map(e=>({id:e,depth:0})),o=new Set,d=new Set,c=[],l=[];for(;s.length>0;){const{id:t,depth:a}=s.shift();if(o.has(t)||a>r)continue;const m=n.get(t);if(m&&(e.includeTests||"test-case"!==m.type)){o.add(t),c.push(` ${gi(t)}${yi(m)}`);for(const c of i){if(c.from_id!==t)continue;const i=n.get(c.to_id);if(!i)continue;if(!e.includeTests&&"test-case"===i.type)continue;if(a+1>r)continue;const m=wi(c);if(!m)continue;const p=`${c.from_id}:${c.type}:${c.to_id}`;d.has(p)||(d.add(p),l.push(` ${m}`),o.has(c.to_id)||s.push({id:c.to_id,depth:a+1}))}}}return{mermaid:["graph TD",...c,...l].join("\n"),node_count:o.size,edge_count:d.size}}({items:r,relationships:n,rootItemId:e.root_item_id,depth:e.depth,includeTests:e.include_tests,emptyLabel:"No items in project"})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(ji,{exportMermaidHandler:()=>Si});var xi=R({"src/tools/export-mermaid.ts"(){Ce(),Gt(),Tt(),vi()}}),ki={};function Ii(e){const t=_t(e??"");return"sub-system"===t?"subsystem":t}async function Ei(e,t){const{data:i}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:i?.domains??[],levels:i?.levels??[]}}async function Ai(e,t,i,r){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:i,levels:r},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function Oi(e,t,i){const r=_t(i??""),n=Ii(r);if(!r)return!1;try{const{domains:i,levels:a}=await Ei(e,t);return!a.some(e=>Ii(e)===n)&&(await Ai(e,t,i,[...a,r]),!0)}catch{return!1}}async function Hi(e){try{const t=await Se(),{levels:i}=await Ei(t,e.project_id),{data:r}=await t.from("items").select("data").eq("project_id",e.project_id).is("deleted_at",null),n={};for(const e of r??[]){const t=e.data?.tags,i=Ii(t?.level);i&&(n[i]=(n[i]??0)+1)}return Ct(ut({levels:i.map((e,t)=>({name:e,prefix:`L${t}`,item_count:n[Ii(e)]??0})),total:i.length,note:"L# is the level's position in this list (0-based). Names are user-defined."}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Di(e){try{const t=await Se();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const{domains:i,levels:r}=await Ei(t,e.project_id),n=_t(e.name),a=Ii(n);if(!n)return Ut(wt("Level name cannot be empty."));if(r.some(e=>Ii(e)===a))return Ut(wt(`Level "${n}" already exists in this project.`));const s=r.length;return await Ai(t,e.project_id,i,[...r,n]),Ct(ut({level:{name:n,prefix:`L${s}`},message:`Level "${n}" registered as L${s}. Tag items with level="${n}".`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(ki,{createLevelHandler:()=>Di,ensureLevelRegistered:()=>Oi,listLevelsHandler:()=>Hi});var Ri,Ci,Ui=R({"src/tools/levels.ts"(){Ce(),Tt()}}),Mi=R({"src/core/project-field-counts.ts"(){}}),Ti={};async function qi(e,t){const{data:i,error:r}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(r)throw r;return Pi(i?.fields)}function Pi(e){if(!Array.isArray(e))return[];const t=[],i=new Set;for(const r of e){if(!r||"object"!=typeof r)continue;const e=r,n="string"==typeof e.name?e.name.trim():"";if(!n)continue;const a=n.toLowerCase();if(i.has(a))continue;i.add(a);const s=void 0===e.type?"text":"string"==typeof e.type&&Ci.has(e.type)?e.type:"text",o=Array.isArray(e.options)?zi(e.options):[];t.push({name:n,type:s,..."select"===s?{options:o}:{}})}return t}function $i(e,t){const i=e.name.trim();if(!i)return"Field name cannot be empty.";if(i.length>60)return"Field name must be 60 characters or fewer.";if(!Ci.has(e.type))return"Field type is not supported.";const r=t.find(e=>e.name.toLowerCase()===i.toLowerCase());return r?`Field "${r.name}" already exists.`:"select"===e.type&&0===zi(e.options??[]).length?"Select fields need at least one option.":null}function Ni(e,t){const i=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!i.has(e.toLowerCase()))}function Li(e,t){const i=new Map(e.map(e=>[e.name.toLowerCase(),e.name])),r={};for(const[e,n]of Object.entries(t))r[i.get(e.toLowerCase())??e]=n;return r}function Fi(e,t,i=new Set){const r=Ni(e,t);if(r.length>0)return{error:`Unknown field${r.length>1?"s":""}: ${r.join(", ")}. Defined: ${e.length>0?e.map(e=>e.name).join(", "):"(none)"}. Define fields first with atoms_create_field.`};const n={},a=new Map(e.map(e=>[e.name.toLowerCase(),e]));for(const[e,r]of Object.entries(t)){const t=a.get(e.toLowerCase());if(!t)continue;const s=Wi(t,r,i);if(s.error)return{error:s.error};s.value&&(n[t.name]=s.value)}return{fields:n}}function Wi(e,t,i){const r=t.trim();if(!r)return{value:""};if(r.length>1e4)return{error:`${e.name} is too long.`};switch(e.type){case"text":case"long":return{value:r};case"bool":{const t=r.toLowerCase();return"yes"===t?{value:"yes"}:"no"===t?{value:"no"}:{error:`${e.name} must be yes or no.`}}case"date":return function(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;const t=new Date(`${e}T00:00:00.000Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}(r)?{value:r}:{error:`${e.name} must be an ISO date.`};case"person":return Bi(r)&&i.has(r)?{value:r}:{error:`${e.name} must be an active project member ID.`};case"select":return(e.options??[]).includes(r)?{value:r}:{error:`${e.name} must be one of: ${(e.options??[]).join(", ")}.`};case"number":return Number.isFinite(Number(r))?{value:r}:{error:`${e.name} must be numeric.`};case"link":return function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(r)?{value:r}:{error:`${e.name} must be an http(s) URL.`}}}async function Vi(e,t,i,r){const n=new Map(i.map(e=>[e.name.toLowerCase(),e])),a=new Map;for(const[e,t]of Object.entries(r)){const i=n.get(e.toLowerCase());"person"===i?.type&&t.trim()&&a.set(t.trim(),i)}const s=new Set;for(const[i,r]of a){if(!Bi(i))return{error:`${r.name} must be an active project member ID.`};const{data:n,error:a}=await e.rpc("is_active_project_member_for_field",{p_project_id:t,p_person_user_id:i,p_actor_user_id:Ee()});if(a)return{error:a.message};!0===n&&s.add(i)}return Fi(i,r,s)}function Bi(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function zi(e){const t=[],i=new Set;for(const r of e){if("string"!=typeof r)continue;const e=r.trim();if(!e)continue;const n=e.toLowerCase();i.has(n)||(i.add(n),t.push(e))}return t}async function Ji(e){try{const t=await Se(),i=await qi(t,e.project_id),r=await async function(e,t,i,r=500){const n=Object.fromEntries(i.map(e=>[e.name,0])),a=new Map(i.map(e=>[e.name.toLowerCase(),e.name]));let s=0;for(;;){const{data:i,error:o}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null).order("id",{ascending:!0}).range(s,s+r-1);if(o)throw o;const d=i??[];for(const e of d){const t=e.data?.fields;if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,i]of Object.entries(t)){const t=a.get(e.toLowerCase());t&&"string"==typeof i&&i.length>0&&(n[t]+=1)}}if(d.length<r)return n;s+=d.length}}(t,e.project_id,i);return Ct(ut({fields:i.map(e=>({name:e.name,type:e.type,options:e.options??[],item_count:r[e.name]??0})),total:i.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Ot(e))}}async function Qi(e){try{const t=await Se();try{await He(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ut(yt("Project admin or owner"));throw e}const{data:i}=await t.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),r=Pi(i?.fields),n={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:zi(e.options??[])}:{}},a=$i(n,r);if(a)return Ut(wt(a));const{data:s,error:o}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"create",p_field:n,p_field_name:null,p_actor_user_id:Ee()});if(o)throw o;return Ct(ut({field:s?.field??n,message:`Field "${n.name}" defined. Set values with atoms_update_item fields={"${n.name}": "<value>"}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Ot(e))}}async function Gi(e){try{const t=await Se();try{await He(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ut(yt("Project admin or owner"));throw e}const i=e.name.trim(),{data:r,error:n}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"delete",p_field:null,p_field_name:i,p_actor_user_id:Ee()});if(n)throw n;return Ct(ut({deleted:r?.deleted??i}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Ot(e))}}C(Ti,{PROJECT_FIELD_TYPES:()=>Ri,canonicalizeFieldKeys:()=>Li,createFieldHandler:()=>Qi,deleteFieldHandler:()=>Gi,findUnknownFieldNames:()=>Ni,getProjectFields:()=>qi,listFieldsHandler:()=>Ji,normalizeProjectFields:()=>Pi,validateAndCanonicalizeFieldValues:()=>Fi,validateProjectFieldDefinition:()=>$i,validateProjectFieldValuesForWrite:()=>Vi});var Yi=R({"src/tools/fields.ts"(){Ce(),Tt(),Mi(),Ri=["text","long","bool","date","person","select","number","link"],Ci=new Set(Ri)}}),Ki={};async function Zi(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=(e.domains??[]).map(_t).filter(e=>e.length>0),n=void 0!==e.level?_t(e.level):void 0;if(r.length>0){const{data:i}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),n=i?.domains??[];if(n.length>0){const e=new Set(n.map(_t).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return Ut(wt(`Unknown domain${t.length>1?"s":""}: ${t.join(", ")}. Registered: ${n.join(", ")}. Add new domains via Taxonomy Management in the ATOMS web app first.`))}}let a;if(e.fields&&Object.keys(e.fields).length>0){const{getProjectFields:i,validateProjectFieldValuesForWrite:r}=await Promise.resolve().then(()=>(Yi(),Ti)),n=await i(t,e.project_id),s=await r(t,e.project_id,n,e.fields);if(s.error)return Ut(wt(s.error));a=s.fields}const s=await Qt(t,e.project_id,e.type),o=(new Date).toISOString(),d={id:s,type:e.type,title:e.title,summary:e.summary,body:e.body,tags:{domains:r,level:n??""},ownership:{primary:null,additional:[]},relationships:{parents:e.parent_ids??[],children:[],related:[],verifies:[],verified_by:[]},links:[],...a?{fields:a}:{},metadata:{created_at:o,created_by:i,updated_at:o,updated_by:i}},{error:c}=await t.rpc("save_item_with_revision",{p_item_id:s,p_project_id:e.project_id,p_type:e.type,p_title:e.title,p_data:d,p_user_id:i,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null});if(c)throw new Error(c.message);if(n&&await Oi(t,e.project_id,n),e.parent_ids&&e.parent_ids.length>0)for(const r of e.parent_ids){const{error:n}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:s,p_to_id:r,p_type:"parent",p_action:"add",p_user_id:i,p_event_source:"mcp"});n&&process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${r}: ${n.message}\n`)}return await t.from("change_history").insert({item_id:s,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:d,actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===e.echo?Ct(ut({id:s,type:e.type})):Ct(ut({id:s,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",domains:r,level:n??"",project_id:e.project_id}))}catch(e){return Ut(Ot(e))}}C(Ki,{createItemHandler:()=>Zi});var Xi=R({"src/tools/create-item.ts"(){Ce(),Gt(),ka(),Tt(),Ui()}}),er={};async function tr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=async(r,n,a,s)=>{const o=await Lt(t,e.project_id,r);if(!o)return{updated_fields:[],error:`Item "${r}" not found`};const d=void 0!==n.domains?n.domains.map(_t).filter(e=>e.length>0):void 0,c=void 0!==n.level?_t(n.level):void 0;if(void 0!==d&&d.length>0){const{data:i}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),r=i?.domains??[];if(r.length>0){const e=new Set(r.map(_t).filter(e=>e.length>0)),t=d.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const l={...o.data},m={...o.data},p=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==n.title&&_(o.data.title,n.title)&&(m.title=n.title,p.push("title")),void 0!==n.body&&_(o.data.body,n.body)&&(m.body=n.body,p.push("body")),void 0!==n.summary&&_(o.data.summary,n.summary)&&(m.summary=n.summary,p.push("summary")),void 0!==d&&_(o.data.tags?.domains??[],d)&&(m.tags={...m.tags,domains:d},p.push("domains")),void 0!==c&&_(o.data.tags?.level,c)&&(m.tags={...m.tags,level:c},p.push("level")),void 0!==n.status&&_(o.data.status,n.status)&&(m.status=n.status,p.push("status")),void 0!==n.fields&&Object.keys(n.fields).length>0){const{getProjectFields:i,validateProjectFieldValuesForWrite:r,canonicalizeFieldKeys:a}=await Promise.resolve().then(()=>(Yi(),Ti)),s=await i(t,e.project_id),d=await r(t,e.project_id,s,n.fields);if(d.error)return{updated_fields:[],error:d.error};const c=a(s,o.data.fields??{});for(const[e,t]of Object.entries({...a(s,n.fields),...d.fields??{}}))""===t?delete c[e]:c[e]=t;_(o.data.fields??{},c)&&(m.fields=c,p.push("fields"))}if(0===p.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};m.metadata={...m.metadata,updated_at:(new Date).toISOString(),updated_by:i};const u=n.title??o.title,{data:f,error:h}=await t.rpc("save_item_with_revision",{p_item_id:r,p_project_id:e.project_id,p_type:o.type,p_title:u,p_data:m,p_user_id:i,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null,p_expected_updated_at:n.expected_updated_at??o.updated_at});if(h)return{updated_fields:[],error:h};if(!f)return{updated_fields:[],error:`Update silently failed for "${r}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};p.includes("level")&&c&&await Oi(t,e.project_id,c);const g={item_id:r,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:l,new_data:m,actor:Sa(),session_id:ja()};return a&&(g.batch_id=a),s&&(g.reason=s),await t.from("change_history").insert(g).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),{updated_fields:p,updatedData:m,itemType:o.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),i=!0===e.continue_on_error,n=[],a=[];for(const s of e.updates){const{updated_fields:o,error:d}=await r(s.item_id,s,t,e.reason);if(d){if(Ht(d))return Ut(Ot(d));if(!i){const e=d instanceof Error?d.message:String("object"==typeof d&&d&&"message"in d?d.message??"":d);return Ut(wt(`Batch stopped at "${s.item_id}": ${e}. ${n.length} item(s) already updated.`))}a.push({item_id:s.item_id,error:String(d)})}else n.push({id:s.item_id,updated_fields:o})}return Ct(ut({batch_id:t,updated:n.length,results:!1===e.echo?void 0:n,errors:a}))}if(!e.item_id)return Ut(wt("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:n,updatedData:a,itemType:s,error:o}=await r(e.item_id,{title:e.title,body:e.body,summary:e.summary,domains:e.domains,level:e.level,status:e.status,fields:e.fields,expected_updated_at:e.expected_updated_at},void 0,e.reason);if(o){const t=o instanceof Error?o.message:String("object"==typeof o&&o&&"message"in o?o.message??"":o);return t.includes("not found")?Ut(gt("Item",e.item_id)):t.includes("Unknown domain")||t.includes("Unknown field")?Ut(wt(t)):kt(t)||Ht(o)?Ut(Ot(o)):Ut(Dt(t))}if(!1===e.echo)return Ct(ut({id:e.item_id,updated_fields:n}));const d=a??{};return Ct(ut({id:e.item_id,type:s,title:d.title??"",summary:d.summary??"",body:d.body??"",domains:d.tags?.domains??[],level:d.tags?.level??"",updated_fields:n}))}catch(e){return Ut(Ot(e))}}C(er,{updateItemHandler:()=>tr});var ir,rr,nr=R({"src/tools/update-item.ts"(){Ce(),Gt(),ka(),Tt(),Ui()}});function ar(e){const t=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(t){const i=t.toLowerCase();if("1"===i||"true"===i||"all"===i)return!0;if(t.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!B().require_confirmation_for.includes(e)}function sr(e,t=ir){const i=Date.now()+t,r={...e,exp:i},n=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${n}.${l.createHmac("sha256",rr).update(n).digest("base64url")}`,expires_at:new Date(i).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function or(e,t){if("string"!=typeof e||!e.includes("."))return{valid:!1,reason:"Token format invalid"};const[i,r]=e.split(".");if(!i||!r)return{valid:!1,reason:"Token format invalid"};const n=l.createHmac("sha256",rr).update(i).digest("base64url"),a=Buffer.from(r,"utf8"),s=Buffer.from(n,"utf8");if(a.length!==s.length||!l.timingSafeEqual(a,s))return{valid:!1,reason:"Token signature invalid"};let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return{valid:!1,reason:"Token payload malformed"}}return"number"!=typeof o.exp||o.exp<Date.now()?{valid:!1,reason:"Token expired"}:o.tool!==t.tool?{valid:!1,reason:"Token issued for a different tool"}:o.project_id!==t.project_id?{valid:!1,reason:"Token issued for a different project"}:o.target!==t.target?{valid:!1,reason:"Token issued for a different target"}:{valid:!0}}function dr(e){if(Array.isArray(e))return e.map(dr);if(null!==e&&"object"==typeof e){const t={};for(const i of Object.keys(e).sort())t[i]=dr(e[i]);return t}return e}function cr(e){const t=JSON.stringify(dr(e));return l.createHash("sha256").update(t).digest("base64url").slice(0,16)}var lr,mr=R({"src/middleware/confirmation.ts"(){z(),ir=6e4,rr=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:l.randomBytes(32).toString("base64url")})()}}),pr={};async function _r(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=await async function(e,t,i){const{data:r,error:n}=await e.from("items").select("*").eq("id",i).eq("project_id",t).maybeSingle();if(n)throw new Error(n.message);return r}(t,e.project_id,e.item_id);if(!r)return Ut(gt("Item",e.item_id));if(r.deleted_at)return Ut(wt(`Item ${e.item_id} is already deleted`));if(ar(lr)){const t={tool:lr,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const i=sr(t);return Ct(ut({status:"confirmation_required",preview:{id:e.item_id,title:r.title,type:r.type,would_soft_delete:!0},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_delete_item with the same project_id, item_id, and confirmation_token within ${i.expires_in_seconds}s to execute.`}))}const i=or(e.confirmation_token,t);if(!i.valid)return Ut(wt(`confirmation_token rejected: ${i.reason}`))}const{error:n}=await t.rpc("soft_delete_item_with_revision",{p_item_id:e.item_id,p_project_id:e.project_id,p_user_id:i,p_expected_updated_at:r.updated_at,p_event_source:"mcp",p_actor:Sa(),p_session_id:ja()});if(n)throw new Error(n.message);return Ct(ut({id:e.item_id,title:r.title,type:r.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return Ut(Ot(e))}}C(pr,{deleteItemHandler:()=>_r});var ur=R({"src/tools/delete-item.ts"(){Ce(),Gt(),ka(),mr(),Tt(),lr="atoms_delete_item"}}),fr={};async function hr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const{data:r,error:n}=await t.from("items").select("*").eq("id",e.item_id).eq("project_id",e.project_id).maybeSingle();if(n)throw new Error(n.message);if(!r)return Ut(gt("Item",e.item_id));if(!r.deleted_at)return Ut(ht(`Item ${e.item_id} is not deleted and cannot be restored.`,["Use atoms_get_item to view the current item state","Use atoms_delete_item first if you intended to delete it"]));const{error:a}=await t.rpc("save_item_with_revision",{p_item_id:e.item_id,p_project_id:e.project_id,p_type:r.type,p_title:r.title,p_data:r.data,p_user_id:i,p_event_source:"restore",p_event_session_id:ja()??null,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:r.updated_at});if(a)throw new Error(a.message);const{error:s}=await t.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:e.project_id,p_item_id:e.item_id});if(s)throw new Error(`Relationship repair failed: ${s.message}`);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"restored",old_data:null,new_data:r.data,actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Ct(ut({id:e.item_id,title:r.title,type:r.type,restored:!0,message:`Item ${e.item_id} restored successfully.`}))}catch(e){return Ut(Ot(e))}}C(fr,{restoreItemHandler:()=>hr});var gr=R({"src/tools/restore-item.ts"(){Ce(),ka(),Tt()}}),yr={};async function wr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=async(r,n,a)=>{const s=await Lt(t,e.project_id,r.from_id);if(!s)throw new Error(`Item "${r.from_id}" not found`);const o=await Lt(t,e.project_id,r.to_id);if(!o)throw new Error(`Item "${r.to_id}" not found`);const{error:d}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r.from_id,p_to_id:r.to_id,p_type:r.type,p_action:r.action,p_user_id:i,p_event_source:"mcp",p_expected_from_updated_at:r.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:r.expected_to_updated_at??o.updated_at});if(d)throw new Error(d.message);const c={item_id:r.from_id,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:null,new_data:{relationship_change:{action:r.action,type:r.type,from:r.from_id,to:r.to_id}},actor:Sa(),session_id:ja()};n&&(c.batch_id=n),a&&(c.reason=a),await t.from("change_history").insert(c).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})};if(e.operations&&Array.isArray(e.operations)){for(const t of e.operations)if(t.from_id===t.to_id)return Ut(wt(`Self-reference in batch: "${t.from_id}"`));const i=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],{data:n}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",i),a=new Set((n??[]).map(e=>e.id)),s=i.filter(e=>!a.has(e));if(s.length>0)return Ut(gt("Items",s.join(", ")));const{data:o}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),d=new Map;for(const e of o??[])"parent"===e.type&&(d.has(e.from_id)||d.set(e.from_id,new Set),d.get(e.from_id).add(e.to_id));for(const t of e.operations){if("parent"!==t.type&&"child"!==t.type)continue;const[e,i]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?d.get(e)?.delete(i):(d.has(e)||d.set(e,new Set),d.get(e).add(i))}const c=0,l=1,m=2,p=new Map,_=new Set;for(const[e,t]of d){_.add(e);for(const e of t)_.add(e)}const u=e=>{if((p.get(e)??c)!==c)return null;const t=[],i=[],r=e=>{p.set(e,l),i.push(e),t.push({node:e,parents:[...d.get(e)??[]],idx:0})};for(r(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){p.set(e.node,m),i.pop(),t.pop();continue}const n=e.parents[e.idx];e.idx++;const a=p.get(n)??c;if(a===l){const e=i.indexOf(n);return[...i.slice(e),n]}a!==m&&r(n)}return null};for(const e of _){const t=u(e);if(t)return Ut(wt(`Batch would create a cycle: ${t.join(" -> ")}. No changes applied.`))}const f=crypto.randomUUID(),h=e.operations.filter(e=>"remove"===e.action),g=e.operations.filter(e=>"add"===e.action);for(const t of[...h,...g])await r(t,f,e.reason);return Ct(ut({batch_id:f,processed:e.operations.length,operations:!1===e.echo?void 0:e.operations}))}return e.from_id&&e.to_id&&e.type&&e.action?e.from_id===e.to_id?Ut(wt("Cannot create a relationship between an item and itself")):(await r({action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type,expected_from_updated_at:e.expected_from_updated_at,expected_to_updated_at:e.expected_to_updated_at},void 0,e.reason),!1===e.echo?Ct(ut({action:e.action,from_id:e.from_id,to_id:e.to_id})):Ct(ut({action:e.action,type:e.type,from_id:e.from_id,to_id:e.to_id,message:`Relationship ${"add"===e.action?"added":"removed"}: ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`}))):Ut(wt("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."))}catch(e){return Ut(Ot(e))}}C(yr,{linkItemsHandler:()=>wr});var br=R({"src/tools/link-items.ts"(){Ce(),Gt(),ka(),Tt()}}),vr=R({"src/core/bulk-parent-links.ts"(){}}),jr={};function Sr(e){return new Set(["22023","23503","23505","23514"]).has(e.code??"")}async function xr(e){try{if(!e.items||0===e.items.length)return Ut(wt("items array must contain at least 1 item"));if(e.items.length>100)return Ut(wt(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=await async function(e,t,i){const{data:r}=await e.from("metadata").select("domains").eq("project_id",t).maybeSingle(),n=r?.domains??[],a=n.length>0?new Set(n.map(_t).filter(e=>e.length>0)):null,s=cr(n.map(_t).filter(e=>e.length>0).sort()),o=[],d=new Set,c={};for(let e=0;e<i.length;e++){const t=i[e];if(c[t.type]=(c[t.type]??0)+1,!a)continue;const r=(t.domains??[]).map(_t).filter(e=>e.length>0);if(0===r.length)continue;const s=r.filter(e=>!a.has(e));s.length>0&&(d.add(e),o.push({index:e,title:t.title,error:`Unknown domain${s.length>1?"s":""}: ${s.join(", ")}. Registered: ${n.join(", ")}.`}))}return{registeredDomains:n,registeredDomainHash:s,invalidDomainIndexes:d,errors:o,typeBreakdown:c}}(t,e.project_id,e.items);if(ar("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:cr({items:e.items,registered_domain_hash:r.registeredDomainHash})};if(!e.confirmation_token){const i=sr(t);return Ct(ut({status:"confirmation_required",preview:{total_items:e.items.length,by_type:r.typeBreakdown,sample_titles:e.items.slice(0,5).map(e=>e.title),would_fail:r.errors.length>0,errors:r.errors,registered_domain_hash:r.registeredDomainHash},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_bulk_import with the same project_id, items array, and confirmation_token within ${i.expires_in_seconds}s to execute. Changing items or project domains will invalidate the token.`}))}const i=or(e.confirmation_token,t);if(!i.valid)return Ut(wt(`confirmation_token rejected: ${i.reason}`))}const n=(new Date).toISOString(),a=ja(),s=[],o=[...r.errors],d=[];for(let i=0;i<e.items.length;i++){const n=e.items[i];if(r.invalidDomainIndexes.has(i))continue;const a=(n.domains??[]).map(_t).filter(e=>e.length>0),s=void 0!==n.level?_t(n.level):void 0;try{const r=await Qt(t,e.project_id,n.type);d.push({itemId:r,input:n,sanitizedDomains:a,sanitizedLevel:s,index:i})}catch(e){o.push({index:i,title:n.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===d.length)return Ct(ut({created:0,items:[],errors:o}));const c=[],l=new Map;for(const{itemId:t,input:r,sanitizedDomains:a,sanitizedLevel:s}of d){const o={id:t,type:r.type,title:r.title,summary:r.summary,body:r.body,tags:{domains:a,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:r.parent_id?[r.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:n,created_by:i,updated_at:n,updated_by:i}};l.set(t,o),c.push({id:t,project_id:e.project_id,type:r.type,title:r.title,data:o,created_by:i,updated_by:i})}const m=c.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:p}=await t.rpc("bulk_save_items_with_revisions",{p_project_id:e.project_id,p_items:m,p_user_id:i,p_event_source:"mcp"});if(p&&Sr(p))for(const{itemId:r,input:n,index:l}of d){const d=c.find(e=>e.id===r);if(!d)continue;const{error:m}=await t.rpc("save_item_with_revision",{p_item_id:d.id,p_project_id:e.project_id,p_type:d.type,p_title:d.title,p_data:d.data,p_user_id:i,p_event_source:"mcp",p_event_session_id:a,p_diff_summary:null});m?o.push({index:l,title:n.title,error:m.message}):s.push({id:r,title:n.title,type:n.type})}else{if(p)throw p;for(const{itemId:e,input:t}of d)s.push({id:e,title:t.title,type:t.type})}const _=d.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:t,input:i})=>({from_id:t,to_id:i.parent_id,type:"parent",project_id:e.project_id}));await async function(e){for(const t of e.links){const{error:i}=await e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:t.from,p_to_id:t.to,p_type:"parent",p_action:"add",p_user_id:e.userId,p_event_source:"mcp"});i&&e.warn(`bulk parent link sync failed for ${t.to}: ${i.message??"unknown error"}`)}}({client:t,projectId:e.project_id,links:_.map(e=>({from:e.from_id,to:e.to_id})),userId:i,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const u=s.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:l.get(t.id)??null,actor:Sa(),session_id:a}));u.length>0&&await t.from("change_history").insert(u).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const f=new Set(s.map(e=>e.id)),h=new Set(d.filter(({itemId:e,sanitizedLevel:t})=>t&&f.has(e)).map(({sanitizedLevel:e})=>e));for(const i of h)await Oi(t,e.project_id,i);return Ct(ut({created:s.length,items:s,errors:o.length>0?o:[],project_id:e.project_id}))}catch(e){return Ut(Ot(e))}}C(jr,{bulkImportHandler:()=>xr,canRetryBulkImportPerItem:()=>Sr});var kr=R({"src/tools/bulk-import.ts"(){Ce(),Gt(),ka(),mr(),Tt(),vr(),Ui()}}),Ir={};async function Er(e){try{const t=await Se(),i=Ee(),r=Ae();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const n=await Lt(t,e.project_id,e.item_id);if(!n)return Ut(gt("Item",e.item_id));if("test-case"!==n.type)return Ut(wt(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const a=(e.asset??"").trim(),s=(new Date).toISOString(),{data:o,error:d}=await t.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:r||i,p_actor_user_id:i,p_results:[{result:e.result,note:e.note,asset:a||void 0,date:s}]});if(d)throw new Error(d.message);const c=Array.isArray(o)?o[0]:o?.[0];await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:s,note:e.note,asset:a||null},actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const l=a?` (asset: ${a})`:"";return Ct(ut({item_id:e.item_id,result:e.result,run_at:s,run_by:r||i,note:e.note??null,asset:a||null,asset_id:c?.asset_id??null,asset_created:c?.asset_created??!1,message:`Test result '${e.result}' recorded for ${e.item_id}${l}`}))}catch(e){return Ut(Ot(e))}}C(Ir,{recordTestResultHandler:()=>Er});var Ar=R({"src/tools/record-test-result.ts"(){Ce(),Gt(),ka(),Tt()}}),Or={};async function Hr(e){try{const t=await Se(),i=Ee(),r=Ae();if(!Array.isArray(e.results)||0===e.results.length)return Ut(wt("results must be a non-empty array"));if(e.results.length>100)return Ut(wt(`results must have at most 100 entries (got ${e.results.length})`));try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const n=await Lt(t,e.project_id,e.item_id);if(!n)return Ut(gt("Item",e.item_id));if("test-case"!==n.type)return Ut(wt(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const{data:a,error:s}=await t.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:r||i,p_actor_user_id:i,p_results:e.results});if(s)throw new Error(s.message);return t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"test_result_recorded",old_data:null,new_data:{bulk:!0,count:e.results.length,results:a},actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Ct(ut({item_id:e.item_id,count:e.results.length,results:a,message:`Recorded ${e.results.length} test results for ${e.item_id}`}))}catch(e){return Ut(Ot(e))}}C(Or,{recordTestResultsBulkHandler:()=>Hr});var Dr,Rr,Cr,Ur,Mr=R({"src/tools/record-test-results-bulk.ts"(){Ce(),Gt(),ka(),Tt()}});function Tr(e){return Math.min(Math.max(e??5,1),10)}var qr=R({"src/core/trace-graph.ts"(){Dr=200,Rr=new Set(["parent","verifies","mitigated_by"]),Cr=new Set(["child","verified_by","mitigates"]),Ur={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"}}}),Pr={};async function $r(e){try{const t=Tr(e.depth),i=await Se(),r=await Lt(i,e.project_id,e.item_id);if(!r)return Ut(gt("Item",e.item_id));const{data:n,error:a}=await i.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);const{data:s,error:o}=await i.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);const d=Jt(n??[],s??[]);return Ct(ut(function(e){const t=Tr(e.depth),i=e.relationshipTypes?.length?new Set(e.relationshipTypes):null,r=new Map(e.items.map(e=>[e.id,e]));r.has(e.rootItemId)||r.set(e.rootItemId,e.rootItem);const n=new Map,a=(e,t,i)=>{n.has(e)||n.set(e,[]),n.get(e).push({neighbor:t,relType:i})};for(const t of e.relationships){const r=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(!Rr.has(r)||i&&!i.has(r)||a(t.from_id,t.to_id,r),Cr.has(r))){const e=Ur[r]??r;i&&!i.has(e)||a(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!Cr.has(r)||i&&!i.has(r)||a(t.from_id,t.to_id,r),Rr.has(r))){const e=Ur[r]??r;i&&!i.has(e)||a(t.to_id,t.from_id,e)}"related"!==r||i&&!i.has("related")||(a(t.from_id,t.to_id,"related"),a(t.to_id,t.from_id,"related"))}const s=new Set([e.rootItemId]),o=[],d=[],c=[];for(const t of n.get(e.rootItemId)??[])c.push({id:t.neighbor,depth:1,relType:t.relType,from:e.rootItemId});for(;c.length>0&&o.length<Dr;){const{id:e,depth:i,relType:a,from:l}=c.shift();if(s.has(e)||i>t)continue;s.add(e);const m=r.get(e);if(m&&(o.push({id:e,title:m.title,type:m.type,relationship:a,depth:i,from:l}),d.push({from:l,to:e,type:a}),i<t))for(const t of n.get(e)??[])s.has(t.neighbor)||c.push({id:t.neighbor,depth:i+1,relType:t.relType,from:e})}const l={id:e.rootItemId,title:e.rootItem.title,type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId};return{root:e.rootItemId,project_id:e.projectId,direction:e.direction,depth_limit:t,items:[l,...o],edges:d,total_count:o.length+1,...o.length>=Dr?{truncated:!0,truncation_message:`Results capped at ${Dr} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown"},items:n??[],relationships:d??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(Pr,{traceHandler:()=>$r});var Nr=R({"src/tools/trace.ts"(){Ce(),Gt(),qr(),Tt()}}),Lr={};async function Fr(e){try{let t=(await Se()).from("assets").select("id, name, archived_at, created_at").eq("project_id",e.project_id).order("name");e.include_archived||(t=t.is("archived_at",null));const{data:i,error:r}=await t;if(r)throw new Error(r.message);return Ct(ut({assets:i||[],total:(i||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(Lr,{listAssetsHandler:()=>Fr});var Wr=R({"src/tools/assets.ts"(){Ce(),Tt()}}),Vr={};async function Br(e,t,i,r){if(i&&r)throw new Error("baseline_id and as_of are mutually exclusive");if(r)return r;if(!i)return null;const{data:n,error:a}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",i).maybeSingle();if(a)throw new Error(a.message);if(!n||n.project_id!==t||n.deleted_at)throw new Error("Baseline not found for this project");return n.snapshot_at}async function zr(e,t,i){if(i){const{data:r,error:n}=await e.rpc("variables_at",{p_project_id:t,p_snapshot_at:i});if(n)throw new Error(n.message);return r??[]}const{data:r,error:n}=await e.from("project_variables").select("*").eq("project_id",t).order("name");if(n)throw new Error(n.message);return r??[]}async function Jr(e,t,i,r){const{data:n,error:a}=await e.rpc("save_variable_with_revision",{p_project_id:t.project_id,p_name:t.name,p_value:t.value,p_unit:t.unit??null,p_description:t.description??null,p_is_signal:t.is_signal??!1,p_range_min:t.range_min??null,p_range_max:t.range_max??null,p_rate_ms:t.rate_ms??null,p_user_id:i,p_event_source:r,p_variable_id:t.id??null});if(a)throw new Error(a.message);return n}async function Qr(e){try{const t=await Se(),i=await Br(t,e.project_id,e.baseline_id,e.as_of),r=await zr(t,e.project_id,i);return Ct(ut({variables:r,total:r.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Gr(e){try{const t=await Se(),i=await Br(t,e.project_id,e.baseline_id,e.as_of),r=(await zr(t,e.project_id,i)).find(t=>t.name===e.variable_name)??null;if(!r)return Ut(gt("Variable",e.variable_name));const{data:n}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),a=`{${e.variable_name}}`,s=(n||[]).filter(e=>(e.data?.body||"").includes(a));return Ct(ut({variable:r,referenced_by:s.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:s.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Yr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(!r.data)return Ut(gt("Variable",e.variable_name));const n={updated_by:i,updated_at:(new Date).toISOString()};return void 0!==e.value&&(n.value=e.value),void 0!==e.unit&&(n.unit=e.unit||null),void 0!==e.description&&(n.description=e.description||null),Ct(ut({variable:await Jr(t,{...r.data,...n,project_id:e.project_id,name:e.variable_name,value:n.value??r.data.value,unit:n.unit??r.data.unit,description:n.description??r.data.description},i,"mcp")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Kr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const n=e.variables.filter(e=>!r.test(e.name));if(n.length>0)return Ut(wt(`Invalid variable name(s): ${n.map(e=>e.name).join(", ")}. Use letters, digits, underscores; must start with letter or underscore.`));const a=e.variables.map(e=>e.name),s=a.filter((e,t)=>a.indexOf(e)!==t);if(s.length>0)return Ut(wt(`Duplicate names in batch: ${[...new Set(s)].join(", ")}`));const{data:o}=await t.from("project_variables").select("name").eq("project_id",e.project_id).in("name",a),d=(o??[]).map(e=>e.name);if(d.length>0)return Ut(wt(`Variable(s) already exist: ${d.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const c=e.variables.map(t=>({project_id:e.project_id,name:t.name,value:t.value,unit:t.unit??null,description:t.description??null,created_by:i,updated_by:i})),l=await async function(e,t,i,r){const{data:n,error:a}=await e.rpc("bulk_save_variables_with_revisions",{p_project_id:t,p_variables:i,p_user_id:r,p_event_source:"mcp"});if(a)throw new Error(a.message);return n??[]}(t,e.project_id,c,i);return Ct(ut({batch_id:crypto.randomUUID(),created:(l??[]).length,variables:!1===e.echo?(l??[]).map(e=>({name:e.name})):l??[],message:`${(l??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`}))}if(!e.name||!e.value)return Ut(wt("Provide either (name, value) for single variable or variables[] for batch."));if(!r.test(e.name))return Ut(wt(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const{data:n}=await t.from("project_variables").select("name").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(n)return Ut(wt(`Variable "${e.name}" already exists in this project.`));const a=await Jr(t,{project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null},i,"mcp");return!1===e.echo?Ct(ut({name:e.name})):Ct(ut({variable:a,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Zr(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const{data:r}=await t.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!r)return Ut(gt("Variable",e.name));const{data:n}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->>body","ilike",`%{${e.name}}%`),a=(n??[]).length;if(a>0&&!e.force)return Ut(wt(`Variable "${e.name}" is referenced in ${a} item${a>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(ar("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const i=sr(t);return Ct(ut({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:a,would_orphan_references:a>0},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_delete_variable with the same project_id, name, and confirmation_token within ${i.expires_in_seconds}s to execute.`}))}const i=or(e.confirmation_token,t);if(!i.valid)return Ut(wt(`confirmation_token rejected: ${i.reason}`))}const s=await async function(e,t,i,r){const{data:n,error:a}=await e.rpc("delete_variable_with_revision",{p_project_id:t,p_variable_id:i,p_user_id:r,p_event_source:"mcp"});if(a)throw new Error(a.message);return Boolean(n)}(t,e.project_id,r.id,i);return s?Ct(ut({deleted:!0,name:e.name,referenced_by_items:a,warning:a>0?`${a} item${a>1?"s":""} still contain {${e.name}} — those references are now unresolved.`:void 0})):Ut(gt("Variable",e.name))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(Vr,{createVariableHandler:()=>Kr,deleteVariableHandler:()=>Zr,getVariableHandler:()=>Gr,listVariablesHandler:()=>Qr,updateVariableHandler:()=>Yr});var Xr=R({"src/tools/variables.ts"(){Ce(),mr(),Tt()}}),en={};async function tn(e,t){const{data:i}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:i?.domains??[],levels:i?.levels??[]}}async function rn(e,t,i,r){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:i,levels:r},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function nn(e){try{const t=await Se(),{domains:i}=await tn(t,e.project_id),{counts:r,orphans:n}=await async function(e,t,i){const{data:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null),n={};for(const e of i)n[e]=0;const a={};for(const e of r??[]){const t=e.data?.tags?.domains??[];for(const e of t)a[e]=(a[e]??0)+1,e in n&&n[e]++}const s=new Set(i),o={};for(const[e,t]of Object.entries(a))s.has(e)||(o[e]=t);return{counts:n,orphans:o}}(t,e.project_id,i),a=i.map(e=>({name:e,registered:!0,item_count:r[e]??0})),s=Object.entries(n).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),o=[...a,...s];return Ct(ut({domains:o,total:o.length,registered_count:a.length,unregistered_count:s.length,note:s.length>0?`${s.length} unregistered tag(s) found on items. Use atoms_create_domain to register them, or atoms_update_item to remove them.`:void 0}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function an(e){try{const t=await Se();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const{domains:i,levels:r}=await tn(t,e.project_id),n=e.name.trim().toLowerCase();return n?i.includes(n)?Ut(wt(`Domain "${n}" already exists in this project.`)):(await rn(t,e.project_id,[...i,n],r),Ct(ut({domain:{name:n},message:`Domain "${n}" registered. You can now tag items with domains=["${n}"].`}))):Ut(wt("Domain name cannot be empty."))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function sn(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const{domains:r,levels:n}=await tn(t,e.project_id),a=e.name.trim().toLowerCase(),s=e.new_name.trim().toLowerCase();if(!s)return Ut(wt("new_name cannot be empty."));const o=r.includes(a);if(!o){const{data:i}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a])).limit(1);if(!i||0===i.length)return Ut(gt("Domain",a))}if(s!==a&&r.includes(s))return Ut(wt(`Domain "${s}" already exists. Choose a different name.`));const{data:d,error:c}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(c)throw new Error(c.message);const l=(d??[]).length;if(e.dry_run)return Ct(ut({dry_run:!0,rename:{from:a,to:s},items_affected:l,message:`Dry run: renaming "${a}" → "${s}" would update ${l} item${1!==l?"s":""}. Call again with dry_run=false to apply.`}));let m;m=o?r.map(e=>e===a?s:e):r.includes(s)?r:[...r,s],await rn(t,e.project_id,m,n);const{error:p}=await t.rpc("apply_domain_change",{p_project_id:e.project_id,p_old_domain:a,p_new_domain:s,p_user_id:i,p_event_source:"mcp"});if(p)throw new Error(p.message);return Ct(ut({domain:{name:s},renamed_from:a,items_updated:l,message:`Domain renamed "${a}" → "${s}". ${l} item${1!==l?"s":""} updated.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}async function on(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const{domains:r,levels:n}=await tn(t,e.project_id),a=e.name.trim().toLowerCase(),s=r.includes(a),{data:o,error:d}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(d)throw new Error(d.message);const c=(o??[]).length;if(!s&&0===c)return Ut(gt("Domain",a));if(c>0&&!e.force)return Ut(wt(`Domain "${a}" is used by ${c} item${c>1?"s":""}. Use force=true to delete and strip the domain from all items, or re-tag them first.`));if(ar("atoms_delete_domain")){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:a};if(!e.confirmation_token){const e=sr(t);return Ct(ut({status:"confirmation_required",preview:{domain_name:a,items_using_count:c,would_strip_from_items:c>0},confirmation_token:e.token,expires_at:e.expires_at,expires_in_seconds:e.expires_in_seconds,message:`Re-call atoms_delete_domain with the same project_id, name, and confirmation_token within ${e.expires_in_seconds}s to execute.`}))}const i=or(e.confirmation_token,t);if(!i.valid)return Ut(wt(`confirmation_token rejected: ${i.reason}`))}const l=s?r.filter(e=>e!==a):r;if(await rn(t,e.project_id,l,n),c>0){const{error:r}=await t.rpc("apply_domain_change",{p_project_id:e.project_id,p_old_domain:a,p_new_domain:null,p_user_id:i,p_event_source:"mcp"});if(r)throw new Error(r.message)}return Ct(ut({deleted:!0,name:a,items_updated:c,message:c>0?`Domain "${a}" deleted and stripped from ${c} item${c>1?"s":""}.`:`Domain "${a}" deleted.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(en,{createDomainHandler:()=>an,deleteDomainHandler:()=>on,listDomainsHandler:()=>nn,updateDomainHandler:()=>sn});var dn=R({"src/tools/domains.ts"(){Ce(),mr(),Tt()}}),cn={};async function ln(e){try{const t=await Se(),{data:i,error:r}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle(),n=i?.name??null,a=r?.message??null,{data:s,error:o}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(o)throw new Error(o.message);const d=s??[];if(!n&&0===d.length){if(a)throw new Error(a);return Ut(gt("Project",e.project_id))}const c={requirements:0,test_cases:0,notes:0},l=[],m=[];for(const e of d)if("requirement"===e.type){c.requirements++;const t=e.data?.tags?.domains??[];m.push({id:e.id,domains:t})}else"test-case"===e.type?(c.test_cases++,l.push(e.id)):"note"===e.type&&c.notes++;const p={passed:0,failed:0,blocked:0,not_run:0};if(l.length>0){const{data:i,error:r}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(r)throw new Error(r.message);const n=new Map;for(const e of i??[])n.has(e.item_id)||n.set(e.item_id,e.result);for(const e of l){const t=n.get(e);t&&"not-run"!==t?"passed"===t?p.passed++:"failed"===t?p.failed++:"blocked"===t?p.blocked++:p.not_run++:p.not_run++}}const{data:_,error:u}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(u)throw new Error(u.message);const f=Jt(s??[],_??[]),h=new Set;for(const e of f)"verifies"===e.type?h.add(e.to_id):"verified_by"===e.type&&h.add(e.from_id);const g=m.filter(e=>h.has(e.id)).length,y=m.length,w={covered:g,uncovered:y-g,total:y,percent:y>0?Math.round(g/y*1e3)/10:100},b=new Map;for(const e of m){const t=e.domains.length>0?e.domains:["(untagged)"],i=h.has(e.id);for(const e of t){b.has(e)||b.set(e,{covered:0,total:0});const t=b.get(e);t.total++,i&&t.covered++}}const v=Array.from(b.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:t.total>0?Math.round(t.covered/t.total*1e3)/10:100})),j=new Date;j.setDate(j.getDate()-7);const{count:S,error:x}=await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",j.toISOString());if(x)throw new Error(x.message);return Ct(ut({project_id:e.project_id,project_name:n??`Project ${e.project_id.slice(0,8)}`,counts:c,test_status:p,coverage:w,coverage_by_domain:v,recent_changes:S??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(cn,{projectSummaryHandler:()=>ln});var mn,pn=R({"src/tools/project-summary.ts"(){Ce(),Gt(),Tt()}}),_n={};async function un(e){try{const t=await Se();let i,r;if(e.query&&e.query.trim().length>0){const n=await zt(t,e.project_id,e.query,{type:e.type,limit:e.limit});i=n.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=n.totalCount}else{const n=await Nt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});i=n.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=n.totalCount}const n=await async function(e,t){const{data:i,error:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(r)throw new Error(r.message);const n=new Set,a=new Set;for(const e of i??[]){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)n.add(t);const i=t.level;i&&a.add(i)}}return{domains:[...n].sort(),levels:[...a].sort()}}(t,e.project_id);return Ct(ut({items:i,filters:{domains:n.domains,levels:n.levels,types:mn},project_id:e.project_id},ft(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(_n,{browseHandler:()=>un});var fn,hn,gn,yn,wn=R({"src/tools/browse.ts"(){Ce(),Gt(),Tt(),mn=["requirement","test-case","note","table"]}}),bn={};async function vn(e){try{const t=e.direction??"downstream",i=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await Se(),n=await Lt(r,e.project_id,e.item_id);if(!n)return Ut(gt("Item",e.item_id));const{data:a,error:s}=await r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(s)throw new Error(s.message);const{data:o,error:d}=await r.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(d)throw new Error(d.message);const c=new Map;for(const e of o??[])c.set(e.id,{title:e.title,type:e.type});const l=new Map,m=(e,t,i)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:i})};for(const e of a??[]){const i=e.type;"upstream"!==t&&"both"!==t||(hn.includes(i)&&m(e.from_id,e.to_id,i),gn.includes(i)&&m(e.to_id,e.from_id,yn[i]??i)),"downstream"!==t&&"both"!==t||(gn.includes(i)&&m(e.from_id,e.to_id,i),hn.includes(i)&&m(e.to_id,e.from_id,yn[i]??i)),"related"===i&&(m(e.from_id,e.to_id,"related"),m(e.to_id,e.from_id,"related"))}const p=new Set;p.add(e.item_id);const _=[];let u=0;const f=[];for(const t of l.get(e.item_id)??[])f.push({id:t.neighbor,depth:1,path:[{from_id:e.item_id,to_id:t.neighbor,relationship_type:t.relType}]});for(;f.length>0&&_.length<fn;){const{id:e,depth:t,path:r}=f.shift();if(p.has(e))continue;if(null!==i&&t>i)continue;p.add(e);const n=c.get(e);if(n&&(_.push({item_id:e,title:Rt(n.title),type:n.type,depth:t,relationship_path:r}),t>u&&(u=t),null===i||t<i))for(const i of l.get(e)??[])p.has(i.neighbor)||f.push({id:i.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:i.neighbor,relationship_type:i.relType}]})}let h=0;if(e.include_variable_refs){const{data:t}=await r.from("variable_references").select("variable_id").eq("item_id",e.item_id).eq("project_id",e.project_id),i=[...new Set((t??[]).map(e=>e.variable_id))];if(i.length>0){const{data:t}=await r.from("project_variables").select("id, name").in("id",i),n=new Map((t??[]).map(e=>[e.id,e.name])),{data:a}=await r.from("variable_references").select("variable_id, item_id").in("variable_id",i).eq("project_id",e.project_id).neq("item_id",e.item_id);for(const t of a??[]){const i=t.item_id;if(p.has(i))continue;if(_.length>=fn)break;p.add(i);const r=c.get(i);if(!r)continue;const a=n.get(t.variable_id)??t.variable_id;_.push({item_id:i,title:Rt(r.title),type:r.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:i,relationship_type:`variable_ref:${a}`}]}),h++}}}const g={};for(const e of _)g[e.type]=(g[e.type]??0)+1;const y=c.get(e.item_id);return Ct(ut({root:{item_id:e.item_id,title:Rt(y?.title??n.title),type:y?.type??n.type},impacted_items:_,summary:{total_impacted:_.length,by_type:g,max_depth_reached:u,...h>0?{variable_impact_count:h}:{},..._.length>=fn?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):Ut(Dt(e instanceof Error?e.message:String(e)))}}C(bn,{impactAnalysisHandler:()=>vn});var jn=R({"src/tools/impact-analysis.ts"(){Ce(),Gt(),Tt(),fn=200,hn=["parent","verifies","traces_to","allocated_from","decomposed_from"],gn=["child","verified_by","allocated_to","decomposes_to","traced_by"],yn={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related",traces_to:"traced_by",traced_by:"traces_to",allocated_to:"allocated_from",allocated_from:"allocated_to",decomposes_to:"decomposed_from",decomposed_from:"decomposes_to"}}}),Sn=R({"src/core/relationship-sync.ts"(){}}),xn={};function kn(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ut(bt()):null}async function In(e,t){const{data:i,error:r}=await e.rpc("restore_baseline_state",{p_baseline_id:t.baselineId,p_project_id:t.projectId,p_items:[],p_variables:[],p_user_id:t.userId});if(r)throw new Error(r.message);return i}async function En(e,t,i){const{data:r,error:n}=await e.from("items").select("id, deleted_at").eq("project_id",t).eq("id",i).maybeSingle();if(n)throw new Error(n.message);if(a=r,!Boolean(a?.id&&null===a.deleted_at))return;var a;const{error:s}=await e.rpc("sync_item_relationships_from_jsonb",{p_project_id:t,p_item_id:i});if(s)throw new Error(s.message)}async function An(e,t,i){const{data:r,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n)return Ut(Dt(n.message));if(!r)return Ut(gt("Project",t));const{data:a,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?Ut(Dt(s.message)):!0!==(a?.feature_flags??{})[i]?Ut(ht(`Feature '${i}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function On(e){try{const t=await Se(),i=await async function(e,t){const{data:i,error:r}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1});if(r)throw new Error(`listBaselines: ${r.message}`);return i??[]}(t,e.project_id),r=Math.max(e.offset??0,0),n=Math.min(Math.max(e.limit??50,1),100);return Ct(ut({baselines:i.slice(r,r+n).map(e=>({id:e.id,name:e.name,description:e.description,field_definitions_snapshot:e.field_definitions_snapshot,snapshot_at:e.snapshot_at,created_at:e.created_at,created_by:e.created_by,locked:null!==e.locked_at,locked_at:e.locked_at})),total:i.length,offset:r,limit:n}))}catch(e){return kn(e)??Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Hn(e){try{const t=await Se(),i=await An(t,e.project_id,"baselines_enabled");if(i)return i;const{data:r,error:n}=await t.from("baselines").insert({project_id:e.project_id,name:e.name.trim(),description:e.description??null,snapshot_at:(new Date).toISOString()}).select().single();return n?"23505"===n.code?Ut(ht(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):Ut(Dt(n.message)):Ct(ut({id:r.id,name:r.name,description:r.description,field_definitions_snapshot:r.field_definitions_snapshot,snapshot_at:r.snapshot_at,created_at:r.created_at,locked:!1}))}catch(e){return kn(e)??Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Dn(e){try{const t=await Se(),i=await Wt(t,e.baseline_id);if(!i)return Ut(gt("Baseline",e.baseline_id));const r=await An(t,i.project_id,"baselines_enabled");if(r)return r;if(null!==i.locked_at)return Ut(ht("Baseline is already locked",["Locks are one-way; nothing to do"]));const{data:n}=await t.from("projects").select("org_id").eq("id",i.project_id).maybeSingle();if(!n)return Ut(gt("Project",i.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ut(bt());const{data:o}=await t.from("org_members").select("role").eq("user_id",s).eq("org_id",n.org_id).maybeSingle();if(!o||"admin"!==o.role)return Ut(ht("Only admins can lock baselines",["Ask an org admin to lock this baseline"]));const{data:d,error:c}=await t.from("baselines").update({locked_at:(new Date).toISOString(),locked_by:s}).eq("id",e.baseline_id).select().single();return c?Ut(Dt(c.message)):Ct(ut({id:d.id,locked_at:d.locked_at,locked_by:d.locked_by}))}catch(e){return kn(e)??Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Rn(e){try{const t=await Se(),[i,r]=await Promise.all([Wt(t,e.baseline_a_id),Wt(t,e.baseline_b_id)]);if(!i||!r)return Ut(gt("Baseline","one of the baseline_ids"));if(i.project_id!==r.project_id)return Ut(ht("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[n,a]=await Promise.all([Bt(t,i.project_id,i.snapshot_at),Bt(t,r.project_id,r.snapshot_at)]),s=new Map(n.map(e=>[e.id,e])),o=new Map(a.map(e=>[e.id,e])),d=Array.from(new Set([...s.keys(),...o.keys()])).sort(),c=[];let l=0,m=0,p=0;for(const e of d){const t=s.get(e),i=o.get(e);if(!t&&i)l++,c.push({item_id:e,change_type:"added"});else if(t&&!i)m++,c.push({item_id:e,change_type:"removed"});else if(t&&i){const r=[];t.title!==i.title&&r.push("title"),t.type!==i.type&&r.push("type");JSON.stringify(t.data??{})!==JSON.stringify(i.data??{})&&r.push("data"),r.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:r}))}}const _=Math.max(e.offset??0,0),u=Math.min(Math.max(e.limit??50,1),200),f=e.detail?c.slice(_,_+u):c.slice(_,_+u).map(({item_id:e,change_type:t,fields_changed:i})=>({item_id:e,change_type:t,fields_changed:i}));return Ct(ut({summary:{added:l,removed:m,modified:p,total_compared:d.length},items:f,page_info:{offset:_,limit:u,total:c.length},baselines:{a:{id:i.id,name:i.name,snapshot_at:i.snapshot_at},b:{id:r.id,name:r.name,snapshot_at:r.snapshot_at}}}))}catch(e){return kn(e)??Ut(Dt(e instanceof Error?e.message:String(e)))}}async function Cn(e){try{const t=await Se(),i=await Wt(t,e.baseline_id);if(!i)return Ut(gt("Baseline",e.baseline_id));const r=await An(t,i.project_id,"baselines_enabled");if(r)return r;const{data:n}=await t.from("projects").select("org_id").eq("id",i.project_id).maybeSingle();if(!n)return Ut(gt("Project",i.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ut(bt());const{data:o}=await t.from("org_members").select("role").eq("user_id",s).eq("org_id",n.org_id).maybeSingle();if(!o||"admin"!==o.role)return Ut(ht("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const d=await Bt(t,i.project_id,i.snapshot_at),c=d.map(e=>e.id),{data:l,error:m}=c.length>0?await t.from("items").select("*").eq("project_id",i.project_id).in("id",c):{data:[],error:null};if(m)return Ut(Dt(m.message));const p=function(e,t){const i=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=i.get(e.id),r=[];var n,a;return t?(null!==t.deleted_at&&r.push("deleted_at"),t.type!==e.type&&r.push("type"),t.title!==e.title&&r.push("title"),n=t.data,a=e.data,JSON.stringify(n??{})!==JSON.stringify(a??{})&&r.push("data")):r.push("missing"),0===r.length?[]:[{id:e.id,type:e.type,title:e.title,data:e.data??{},diff_summary:{changed_fields:r,restored:!0},oldData:t?.data??null}]})}(d,l??[]),{data:_,error:u}=await t.rpc("variables_at",{p_project_id:i.project_id,p_snapshot_at:i.snapshot_at});if(u)return Ut(Dt(u.message));const f=_??[];if(!0!==e.confirm)return Ct(ut({preview:!0,items_to_restore:p.length,variables_to_restore:f.length,field_definitions_to_restore:i.field_definitions_snapshot?.length??null}));const h=await In(t,{baselineId:i.id,projectId:i.project_id,userId:s});return Ct(ut({ok:!0,items_restored:h.items_restored,variables_restored:h.variables_restored,field_definitions_restored:h.field_definitions.length}))}catch(e){return kn(e)??Ut(Dt(e instanceof Error?e.message:String(e)))}}C(xn,{createBaselineHandler:()=>Hn,diffBaselinesHandler:()=>Rn,listBaselinesHandler:()=>On,lockBaselineHandler:()=>Dn,restoreBaselineHandler:()=>Cn,restoreBaselineStateAtomically:()=>In,syncRestoredItemRelationships:()=>En});var Un,Mn,Tn,qn,Pn,$n,Nn,Ln,Fn,Wn,Vn=R({"src/tools/baselines.ts"(){Ce(),ka(),Tt(),Gt(),Sn()}});function Bn(e){const t=e?.severity||"",i=e?.exposure||"",r=e?.controllability||"";return t&&i&&r?"S0"===t||"E0"===i||"C0"===r?"QM":Tn[`${t}-${i}-${r}`]||Un:Un}function zn(e){const t=parseInt(e?.severity||"",10),i=parseInt(e?.occurrence||"",10),r=parseInt(e?.detection||"",10);return Number.isNaN(t)||Number.isNaN(i)||Number.isNaN(r)?Un:String(t*i*r)}function Jn(e,t){return"hara"===e?Bn(t):zn(t)}function Qn(e,t,i){if(i)return!1;if("hara"===e){const e=Bn(t);return"C"===e||"D"===e}const r=parseInt(zn(t),10);return!Number.isNaN(r)&&r>=200}function Gn(e,t,i){if(!e?.approved||!e.approved_at)return!1;const r=Date.parse(e.approved_at);return!Number.isNaN(r)&&[...e.source_req?[e.source_req]:[],...t].some(e=>{const t=i(e),n=t?Date.parse(t):NaN;return!Number.isNaN(n)&&n>r})}var Yn,Kn,Zn=R({"src/core/analysis.ts"(){Un="—",Mn=["prevention","detection","mitigation"],Tn={"S1-E1-C1":"QM","S1-E1-C2":"QM","S1-E1-C3":"QM","S1-E2-C1":"QM","S1-E2-C2":"QM","S1-E2-C3":"QM","S1-E3-C1":"QM","S1-E3-C2":"QM","S1-E3-C3":"A","S1-E4-C1":"QM","S1-E4-C2":"A","S1-E4-C3":"B","S2-E1-C1":"QM","S2-E1-C2":"QM","S2-E1-C3":"QM","S2-E2-C1":"QM","S2-E2-C2":"QM","S2-E2-C3":"A","S2-E3-C1":"QM","S2-E3-C2":"A","S2-E3-C3":"B","S2-E4-C1":"A","S2-E4-C2":"B","S2-E4-C3":"C","S3-E1-C1":"QM","S3-E1-C2":"QM","S3-E1-C3":"A","S3-E2-C1":"QM","S3-E2-C2":"A","S3-E2-C3":"B","S3-E3-C1":"A","S3-E3-C2":"B","S3-E3-C3":"C","S3-E4-C1":"B","S3-E4-C2":"C","S3-E4-C3":"D"},Pn={hara:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea:{severity:qn=["1","2","3","4","5","6","7","8","9","10"],occurrence:qn,detection:qn}},$n={hara:["failure_mode","operating_scenario","severity","exposure","controllability","safe_state","ftti","rationale"],dfmea:["failure_mode","cause","severity","occurrence","detection","rationale"]},Nn={hara:"safety-goal",dfmea:"failure-mode"},Ln={hara:"SG",dfmea:"FM"},Fn={hara:"HARA",dfmea:"DFMEA"},Wn={hara:"hara_iso26262",dfmea:"dfmea_rpn"}}}),Xn={};function ea(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}async function ta(e,t,i){const{data:r,error:n}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:i});if(n)throw new Error(`ID generation failed: ${n.message}`);return r}function ia(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function ra(e){return JSON.parse(JSON.stringify(e??{}))}async function na(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=e.source_req_ids??[];if(r.length>50)return Ut(wt("source_req_ids supports at most 50 entries per call"));if(r.length>0){const{data:i,error:n}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null).in("id",r);if(n)throw new Error(n.message);const a=new Map((i??[]).map(e=>[e.id,e])),s=r.filter(e=>!a.has(e));if(s.length>0)return Ut(gt("Source requirement(s)",s.join(", ")));const o=r.filter(e=>{const t=a.get(e);return"requirement"!==t.type||Yn.has(t.data?.req_type)});if(o.length>0)return Ut(wt(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${o.join(", ")}`))}const n=e.subtype,a=await ta(t,e.project_id,Fn[n]),s=e.title??("hara"===n?"New HARA":"New DFMEA"),o=e.revision??"1.0",d=Nn[n],c=(new Date).toISOString(),l={id:a,type:"analysis",title:s,body:"",tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis:{subtype:n,scheme:Wn[n],revision:o},metadata:{created_at:c,created_by:i,updated_at:c,updated_by:i}},{error:m}=await t.rpc("save_item_with_revision",{p_item_id:a,p_project_id:e.project_id,p_type:"analysis",p_title:s,p_data:l,p_user_id:i,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null});if(m)throw new Error(m.message);const p=[],_=[];for(const s of r){const r=await ta(t,e.project_id,Ln[n]),o={id:r,type:"requirement",title:"",body:"",req_type:d,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[a],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:{source_req:s,approved:!1,approved_at:null,field_source:{}},metadata:{created_at:c,created_by:i,updated_at:c,updated_by:i}},{error:l}=await t.rpc("save_item_with_revision",{p_item_id:r,p_project_id:e.project_id,p_type:"requirement",p_title:"",p_data:o,p_user_id:i,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null});if(l)throw new Error(l.message);const{error:m}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r,p_to_id:a,p_type:"parent",p_action:"add",p_user_id:i,p_event_source:"mcp"});m&&(process.stderr.write(`[atoms-mcp] Warning: analysis row parent link sync failed for ${r}: ${m.message}\n`),_.push({row_id:r,source_req:s,message:m.message})),await t.from("change_history").insert({item_id:r,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:o,actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),p.push({id:r,source_req:s})}return await t.from("change_history").insert({item_id:a,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:l,actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Ct(ut({id:a,subtype:n,title:Rt(s),revision:o,rows:p,..._.length>0?{link_warnings:_,warning:`${_.length} row(s) were created but could not be attached to the analysis and will not appear in atoms_get_analysis. Repair: for each row in link_warnings, call atoms_link_items with type 'parent', from_id=<row id>, to_id=${a}.`}:{}}))}catch(e){return Ut(Ot(e))}}async function aa(e){try{const t=await Se(),i=Ee();try{await Oe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}const r=await Lt(t,e.project_id,e.row_id);if(!r)return Ut(gt("Analysis row",e.row_id));const n=r.data,a=ea(n?.req_type);if(!a)return Ut(wt(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const s=new Set([...$n[a],"effect"]);"hara"===a&&s.add("title");const o=Object.keys(e.fields??{});if(0===o.length)return Ut(wt("fields must contain at least one key"));const d=o.filter(e=>!s.has(e));if(d.length>0)return Ut(wt(`Unknown field(s) for ${a}: ${d.join(", ")}. Allowed: ${[...s].sort().join(", ")}`));const c=Pn[a],l={};for(const t of o){const i=e.fields[t];if(c[t]){const e="number"==typeof i&&"dfmea"===a?String(i):i;if("string"!=typeof e||!c[t].includes(e))return Ut(wt(`Invalid ${t} value ${JSON.stringify(i)} for ${a}. Allowed: ${c[t].join(", ")}`));l[t]=e}else{if("string"!=typeof i)return Ut(wt(`Field '${t}' must be a string`));l[t]=i}}const m=n?.analysis_props??null,p=ra(n);p.analysis_props&&"object"==typeof p.analysis_props||(p.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const _=p.analysis_props;_.field_source&&"object"==typeof _.field_source||(_.field_source={});let u=r.title;for(const[e,t]of Object.entries(l))"effect"===e?p.body=t:"title"===e?(p.title=t,u=t):(_[e]=t,"failure_mode"===e&&"dfmea"===a&&(p.title=t,u=t)),_.field_source[e]="mcp";const f=(new Date).toISOString();p.metadata={...p.metadata??{},updated_at:f,updated_by:i};const{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:r.id,p_project_id:e.project_id,p_type:r.type,p_title:u,p_data:p,p_user_id:i,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null,p_expected_updated_at:r.updated_at});if(g)throw new Error(g.message);if(!h)return Ut(ht(`Fill silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await t.from("change_history").insert({item_id:r.id,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:n,new_data:p,actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=Jn(a,_),w=[];if("hara"===a){const n=Jn("hara",m),a=ia(p);if(a.length>0&&y!==Un&&y!==n)for(const n of a){const a=await Lt(t,e.project_id,n);if(!a)continue;const s=a.data;if(s?.asil===y&&s?.asil_source===r.id)continue;const o=s?.asil??null,d=s?.asil_source??null,c=ra(s);c.asil=y,c.asil_source=r.id,c.metadata={...c.metadata??{},updated_at:f,updated_by:i};const{error:l}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:c,p_user_id:i,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});if(l)throw new Error(l.message);await t.from("change_history").insert({item_id:a.id,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:{asil:o,asil_source:d},new_data:{asil:y,asil_source:r.id},actor:Sa(),session_id:ja(),reason:`ASIL propagated from ${r.id} (rating change via atoms_fill_row)`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),w.push(n)}}return Ct(ut({row_id:r.id,subtype:a,written_fields:Object.keys(l),computed_level:y,...w.length>0?{asil_propagated_to:w}:{}}))}catch(e){return Ut(Ot(e))}}async function sa(e,t,i){const r=await Lt(e,t,i);if(!r)return{ok:!1,result:Ut(gt("Analysis",i))};if("analysis"!==r.type)return{ok:!1,result:Ut(wt(`Item ${i} is not an analysis (type='${r.type}')`))};const n=r.data,a=ea("hara"===n?.analysis?.subtype?"safety-goal":"dfmea"===n?.analysis?.subtype?"failure-mode":null);if(!a)return{ok:!1,result:Ut(wt(`Analysis ${i} is missing a valid analysis.subtype`))};const s=Nn[a],o=Array.isArray(n?.relationships?.children)?n.relationships.children.filter(e=>"string"==typeof e):[];let d=[];if(o.length>0){const{data:i,error:r}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",o);if(r)throw new Error(r.message);const n=new Map((i??[]).filter(e=>!e.deleted_at&&o.includes(e.id)&&e.data?.req_type===s).map(e=>[e.id,e]));d=o.map(e=>n.get(e)).filter(e=>Boolean(e))}const c=new Set;for(const e of d){const t=e.data?.analysis_props??{};"string"==typeof t.source_req&&t.source_req&&c.add(t.source_req);for(const t of ia(e.data))c.add(t)}const l=new Map;if(c.size>0){const{data:i,error:r}=await e.from("items").select("id, updated_at").eq("project_id",t).is("deleted_at",null).in("id",[...c]);if(r)throw new Error(r.message);for(const e of i??[])l.set(e.id,e.updated_at)}const m=d.map(e=>{const t=e.data?.analysis_props??{},i=ia(e.data).filter(e=>l.has(e)),r=i.length>0,n=Jn(a,t),s=function(e,t,i){if(i)return null;if("hara"===e){const e=Bn(t);return"QM"!==e&&e!==Un?`asil ${e} unmitigated`:null}const r=parseInt(zn(t),10),n=parseInt(t?.severity||"",10);return!Number.isNaN(r)&&r>=100?"rpn >= 100":!Number.isNaN(n)&&n>=9?"severity >= 9":null}(a,t,r),o={id:e.id,title:Rt("string"==typeof e.title?e.title:""),source_req:"string"==typeof t.source_req?t.source_req:null,effect:Rt("string"==typeof e.data?.body?e.data.body:""),computed_level:n,is_gap:null!==s,gap_rule:s,is_critical:Qn(a,t,r),is_stale:Gn(t,i,e=>l.get(e)??null),mitigated_by:i,link_roles:t.link_roles??{},approved:!0===t.approved,approved_at:t.approved_at??null,mcp_fields:Object.entries(t.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort()};for(const e of $n[a]){const i=t[e]??null;o[e]=Kn.has(e)&&"string"==typeof i?Rt(i):i}return o});return{ok:!0,analysis:{id:r.id,title:Rt("string"==typeof r.title?r.title:""),subtype:a,scheme:"string"==typeof n?.analysis?.scheme?n.analysis.scheme:Wn[a],revision:"string"==typeof n?.analysis?.revision?n.analysis.revision:"1.0"},rows:m,counts:{rows:m.length,gaps:m.filter(e=>e.is_gap).length,critical:m.filter(e=>e.is_critical).length,stale:m.filter(e=>e.is_stale).length,approved:m.filter(e=>e.approved).length,linked:m.filter(e=>e.mitigated_by.length>0).length}}}async function oa(e){try{const t=await Se(),i=await sa(t,e.project_id,e.analysis_id);return i.ok?Ct(ut({analysis:i.analysis,rows:i.rows,counts:i.counts})):i.result}catch(e){return Ut(Ot(e))}}async function da(e){try{const n=await Se(),a=Ee();try{await Oe(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ut(yt("Viewer"));throw e}if(e.row_id===e.req_id)return Ut(wt("row_id and req_id must be different items"));const s=await Lt(n,e.project_id,e.row_id);if(!s)return Ut(gt("Analysis row",e.row_id));const o=s.data,d=ea(o?.req_type);if(!d)return Ut(wt(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const c=await Lt(n,e.project_id,e.req_id);if(!c)return Ut(gt("Requirement",e.req_id));const l=c.data;if("requirement"!==c.type||Yn.has(l?.req_type))return Ut(wt(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));if("dfmea"===d&&!e.role)return Ut(wt(`role is required for dfmea mitigation links. Choose one of: ${Mn.join(", ")}`));if("hara"===d&&e.role)return Ut(wt("role is not applicable to hara mitigation links; omit it (roles are a dfmea concept)"));let m=Un;if("hara"===d){m=Jn("hara",o?.analysis_props);const n=l?.asil;if(m!==Un&&"string"==typeof n&&n.length>0&&n!==m&&!0!==e.override)return Ut((i=m,{...ht(`ASIL conflict: the target requirement already carries asil '${t=n}' but ${r=s.id} computes '${i}'.`,["Pass override=true to apply the HARA value; the override is history-logged like a dialog accept","Or align the row's S/E/C ratings with the existing ASIL before linking"]),details:{code:"asil_conflict",current_value:t,incoming_value:i,source_row:r,hint:"pass override=true to apply the HARA value; the override is history-logged like a dialog accept"}}))}const p="dfmea"===d?e.role:null,{error:_}=await n.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:e.row_id,p_to_id:e.req_id,p_type:"mitigated_by",p_action:"add",p_user_id:a,p_event_source:"mcp",p_expected_from_updated_at:s.updated_at,p_expected_to_updated_at:c.updated_at,p_role:p});if(_)throw new Error(_.message);let u;if(await n.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"add",type:"mitigated_by",from:e.row_id,to:e.req_id,...p?{role:p}:{}}},actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),"hara"===d&&m!==Un){const t=await Lt(n,e.project_id,e.req_id);if(t){const i=t.data,r=i?.asil??null,o=i?.asil_source??null,d=ra(i);d.asil=m,d.asil_source=s.id;const c=(new Date).toISOString();d.metadata={...d.metadata??{},updated_at:c,updated_by:a};const{error:l}=await n.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:d,p_user_id:a,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});if(l)throw new Error(l.message);await n.from("change_history").insert({item_id:t.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{asil:r,asil_source:o},new_data:{asil:m,asil_source:s.id},actor:Sa(),session_id:ja(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${r??"unset"}', now '${m}' from ${s.id})`:`ASIL set via atoms_link_mitigation from ${s.id}`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),u=m}}return Ct(ut({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:p,...u?{asil_written:u}:{}}))}catch(e){return Ut(Ot(e))}var t,i,r}async function ca(e){try{const t=await Se(),i=await sa(t,e.project_id,e.analysis_id);if(!i.ok)return i.result;const r=i.rows.filter(e=>e.is_gap).map(e=>({id:e.id,title:e.title,source_req:e.source_req,computed_level:e.computed_level,rule:e.gap_rule}));return Ct(ut({analysis_id:i.analysis.id,subtype:i.analysis.subtype,gaps:r,count:r.length}))}catch(e){return Ut(Ot(e))}}C(Xn,{createAnalysisHandler:()=>na,fillRowHandler:()=>aa,getAnalysisHandler:()=>oa,getGapsHandler:()=>ca,linkMitigationHandler:()=>da});var la,ma,pa,_a,ua,fa,ha,ga,ya=R({"src/tools/analysis.ts"(){Ce(),Gt(),ka(),Tt(),Zn(),Yn=new Set(["safety-goal","failure-mode"]),Kn=new Set(["failure_mode","cause","operating_scenario","safe_state","ftti","rationale"])}}),wa={};function ba(t){G(t.toolName)&&function(t,i){const r=`ui://${i.toolName}/${i.htmlFile}`,n=function(e,t){const i=u(import.meta.url),r=s.dirname(i);return s.resolve(r,"apps","src","apps",e,t)}(i.appName,i.htmlFile),a=[...Mt.resourceDomains,...i.extraResourceDomains??[]];g(t,i.toolName,{title:i.title,description:i.description,inputSchema:i.inputSchema,annotations:i.annotations,_meta:{ui:{resourceUri:r}}},i.handler),y(t,`${i.title} UI`,r,{mimeType:w},async()=>{const t=await e.readFile(n,"utf-8");return{contents:[{uri:r,mimeType:w,text:t,_meta:{ui:{csp:{resourceDomains:a}}}}]}})}(_a,t)}function va(e,t){return async i=>{const r=T(B(),e);if(!r.allowed)return Ut(ht(`Tool ${e} is blocked by org policy.`,[P(r.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=Ze();if(!t)return;if("object"!=typeof e||null===e)return;const i=e.project_id;if("string"==typeof i&&i!==t)throw new Ge(t,i)}(i)}catch(e){if(e instanceof Ge)return Ut(jt(e.expectedProjectId));throw e}{const e=B(),t=i?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return Ut(ht("Tool call rejected: project_id is outside your org's MCP project scope.",[`Allowed projects: ${e.project_scope.length} project${1===e.project_scope.length?"":"s"} configured by your admin`,"Use atoms_list_projects to see which projects you can access in this session"]))}let n,a;try{a=await Se(),n=Ee()}catch{return t(i)}const s=await async function(e,t){const i=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Be,r=new Date,n=new Date(r.getTime()-ze);try{const{count:a,error:s}=await t.from("mcp_rate_limits").select("id",{count:"exact",head:!0}).eq("user_id",e).gte("requested_at",n.toISOString());if(s)throw new Error(s.message);if((a??0)>=i){const{data:i,error:a}=await t.from("mcp_rate_limits").select("requested_at").eq("user_id",e).gte("requested_at",n.toISOString()).order("requested_at",{ascending:!0}).limit(1).maybeSingle();if(a)throw new Error(a.message);const s=(i?new Date(i.requested_at).getTime():r.getTime())+ze-r.getTime();return{allowed:!1,retryAfterSeconds:Math.max(1,Math.ceil(s/1e3))}}t.from("mcp_rate_limits").insert({user_id:e,requested_at:r.toISOString()}).then(({error:e})=>{e&&process.stderr.write(`[rate-limiter] insert failed: ${e.message}\n`)});const o=new Date(r.getTime()-2*ze);return t.from("mcp_rate_limits").delete().eq("user_id",e).lt("requested_at",o.toISOString()).then(()=>{}),{allowed:!0}}catch(e){return process.stderr.write(`[rate-limiter] DB check failed (${e instanceof Error?e.message:String(e)}), falling back to allow.\n`),{allowed:!0}}}(n,a);if(!s.allowed)return Ut(St(s.retryAfterSeconds));if("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN){const e=i?.project_id;if("string"==typeof e)try{const{requireWriteAccess:t}=await Promise.resolve().then(()=>(Ce(),je));await t(a,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(Tt(),mt));return Ut(e("Viewer (lockdown mode: read access requires editor or admin)"))}}}const o=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let d,c="success";try{const e=await t(i),r=e;if(!0===r?.isError){c="error";const e=r?.content;if(e?.[0]?.text)try{d=JSON.parse(e[0].text).message}catch{}}return e}catch(e){throw c="error",d=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:i,status:c,duration_ms:o(),error_msg:d,project_id:i.project_id,session_id:fa,client_name:ha};try{!function(e,t,i){const r=Ve(i.params);e.from("mcp_audit_log").insert({user_id:t,tool_name:i.tool_name,params:r,status:i.status,duration_ms:i.duration_ms,error_msg:i.error_msg??null,project_id:i.project_id??null,session_id:i.session_id??null,client_name:i.client_name??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await Se(),n,t)}catch{}}}}function ja(){return fa}function Sa(){return ga}function xa(){return ha}C(wa,{ATOMS_MCP_SERVER_VERSION:()=>pa,getMcpActor:()=>Sa,getMcpClientName:()=>xa,getMcpSessionId:()=>ja,server:()=>_a});var ka=R({"src/server.ts"(){Ye(),Ke(),Z(),et(),z(),W(),dt(),ct(),Ce(),Tt(),qt(),la=v(import.meta.url),ma=la("../package.json"),pa=ma.version,_a=new b({name:"atoms-mcp-server",version:pa}),ua=(e,t,i)=>{if(G(e))return _a.registerTool(e,t,i)},fa=m(),ha=tt(process.env.ATOMS_CLIENT_NAME),ga=function(){const e=tt(ha);return"cursor"===e?"mcp_cursor":"copilot"===e?"mcp_copilot":"mcp_claude"}(),ua("atoms_status",{title:"ATOMS MCP Health Check",description:'Check the health and authentication status of the ATOMS MCP server.\n\nCall this FIRST if other atoms tools fail or return auth errors.\nThis tool works WITHOUT authentication — it checks whether credentials\nexist and are valid, and tells the user exactly what to do if not.\n\nArgs: None\n\nReturns:\n { status: "authenticated"|"not_authenticated"|"expired", email, message, next_steps }\n\nExamples:\n - "Is ATOMS MCP working?" → atoms_status()\n - "Why are atoms tools failing?" → atoms_status()',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{try{const{readCredentials:e,isTokenValid:t}=await Promise.resolve().then(()=>(ce(),X)),i=await e();if(!i)return{content:[{type:"text",text:JSON.stringify({status:"not_authenticated",message:"No ATOMS credentials found. You need to login first.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp login","3. Complete the login in your browser","4. Restart Claude Desktop (quit and reopen)","5. Try your query again"]},null,2)}]};if(!t(i))try{const{getValidToken:e}=await Promise.resolve().then(()=>(ve(),_e)),{email:t}=await e(),{invalidateClient:i}=await Promise.resolve().then(()=>(Ce(),je));return i(),{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:t,message:"Token was expired but has been refreshed. You're good to go!"},null,2)}]}}catch{return{content:[{type:"text",text:JSON.stringify({status:"expired",email:i.user_email??"unknown",message:"Your session has expired and could not be refreshed.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp logout","3. Run: npx @atoms-tech/atoms-mcp login","4. Complete the login in your browser","5. Restart Claude Desktop (quit and reopen)"]},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:i.user_email??"unknown",message:"ATOMS MCP is connected and authenticated. All tools are ready."},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({status:"error",message:`Health check failed: ${e instanceof Error?e.message:String(e)}`,next_steps:["1. Open a terminal","2. Run: npx @atoms-tech/atoms-mcp login","3. Restart Claude Desktop"]},null,2)}]}}}),ua("atoms_list_projects",{title:"List ATOMS Projects",description:'List all projects the authenticated user has access to.\n\nThis is the ENTRY POINT tool. Call this first to discover project IDs,\nthen use those IDs with all other tools.\n\nArgs: None\n\nReturns:\n { status: "success", data: [{ id, name, description, org_id, created_at }] }\n\nExamples:\n - "What projects do I have?" → atoms_list_projects()\n - "Show my projects" → atoms_list_projects()\n\nWorkflow:\n atoms_list_projects → atoms_list_items(project_id) → atoms_get_item(project_id, item_id)',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(Zt(),Yt));return e()})),ua("atoms_list_items",{title:"List ATOMS Items",description:'List items in an ATOMS project with optional type/domain/level filters.\n\nThis is the primary ENTRY POINT for discovering items. Use it to browse\nproject contents before drilling into specific items with atoms_get_item.\n\nArgs:\n - project_id (string, UUID): The project to list items from\n - type (string, optional): Filter: requirement|test-case|note|table\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - limit (number, optional): Max results, 1-200 (default 50)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { status: "success", data: [{ id, title, type, status, domains, level }], meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me all requirements" → atoms_list_items(project_id, type="requirement")\n - "What test cases exist?" → atoms_list_items(project_id, type="test-case")\n\nErrors:\n - "Project not found" → verify project_id\n - "Access denied" → check org membership',inputSchema:{project_id:h.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:h.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:h.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:h.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:h.number().int().min(0).default(0).describe("Pagination offset (default 0)"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:h.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns items as they were at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(ti(),Xt));return t(e)})),ua("atoms_get_item",{title:"Get ATOMS Item Details",description:'Get full details of a single item including relationships, test history, and ownership.\n\nUse after atoms_list_items or atoms_search to drill into a specific item.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID (e.g., "REQ-001", "TC-050")\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\nExamples:\n - "Show me requirement REQ-001" → atoms_get_item(project_id, "REQ-001")\n - "Get test case details" → atoms_get_item(project_id, "TC-050")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID. Returns the item as it was at that baseline's moment. Mutually exclusive with as_of."),as_of:h.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns the item as it was at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(ni(),ii));return t(e)})),ua("atoms_search",{title:"Search ATOMS Items",description:'Full-text search across items in a project. Searches title, body, and summary.\n\nAlternative entry point to atoms_list_items when you know what you\'re looking for.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Search text (max 1000 chars)\n - type (string, optional): Filter by type\n - asset (string, optional): Filter to items with at least one run on the given asset\n (VIN, module, lot, ...). Case-sensitive exact match.\n - limit (number, optional): Max results, 1-100 (default 25)\n\nReturns:\n Matching items with @basic fields, ranked by relevance.\n\nExamples:\n - "Find braking requirements" → atoms_search(project_id, "braking system")\n - "Search for safety tests" → atoms_search(project_id, "safety", type="test-case")\n - "Tests that ran on this VIN" → atoms_search(project_id, "", asset="WEV...0005")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),query:h.string().min(1).max(1e3).describe("Search text"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),asset:h.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:h.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID. Searches within the project state at that baseline's moment.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(oi(),ai));return t(e)})),ua("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:'Meaning-based search across items using pgvector embeddings (GTE-small, 384d).\n\nUse when atoms_search (exact/substring) misses conceptually related items.\nBest for natural-language concept queries; atoms_search is better for exact phrases or IDs.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Natural-language concept query (max 1000 chars)\n - type (string, optional): Filter by type\n - limit (number, optional): Max results, 1-50 (default 10)\n\nReturns:\n Semantically similar items ranked by cosine similarity.\n\nExamples:\n - "Find braking-related requirements" → atoms_semantic_search(project_id, "braking deceleration stopping distance")\n - "Safety-related test cases" → atoms_semantic_search(project_id, "hazard risk mitigation safety", type="test-case")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),query:h.string().min(1).max(1e3).describe("Natural-language concept query"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:h.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(li(),di));return t(e)})),ba({appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:'Find requirements without linked test cases (coverage gaps).\n\nEssential for compliance reporting in safety-critical industries.\n\nIn MCP App hosts (Claude, ChatGPT), renders a visual coverage heatmap.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to analyze\n - domain (string, optional): Filter by domain\n - level (string, optional): Filter by level\n - baseline_id (string, UUID, optional): coverage at that baseline\'s moment\n - as_of (string ISO 8601, optional): coverage at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n { covered, uncovered, total, coverage_percent, uncovered_items: [...] }\n\nExamples:\n - "What\'s our test coverage?" → atoms_get_coverage(project_id)\n - "Safety coverage gaps?" → atoms_get_coverage(project_id, domain="Safety")\n - "Coverage at PDR submission" → atoms_get_coverage(project_id, baseline_id="...")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),domain:h.string().max(64).optional().describe("Filter by domain tag"),level:h.string().max(32).optional().describe("Filter by level"),baseline_id:h.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:h.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:va("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(_i(),mi));return t(e)})}),ua("atoms_get_history",{title:"Get Item Change History",description:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_<client>) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID"),limit:h.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(hi(),ui));return t(e)})),ba({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Shows parent-child relationships\nand requirement-to-test-case verification links.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive pan/zoom diagram.\nFalls back to Mermaid text for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to visualize\n - root_item_id (string, optional): Start node (default: all roots)\n - depth (number, optional): Max depth (default 3, max 10)\n - include_tests (boolean, optional): Show test case links (default true)\n - baseline_id (string, UUID, optional): render the graph at that baseline's moment\n - as_of (string ISO 8601, optional): render the graph at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n Mermaid graph string.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),root_item_id:h.string().max(20).optional().describe("Root item ID to start from"),depth:h.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:h.boolean().default(!0).describe("Include test case links"),baseline_id:h.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:h.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:va("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(xi(),ji));return t(e)})}),ua("atoms_create_item",{title:"Create ATOMS Item",description:'Create a new requirement, test case, or note in a project.\n\nRequires editor or admin role. Changes are logged with AI actor attribution.\n\nArgs:\n - project_id (string, UUID): Target project\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_ids (string[], optional): Parent item IDs to link\n - fields (object, optional): Project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field first and values must match each field type.\n\nReturns:\n Created item with generated ID (e.g., "REQ-058")\n\nSide effects:\n - Logs to change_history with actor=\'mcp_<client>\'\n - Creates relationships if parent_ids provided',inputSchema:{project_id:h.string().uuid().describe("UUID of the target project"),type:h.enum(["requirement","test-case","note"]).describe("Item type"),title:h.string().min(1).max(500).describe("Item title"),body:h.string().max(5e4).optional().describe("Rich text body"),summary:h.string().max(2e3).optional().describe("Brief summary"),domains:h.array(h.string().max(64)).max(20).optional().describe("Domain tags"),level:h.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:h.array(h.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:h.record(h.string().max(60),h.string().max(1e4)).optional().describe("Project-field values keyed by defined field name"),echo:h.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Xi(),Ki));return t(e)})),ua("atoms_update_item",{title:"Update ATOMS Item",description:'Update an existing item\'s fields. Only provided fields are changed.\n\nRequires editor or admin role. Logs old/new data diff to change history.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to update\n - title, body, summary, domains, level, status: Fields to update (all optional)\n - fields (object, optional): Project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field; merged per key, "" clears a key; non-empty values must match each field type\n - expected_updated_at (string, optional): Pass metadata.updated_at from atoms_get_item to reject stale writes\n\nReturns:\n Updated item.',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).optional().describe("Item ID (single form)"),title:h.string().min(1).max(500).optional().describe("New title"),body:h.string().max(5e4).optional().describe("New body"),summary:h.string().max(2e3).optional().describe("New summary"),domains:h.array(h.string().max(64)).max(20).optional().describe("New domain tags"),level:h.string().max(32).optional().describe("New level"),status:h.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status"),fields:h.record(h.string().max(60),h.string().max(1e4)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),expected_updated_at:it.optional().describe("metadata.updated_at value from atoms_get_item; rejects stale writes"),echo:h.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:h.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:h.array(h.object({item_id:h.string().min(1).max(20),title:h.string().min(1).max(500).optional(),body:h.string().max(5e4).optional(),summary:h.string().max(2e3).optional(),domains:h.array(h.string().max(64)).max(20).optional(),level:h.string().max(32).optional(),status:h.enum(["passed","failed","blocked","not-run"]).optional(),fields:h.record(h.string().max(60),h.string().max(1e4)).optional(),expected_updated_at:it.optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:h.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:h.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(nr(),er));return t(e)})),ua("atoms_delete_item",{title:"Delete ATOMS Item",description:'Soft-delete an item (sets deleted_at, preserves for audit trail).\n\nRequires editor or admin role. The item is never truly removed.\n\nWhen ATOMS_MCP_REQUIRE_CONFIRMATION is set on the server, this tool uses a\ntwo-step flow: the first call returns a preview + confirmation_token; the\nsecond call (with the token) executes. Tokens expire in 60s and are bound\nto (tool, project_id, item_id).\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to delete\n - confirmation_token (string, optional): Token from a prior preview call\n\nReturns:\n Confirmation with deleted item summary, or { status: "confirmation_required",\n preview, confirmation_token } when the confirmation gate is active.',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},va("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(ur(),pr));return t(e)})),ua("atoms_restore_item",{title:"Restore ATOMS Item",description:'Undo a soft-delete — restores an item that was previously deleted with atoms_delete_item.\n\nOnly works on items that have been soft-deleted (still in the database with deleted_at set).\nHas no effect if the item is not deleted. Logs the restoration to change_history.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): ID of the deleted item to restore\n\nReturns:\n Confirmation with the restored item\'s title and type.\n\nExamples:\n - "Restore the deleted requirement REQ-042" → atoms_restore_item(project_id, "REQ-042")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().max(256).describe("ID of the soft-deleted item to restore")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(gr(),fr));return t(e)})),ua("atoms_link_items",{title:"Link ATOMS Items",description:"Add or remove relationships between items.\n\nSupports: parent, child, related, verifies, verified_by.\nUpdates both items' JSONB data and the shadow table.\n\nArgs:\n - project_id (string, UUID): Project containing both items\n - from_id (string): Source item\n - to_id (string): Target item\n - type (string): parent|child|related|verifies|verified_by\n - action (string): add|remove\n - expected_from_updated_at / expected_to_updated_at (string, optional): pass metadata.updated_at values from atoms_get_item to reject stale link commands\n\nReturns:\n Updated relationship state for both items.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),from_id:h.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:h.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:h.enum(["parent","child","related","verifies","verified_by"]).optional().describe("Relationship type"),action:h.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:it.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:it.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:h.boolean().optional().describe("false → lean response"),reason:h.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:h.array(h.object({action:h.enum(["add","remove"]),from_id:h.string().min(1).max(20),to_id:h.string().min(1).max(20),type:h.enum(["parent","child","related","verifies","verified_by"]),expected_from_updated_at:it.optional(),expected_to_updated_at:it.optional()})).optional().describe("Array form: batch relationship ops. Always atomic with DAG cycle detection."),idempotency_key:h.string().max(128).optional().describe("Safe retry key (24h TTL)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(br(),yr));return t(e)})),ba({appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:"Bulk create multiple items in a single tool call. Essential for AI agents\nthat generate 20+ requirements at once.\n\nChecks write access once, generates sequential IDs, batch inserts all items,\nand reports per-item errors without aborting the entire batch.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive results table.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Target project\n - items (array): Up to 100 items to create, each with:\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_id (string, optional): Parent item ID to link\n\nReturns:\n { created: number, items: [{ id, title, type }], errors: [] }\n\nLimits:\n - Maximum 100 items per call\n - If any item fails, others still succeed — errors reported separately\n\nSide effects:\n - Logs to change_history with actor='mcp_<client>' for each created item\n - Creates parent relationships for items with parent_id",inputSchema:{project_id:h.string().uuid().describe("UUID of the target project"),items:h.array(h.object({type:h.enum(["requirement","test-case","note"]).describe("Item type"),title:h.string().min(1).max(500).describe("Item title"),body:h.string().max(5e4).optional().describe("Rich text body"),summary:h.string().max(2e3).optional().describe("Brief summary"),domains:h.array(h.string().max(64)).max(20).optional().describe("Domain tags"),level:h.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:h.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:va("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(kr(),jr));return t(e)})}),ua("atoms_record_test_result",{title:"Record Test Result",description:"Record a pass/fail/blocked result for a test case.\n\nAppends to canonical items.data.runs and projects test_results from that\nhistory. Use atoms_get_item to see all results.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., \"TC-001\")\n - result (string): passed|failed|blocked|not-run\n - note (string, optional): Reason or comment for this result\n - asset (string, optional): Asset identifier this run was executed against\n (VIN, module ID, lot number, serial number, etc). Max 200 chars.\n Auto-trimmed; empty/whitespace is treated as omitted. If the asset\n name does not yet exist in the project, it is auto-registered.\n\nReturns:\n Recorded result with timestamp. When asset is provided, also returns\n asset_id and asset_created.\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts into assets table if asset name is new in this project\n - Logs to change_history with actor='mcp_<client>'",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:h.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:h.string().max(1e3).optional().describe("Reason or comment for this result"),asset:h.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new.")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(Ar(),Ir));return t(e)})),ua("atoms_record_test_results",{title:"Record Test Results (bulk)",description:'Record many runs on one test case in a single atomic call.\n\nOptimized for multi-asset campaigns. Each entry can have its own asset and\nresult. Asset lookup-or-create happens per entry; new asset names are\nauto-registered. Runs are appended to canonical items.data.runs, then\ntest_results is projected from that history. The whole call is one DB\ntransaction; any entry failure rolls back the rest.\n\nUse the singular atoms_record_test_result for one-off runs.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., "TC-001")\n - results (array, 1-100 entries): Each entry has:\n - asset (string, optional): Asset identifier (VIN, module ID, lot)\n - result (string, required): passed|failed|blocked|not-run\n - note (string, optional): Run note\n - date (string, optional): ISO 8601 datetime, default now()\n\nReturns:\n Per-entry outcomes with asset_id, asset_created, run_at, ok flags.\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts new rows into assets for any asset name not already registered\n - Logs a single change_history entry summarizing the batch',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:h.array(h.object({asset:h.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:h.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:h.string().max(500).optional().describe("Run note"),date:h.string().optional().describe("ISO 8601 datetime (default: now())")})).min(1).max(100).describe("1 to 100 result entries on this test case")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_record_test_results",async e=>{const{recordTestResultsBulkHandler:t}=await Promise.resolve().then(()=>(Mr(),Or));return t(e)})),ba({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:'Walk the traceability graph from a starting item.\n\nAnswers questions like "which requirements does TC-003 verify?" or\n"if I change REQ-001, what\'s affected downstream?"\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive graph visualization.\nFalls back to flat list for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Starting item ID\n - direction (string): upstream|downstream|both\n - upstream: follow parent/verifies links (dependencies)\n - downstream: follow child/verified_by links (dependents)\n - both: trace in both directions\n - depth (number, optional): Max traversal depth (default 5, max 10)\n - relationship_types (string[], optional): Filter to specific types (parent, child, related, verifies, verified_by, mitigated_by, mitigates)\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], total_count }\n\nExamples:\n - "What does TC-003 verify?" → atoms_trace(project_id, "TC-003", "upstream")\n - "What\'s affected by REQ-001?" → atoms_trace(project_id, "REQ-001", "downstream")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Starting item ID"),direction:h.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:h.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:h.array(h.enum(["parent","child","related","verifies","verified_by","mitigated_by","mitigates"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:va("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(Nr(),Pr));return t(e)})}),ua("atoms_list_assets",{title:"List Project Assets",description:"List asset identifiers registered in a project.\n\nAssets are free-form per-instance IDs (VINs, module names, lot numbers,\nserial numbers) that test runs are tagged against. They are auto-registered\nthe first time they appear on a run via atoms_record_test_result.\n\nArgs:\n - project_id (string, UUID): Project to list assets for\n - include_archived (boolean, optional): Include archived assets (default false)\n\nReturns:\n { assets: [{ id, name, archived_at, created_at }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),include_archived:h.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(Wr(),Lr));return t(e)})),ua("atoms_list_variables",{title:"List Project Variables",description:"List all parameterized variables defined in a project.\n\nVariables are shared values (e.g., backup_camera_latency = 2s) that can be\nreferenced in requirement bodies as {variable_name}.\n\nArgs:\n - project_id (string, UUID): Project to list variables for\n - baseline_id (string, UUID, optional): list variables as they were at that baseline\n - as_of (string ISO 8601, optional): list variables as they were at that moment\n\nReturns:\n { variables: [{ id, name, value, unit, description }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:h.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(Xr(),Vr));return t(e)})),ua("atoms_get_variable",{title:"Get Project Variable",description:'Get a specific variable by name, including which items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name (e.g., "backup_camera_latency")\n - baseline_id (string, UUID, optional): get the variable as it was at that baseline\n - as_of (string ISO 8601, optional): get the variable as it was at that moment\n\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),variable_name:h.string().min(1).max(64).describe("Variable name"),baseline_id:h.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:h.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(Xr(),Vr));return t(e)})),ua("atoms_update_variable",{title:"Update Project Variable",description:"Update a variable's value, unit, or description.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name\n - value (string, optional): New value\n - unit (string, optional): Unit abbreviation (e.g., 's', 'Hz')\n - description (string, optional): Human-readable description\n\nReturns:\n { variable }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),variable_name:h.string().min(1).max(64).describe("Variable name"),value:h.string().max(500).optional().describe("New value"),unit:h.string().max(32).optional().describe("Unit abbreviation"),description:h.string().max(2e3).optional().describe("Description")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(Xr(),Vr));return t(e)})),ua("atoms_create_variable",{title:"Create Project Variable",description:'Create one or many parameterized variables for a project.\n\nSingle form: provide name + value.\nArray form: provide variables[] for bulk creation (one atomic INSERT).\n\nVariables can then be embedded in requirement bodies as {variable_name}.\n\nArgs (single form):\n - project_id (string, UUID): Project to add the variable to\n - name (string): Variable name, letters, digits, underscores; must start with letter/underscore\n - value (string): Initial value (e.g., "100", "true", "nominal")\n - unit (string, optional): Unit abbreviation (e.g., "Hz", "ms", "m/s²")\n - description (string, optional): Human-readable description\n - echo (bool, optional): false → lean {name} response (default true)\n\nArgs (array form):\n - project_id (string, UUID): Project UUID\n - variables[]: Array of { name, value, unit?, description? }\n - echo (bool, optional): false → lean {name} list (default true)\n - idempotency_key (string, optional): Dedup key\n\nReturns (single): { variable, message }\nReturns (array): { batch_id, created, variables, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).optional().describe("Variable name (single form)"),value:h.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:h.string().max(32).optional().describe("Unit abbreviation"),description:h.string().max(2e3).optional().describe("Description"),echo:h.boolean().optional().describe("false → lean response (default true)"),variables:h.array(h.object({name:h.string().min(1).max(64).describe("Variable name"),value:h.string().min(1).max(500).describe("Initial value"),unit:h.string().max(32).optional().describe("Unit abbreviation"),description:h.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:h.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(Xr(),Vr));return t(e)})),ua("atoms_delete_variable",{title:"Delete Project Variable",description:"Delete a project variable. Refuses by default if any items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - name (string): Variable name to delete\n - force (bool, optional): Delete even if items still reference it (default false)\n\nReturns:\n { deleted, name, referenced_by_items, warning? }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Variable name to delete"),force:h.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},va("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(Xr(),Vr));return t(e)})),ua("atoms_list_domains",{title:"List Project Domains",description:"List all domain tags registered in a project's taxonomy, with item counts.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { domains: [{ name, item_count }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(dn(),en));return t(e)})),ua("atoms_create_domain",{title:"Create Project Domain",description:'Register a new domain tag in the project taxonomy.\n\nOnce created, items can be tagged with this domain via atoms_create_item or atoms_update_item.\n\nArgs:\n - project_id (string, UUID): Project to add the domain to\n - name (string): Domain name (lowercased automatically, e.g., "safety", "can-bus")\n\nReturns:\n { domain: { name }, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(dn(),en));return t(e)})),ua("atoms_list_levels",{title:"List Project Levels",description:"List the project's level taxonomy in order, with each level's L# (positional index) and item count.\n\nArgs:\n - project_id (string, UUID): Project to list levels for\n\nReturns:\n { levels: [{ name, prefix, item_count }], total }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(Ui(),ki));return t(e)})),ua("atoms_create_level",{title:"Create Project Level",description:'Register a new level in the project taxonomy so items can be tagged with it and it shows in the Strata view. Appended to the ordered level list; its L# is the next index. Names are user-defined labels (lowercased automatically); matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID): Project to add the level to\n - name (string): Level name, e.g. "feature", "system", "subsystem"\n\nReturns:\n { level: { name, prefix }, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(Ui(),ki));return t(e)})),ua("atoms_list_fields",{title:"List Project Fields",description:'List the project\'s custom field definitions (project-scoped key-value slots on items, e.g. "Verification Method"), with counts of items carrying a value.\n\nField values are set per item via atoms_create_item / atoms_update_item fields.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { fields: [{ name, type, options, item_count }], total }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(Yi(),Ti));return t(e)})),ua("atoms_create_field",{title:"Create Project Field",description:'Define a project custom field so items can carry a value for it (shown as a Matrix column, e.g. "Verification Method").\n\nThe name keeps its casing; uniqueness is case-insensitive. Type is one of text, long, bool, date, person, select, number, link. Select fields require options. Field definitions never carry visibility rules, permissions, or workflow logic.\n\nArgs:\n - project_id (string, UUID): Project to define the field in\n - name (string): Field name, 1-60 characters (e.g. "Verification Method", "Essential Output?")\n - type (string, optional): Defaults to text\n - options (string[], optional): Required when type=select\n\nReturns:\n { field: { name, type, options }, message }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:h.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:h.array(h.string().min(1).max(120)).optional().describe("Allowed values for select fields")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(Yi(),Ti));return t(e)})),ua("atoms_delete_field",{title:"Delete Project Field",description:"Delete a project field definition. Existing item values are left in item JSON but no longer render as Matrix columns until a matching field is created again.\n\nArgs:\n - project_id (string, UUID): Project containing the field\n - name (string): Field name to delete",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(60).describe("Field name")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},va("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(Yi(),Ti));return t(e)})),ua("atoms_update_domain",{title:"Rename Project Domain",description:"Rename a domain tag. Updates the taxonomy and propagates to all tagged items.\n\nUse dry_run=true first to see how many items will be affected before committing.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Current domain name\n - new_name (string): New domain name\n - dry_run (bool, optional): If true, return impact count without making changes (default false)\n\nReturns (dry_run=false):\n { domain: { name }, renamed_from, items_updated, message }\n\nReturns (dry_run=true):\n { dry_run: true, rename: { from, to }, items_affected, message }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Current domain name"),new_name:h.string().min(1).max(64).describe("New domain name"),dry_run:h.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(dn(),en));return t(e)})),ua("atoms_delete_domain",{title:"Delete Project Domain",description:"Delete a domain tag from the project taxonomy.\n\nRefuses by default if any items are tagged with it. With force=true, deletes the\ndomain and strips the tag from all items.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Domain name to delete\n - force (bool, optional): Strip from items and delete anyway (default false)\n\nReturns:\n { deleted, name, items_updated, message }",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(64).describe("Domain name to delete"),force:h.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:h.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},va("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(dn(),en));return t(e)})),ba({appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:'One-call project health and compliance dashboard.\n\nReturns item counts by type, test execution status, requirement coverage\n(overall and by domain), and recent change activity.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive dashboard with charts.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project to summarize\n\nReturns:\n { project_name, counts, test_status, coverage, coverage_by_domain, recent_changes, last_updated }\n\nExamples:\n - "Give me a compliance snapshot" → atoms_project_summary(project_id)\n - "How\'s our test coverage?" → atoms_project_summary(project_id)',inputSchema:{project_id:h.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:va("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(pn(),cn));return t(e)})}),ba({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:'View and filter items in an ATOMS project with a visual browser.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive filterable list\nwith expandable item details. Falls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to browse\n - type (string, optional): Filter by type (requirement, test-case, note, table)\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - query (string, optional): Full-text search query\n - limit (number, optional): Max results (default 25, max 100)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { items: [...], filters: { domains, levels, types }, meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me the requirements" → atoms_browse(project_id, type="requirement")\n - "Browse safety items" → atoms_browse(project_id, domain="Safety")\n - "Find braking requirements" → atoms_browse(project_id, query="braking")',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),type:h.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:h.string().max(64).optional().describe("Filter by domain tag"),level:h.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:h.string().max(1e3).optional().describe("Full-text search query"),limit:h.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:h.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:va("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(wn(),_n));return t(e)})}),ua("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:'Analyze the blast radius of changing a specific item.\n\nTraverses the relationship graph from the given item and returns every item that\nwould be affected by a change — with their types, depths, and full relationship paths.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to analyze (e.g., "REQ-001")\n - direction (string, optional): "downstream" (default) | "upstream" | "both"\n - downstream: what this item affects (children, verified_by)\n - upstream: what affects this item (parents, verifies)\n - both: full bidirectional traversal\n - depth (integer, optional): Max traversal depth. Omit for full depth (all reachable nodes).\n - include_variable_refs (boolean, optional): Reserved for future variable-aware impact. Default true.\n\nReturns:\n { root: { item_id, title, type }, impacted_items: [{ item_id, title, type, depth, relationship_path }], summary: { total_impacted, by_type, max_depth_reached } }\n\nExamples:\n - "What breaks if I change REQ-001?" → atoms_impact_analysis(project_id, "REQ-001")\n - "What\'s upstream of TC-005?" → atoms_impact_analysis(project_id, "TC-005", direction="upstream")\n - "Show direct dependencies only" → atoms_impact_analysis(project_id, "REQ-001", depth=1)\n\nErrors:\n - "Item not found" → verify item_id exists in the project',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),item_id:h.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:h.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:h.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:h.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(jn(),bn));return t(e)})),ua("atoms_list_baselines",{title:"List ATOMS Baselines",description:"List named baselines (named project snapshots) for a project, newest first.\n\nA baseline is a labeled moment in time. Use atoms_create_baseline to make one,\natoms_diff_baselines to compare two, and atoms_restore_baseline to roll back.",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),limit:h.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:h.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(Vn(),xn));return t(e)})),ua("atoms_create_baseline",{title:"Create ATOMS Baseline",description:"Create a named baseline (snapshot label) at the current moment for a project.\n\nThe baseline records a name + timestamp. It does NOT copy item data; the project\nstate at that moment is reconstructed via temporal queries against item_revisions.\nNames must be unique per project (case-insensitive).",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),name:h.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:h.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(Vn(),xn));return t(e)})),ua("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:"Lock a baseline so it becomes audit-grade immutable. Admin only. One-way: there is no unlock.\n\nAfter locking, the baseline's name, description, and snapshot_at cannot be changed,\nand it cannot be deleted. Use for regulatory submissions and DRBs.",inputSchema:{baseline_id:h.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(Vn(),xn));return t(e)})),ua("atoms_diff_baselines",{title:"Diff ATOMS Baselines",description:"Compute the diff between two baselines: which items were added, removed, or modified.\n\nReturns a summary plus a paginated items array. Pass detail=true to include\nper-item field-level diffs (slower for large projects).",inputSchema:{baseline_a_id:h.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:h.string().uuid().describe("UUID of the second (newer) baseline"),detail:h.boolean().default(!1).describe("Include per-item field-level diffs (default false)"),limit:h.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:h.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(Vn(),xn));return t(e)})),ua("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:"Restore project state to a baseline. Admin only. Preview-by-default.\n\nCall with confirm=false (default) for a dry run that returns items_to_restore count.\nCall with confirm=true to execute: each item present at the baseline gets a new\nrevision matching its historical state, event_source='restore'. Items added AFTER\nthe baseline are NOT deleted. Always recoverable via further history.",inputSchema:{baseline_id:h.string().uuid().describe("UUID of the baseline to restore from"),confirm:h.boolean().default(!1).describe("Set true to execute; false (default) returns a preview")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},va("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(Vn(),xn));return t(e)})),ua("atoms_create_analysis",{title:"Create HARA / DFMEA Analysis",description:'Create a new safety analysis (HARA or DFMEA) with one empty row per source requirement.\n\nRequires editor or admin role. Structure matches analyses created in the ATOMS web app.\n\nArgs:\n - project_id (string, UUID): Target project\n - subtype (string): hara | dfmea\n - title (string, optional): Analysis title (default "New HARA" / "New DFMEA")\n - source_req_ids (string[], optional, max 50): Requirement IDs to seed rows from.\n Each must exist, be a plain requirement, and not itself be an analysis row.\n - revision (string, optional): Revision label (default "1.0")\n\nReturns:\n { id (e.g. "HARA-001" / "DFMEA-001"), subtype, title, revision, rows: [{ id, source_req }],\n link_warnings?: [{ row_id, source_req, message }], warning? }\n rows lists every created row. If any row could not be attached to the analysis, it is\n named in link_warnings and warning explains the repair (atoms_link_items with type\n \'parent\', from_id=<row id>, to_id=<analysis id>); such rows will not appear in\n atoms_get_analysis until relinked.\n\nSide effects:\n - Creates the analysis parent item plus one row item (SG-nnn / FM-nnn) per source requirement\n - Links each row to the parent (dual-written to the relationship shadow table)\n - Logs each created item to change_history with actor=\'mcp_<client>\'',inputSchema:{project_id:h.string().uuid().describe("UUID of the target project"),subtype:h.enum(["hara","dfmea"]).describe("Analysis subtype"),title:h.string().min(1).max(500).optional().describe("Analysis title"),source_req_ids:h.array(h.string().min(1).max(20)).max(50).optional().describe("Requirement IDs to seed rows from (0-50)"),revision:h.string().min(1).max(32).optional().describe("Revision label (default 1.0)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(ya(),Xn));return t(e)})),ua("atoms_fill_row",{title:"Fill Analysis Row Fields",description:"Fill fields on one HARA / DFMEA analysis row (SG-nnn / FM-nnn).\n\nRequires editor or admin role. Written fields are marked as MCP-sourced so the\nweb app shows their provenance. The computed level (ASIL / RPN) is derived and\nnever stored.\n\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. \"SG-001\", \"FM-003\")\n - fields (object): Field name to value map. Allowed keys:\n hara: failure_mode, operating_scenario, severity (S0-S3), exposure (E0-E4),\n controllability (C0-C3), safe_state, ftti, rationale, effect, title\n dfmea: failure_mode, cause, severity (1-10), occurrence (1-10), detection (1-10),\n rationale, effect\n 'effect' writes the row's long text body. dfmea failure_mode also becomes the row title.\n dfmea ratings accept numbers and are stored as strings.\n\nReturns:\n { row_id, subtype, written_fields, computed_level, asil_propagated_to? }\n\nSide effects:\n - Saves the row with stale-write protection and logs to change_history\n - hara only: if the row is linked and its computed ASIL changed, updates each\n linked requirement's asil / asil_source (each update is history-logged)",inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),row_id:h.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),fields:h.record(h.string().max(64),h.union([h.string().max(5e4),h.number()])).describe("Field name to value map (see description for allowed keys per subtype)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(ya(),Xn));return t(e)})),ua("atoms_get_analysis",{title:"Get HARA / DFMEA Analysis",description:'Get a full analysis view: every row with its computed level (ASIL / RPN) and\ngap / critical / stale classifications, plus summary counts.\n\nClassifications match the ATOMS web app exactly (same rules, same thresholds).\n\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "DFMEA-002")\n\nReturns:\n { analysis: { id, title, subtype, scheme, revision },\n rows: [{ id, title, source_req, effect, <subtype fields>, computed_level, is_gap, gap_rule,\n is_critical, is_stale, mitigated_by, link_roles, approved, approved_at, mcp_fields }],\n counts: { rows, gaps, critical, stale, approved, linked } }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),analysis_id:h.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, DFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(ya(),Xn));return t(e)})),ua("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:'Link a HARA / DFMEA row to the technical requirement that mitigates it.\n\nRequires editor or admin role.\n\nArgs:\n - project_id (string, UUID): Project containing both items\n - row_id (string): Analysis row ID (e.g. "SG-001", "FM-003")\n - req_id (string): Target requirement ID (must be a plain requirement, not an analysis row)\n - role (string, dfmea only, REQUIRED for dfmea): prevention | detection | mitigation.\n Must be omitted for hara rows.\n - override (boolean, optional, default false): hara only. When the target already\n carries a different asil, the call fails with a structured error\n (details.code=\'asil_conflict\') unless override=true; the override is\n history-logged like a dialog accept.\n\nReturns:\n { row_id, req_id, type: "mitigated_by", role, asil_written? }\n\nSide effects:\n - Adds the mitigated_by/mitigates relationship (JSONB + shadow table, one transaction)\n - hara only: writes the row\'s computed ASIL onto the target requirement\n (data.asil + data.asil_source) with a history entry recording previous/new values\n - dfmea: never modifies any field on the target requirement',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),row_id:h.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:h.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:h.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows; must be omitted for hara rows."),override:h.boolean().optional().describe("hara only: apply the row's ASIL over a conflicting existing value (history-logged)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(ya(),Xn));return t(e)})),ua("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:'List only the gap rows of a HARA / DFMEA analysis, each naming the rule that matched.\n\nGap rules (identical to the web app):\n hara: unmitigated row with ASIL A-D ("asil <X> unmitigated")\n dfmea: unmitigated row with RPN >= 100 ("rpn >= 100") or severity >= 9 ("severity >= 9")\n\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "DFMEA-002")\n\nReturns:\n { analysis_id, subtype, gaps: [{ id, title, source_req, computed_level, rule }], count }',inputSchema:{project_id:h.string().uuid().describe("UUID of the project"),analysis_id:h.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, DFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(ya(),Xn));return t(e)}))}});Z(),z(),Ce(),V();var Ia=v(import.meta.url)("../package.json"),Ea=process.argv.slice(2)[0];(async function(){switch(Ea){case"login":{const{login:e}=await Promise.resolve().then(()=>(Fe(),Ue));try{const{email:t}=await e();process.stderr.write(`\n [32m✓[0m Authenticated as ${t}\n`),process.stderr.write(" [32m✓[0m Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" [1mNext steps:[0m\n"),process.stderr.write(" [36m$[0m claude mcp add atoms -- npx -y @atoms-tech/atoms-mcp\n"),process.stderr.write("\n Or add to Claude Desktop (Settings → MCP → Edit Config):\n"),process.stderr.write(' [90m{\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp"]\n }\n }\n }[0m\n\n')}catch(e){process.stderr.write(`\n [31m✗[0m ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>(ve(),_e));try{const{email:t,user_id:i}=await e();process.stderr.write(`\n [32m✓[0m Logged in as ${t}\n [90mUser ID: ${i}[0m\n\n`)}catch(e){process.stderr.write("\n [31m✗[0m Not authenticated.\n Run: npx @atoms-tech/atoms-mcp login\n\n"),process.exit(1)}break}case"logout":{const{clearCredentials:e}=await Promise.resolve().then(()=>(ce(),X));await e(),process.stderr.write("Logged out. Credentials removed.\n"),process.stderr.write("Run 'npx @atoms-tech/atoms-mcp login' to authenticate again.\n");break}case"--version":case"-v":process.stderr.write(`@atoms-tech/atoms-mcp v${Ia.version}\n`);break;case"--help":case"-h":process.stderr.write("ATOMS MCP Server — AI agent integration for requirements management\n\nUsage:\n npx @atoms-tech/atoms-mcp Start MCP server (stdio)\n npx @atoms-tech/atoms-mcp login Authenticate with ATOMS.tech\n npx @atoms-tech/atoms-mcp logout Switch account / clear credentials\n npx @atoms-tech/atoms-mcp whoami Show current user\n npx @atoms-tech/atoms-mcp --version Show version\n");break;default:{process.stderr.write("[atoms-mcp] Starting MCP server via stdio...\n");try{const{getValidToken:e}=await Promise.resolve().then(()=>(ve(),_e)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch{process.stderr.write("[atoms-mcp] No credentials found. Starting login flow...\n");try{const{login:e}=await Promise.resolve().then(()=>(Fe(),Ue)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch(e){process.stderr.write(`[atoms-mcp] Login failed: ${e instanceof Error?e.message:String(e)}\n[atoms-mcp] Starting server without auth. Tools will fail until you run: npx @atoms-tech/atoms-mcp login\n`)}}try{const t=await Se(),i=Ee(),r=await async function(e,t){const i=process.env.ATOMS_MCP_ORG_ID?.trim();if(i)return i;const{data:r,error:n}=await e.from("org_members").select("org_id, joined_at").eq("user_id",t).order("joined_at",{ascending:!0}).limit(1).maybeSingle();return n?(process.stderr.write(`[atoms-mcp] Could not resolve session org: ${n.message}\n`),null):r?.org_id??null}(t,i),n=await async function(e,t,i){if(!i)return{role:null,is_member:!1,effective:$};const{data:r,error:n}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:i});return n?(process.stderr.write(`[atoms-mcp] mcp_resolve_policy failed (${n.code}): ${n.message}. Falling back to fail-closed policy.\n`),{role:null,is_member:!1,effective:N}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:$};const t=e,i="string"==typeof t.role?t.role:null,r=!0===t.is_member,n=t.effective??{},a=(e,t)=>Array.isArray(e)?e.filter(e=>"string"==typeof e):t,s=(e,t)=>"boolean"==typeof e?e:t,o=n.project_scope,d=Array.isArray(o)&&o.length>0?o.filter(e=>"string"==typeof e):null;return{role:i,is_member:r,effective:{read_only:s(n.read_only,$.read_only),lockdown:s(n.lockdown,$.lockdown),block_destructive:s(n.block_destructive,$.block_destructive),block_bulk_import:s(n.block_bulk_import,$.block_bulk_import),cross_project_browse:s(n.cross_project_browse,$.cross_project_browse),allowed_toolsets:a(n.allowed_toolsets,$.allowed_toolsets),forbidden_tools:a(n.forbidden_tools,$.forbidden_tools),project_scope:d,require_confirmation_for:a(n.require_confirmation_for,$.require_confirmation_for)}}}(r)}(t,i,r);e={effective:n.effective,role:n.role,org_id:r},L=e.effective,F=e.org_id,n.is_member&&r?process.stderr.write(`[atoms-mcp] Org policy loaded: org=${r.slice(0,8)}… role=${n.role??"?"} read_only=${n.effective.read_only} lockdown=${n.effective.lockdown}\n`):process.stderr.write("[atoms-mcp] No org membership detected — running with permissive default policy.\n")}catch(e){process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). Running with permissive default — RLS still enforces row-level access.\n`)}process.stderr.write(`[atoms-mcp] Tool registry: ${function(){const e=Q(),t=J(),i=[];i.push(e?"read-only":"read+write"),null===t?i.push("all toolsets"):(i.push(`toolsets=${[...t.allowed].sort().join(",")||"(none — only always-on tools)"}`),t.unknown.length>0&&i.push(`unknown=${t.unknown.join(",")}`));const r=process.env.ATOMS_MCP_PROJECT_ID?.trim();return r&&i.push(`project_scope=${r.slice(0,8)}…`),("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN)&&i.push("lockdown=on"),i.join(" | ")}()}\n`);const{server:t}=await Promise.resolve().then(()=>(ka(),wa)),i=new j;await t.connect(i),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}var e})().catch(e=>{process.stderr.write(`[atoms-mcp] Fatal: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)});
|