@atoms-tech/atoms-mcp 0.20.0 → 0.20.2
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.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var e=require("fs/promises"),t=require("os"),r=require("path"),i=require("@supabase/supabase-js"),n=require("http"),a=require("crypto"),s=require("url"),o=require("zod"),d=require("@modelcontextprotocol/ext-apps/server"),c=require("@modelcontextprotocol/sdk/server/mcp.js"),l=require("module"),m=require("@modelcontextprotocol/sdk/server/stdio.js"),p="undefined"!=typeof document?document.currentScript:null;function u(e){return e&&e.__esModule?e:{default:e}}var _,f,h,g,y,w,b,v=u(e),j=u(r),S=u(a),x=Object.defineProperty,k=Object.getOwnPropertyNames,I=(e,t,r)=>function(){if(r)throw r[0];try{return e&&(t=(0,e[k(e)[0]])(e=0)),t}catch(e){throw r=[e],e}},E=(e,t)=>{for(var r in t)x(e,r,{get:t[r],enumerable:!0})};function A(e){return b.get(e)}var O=I({"src/core/tool-catalog.ts"(){_=new Set(["atoms_status","atoms_list_projects"]),f=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_reorder_fields","atoms_create_baseline","atoms_lock_baseline","atoms_restore_baseline","atoms_create_analysis","atoms_fill_row","atoms_link_mitigation"]),h=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_field","atoms_restore_baseline"]),g=new Set(["atoms_bulk_import"]),y={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","atoms_reorder_fields"],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"]},w=Object.keys(y),b=new Map;for(const[e,t]of Object.entries(y))for(const r of t)b.set(r,e)}});function R(e,t){if(_.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&&f.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&h.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&g.has(t))return{allowed:!1,reason:"block_bulk_import"};const r=A(t);return void 0===r||e.allowed_toolsets.includes(r)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function D(e,t){return R(e,t).allowed}function H(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 C,U,z,q,T=I({"src/core/policy.ts"(){O()}}),M=I({"src/core/types.ts"(){C={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:[]},U={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 P(){return z}var $=I({"src/middleware/session-policy.ts"(){M(),z=C,q=null}});function N(){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 r=new Set,i=[];for(const e of t)w.includes(e)?r.add(e):i.push(e);return{allowed:r,unknown:i}}function L(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function F(e){if(L()&&f.has(e))return!1;if(_.has(e))return!0;const t=N();if(null===t)return D(P(),e);const r=A(e);return!!r&&!!t.allowed.has(r)&&D(P(),e)}var W,V,B=I({"src/middleware/tool-registry.ts"(){O(),T(),$()}}),J={};async function Q(){try{const t=await e.readFile(V,"utf-8"),r=JSON.parse(t);return r.access_token&&r.refresh_token?r:null}catch{return null}}async function G(t){await e.mkdir(W,{recursive:!0,mode:448}),await e.writeFile(V,JSON.stringify(t,null,2),{mode:384})}async function Y(){const e=await Q();return!!e&&e.expires_at>Date.now()+6e4}function K(e){return e.expires_at>Date.now()+6e4}async function Z(){try{await e.unlink(V)}catch{}}function X(){return V}E(J,{clearCredentials:()=>Z,getCredentialsPath:()=>X,hasValidCredentials:()=>Y,isTokenValid:()=>K,readCredentials:()=>Q,writeCredentials:()=>G});var ee,te,re,ie=I({"src/auth/token-store.ts"(){W=r.join(t.homedir(),".atoms"),V=r.join(W,"credentials.json")}}),ne={};function ae(e){return e.trim().replace(/\/+$/,"")}E(ne,{ATOMS_APP_URL:()=>re,ATOMS_SUPABASE_ANON_KEY:()=>te,ATOMS_SUPABASE_URL:()=>ee,resolveUrl:()=>ae});var se=I({"src/config.ts"(){ee=ae(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),te=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",re=process.env.ATOMS_APP_URL??"https://atoms.tech"}}),oe={};async function de(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=ce(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await Q();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=ce(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 r=i.createClient(ee,te),{data:n,error:a}=await r.auth.refreshSession({refresh_token:t.refresh_token});if(a||!n.session)throw new Error(`Token refresh failed: ${a?.message??"No session returned"}. Re-run 'npx @atoms-tech/atoms-mcp login'.`);const s=n.session;return await G({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:Date.now()+1e3*(s.expires_in??3600),user_email:s.user?.email}),{access_token:s.access_token,refresh_token:s.refresh_token,user_id:s.user?.id??"",email:s.user?.email??""}}function ce(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),i=JSON.parse(Buffer.from(r,"base64").toString("utf-8"));if(!i.sub)throw new Error("JWT missing 'sub' claim");return i}E(oe,{getValidToken:()=>de});var le,me,pe,ue,_e,fe=I({"src/auth/refresh.ts"(){ie(),se()}}),he={};async function ge(){if(le)try{const e=await Q();e&&e.expires_at>_e&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),ye())}catch{}if(le&&ue>Date.now()+6e4)return le;le&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:r}=await de(),n=e.split(".");if(3===n.length)try{const e=JSON.parse(Buffer.from(n[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());ue=1e3*(e.exp??0)}catch{ue=Date.now()+36e5}try{const e=await Q();_e=e?.expires_at??0}catch{_e=0}const a=i.createClient(ee,te,{global:{headers:{Authorization:`Bearer ${e}`}}});return me=t,pe=r,le=a}function ye(){le=null,me=null,pe=null,ue=0,_e=0}function we(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const r=e;t="string"==typeof r.message?r.message:"string"==typeof r.code?r.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 be(e){try{return await e()}catch(t){if(!we(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),ye(),await e()}}function ve(){if(!me)throw new Error("Not authenticated. Call getClient() first.");return me}function je(){return pe??""}async function Se(e,t){const r=ve(),{data:i,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n||!i)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",r).eq("org_id",i.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 xe(e,t){const r=ve(),{data:i,error:n}=await e.from("projects").select("org_id, created_by").eq("id",t).maybeSingle();if(n||!i)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",r).eq("org_id",i.org_id).maybeSingle();if(s||!a)throw new Error("Not a member of this project's organization");if("admin"===a.role)return"admin";if(i.created_by===r)return"owner";throw new Error("PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED")}E(he,{getClient:()=>ge,getUserEmail:()=>je,getUserId:()=>ve,invalidateClient:()=>ye,isJwtExpiredError:()=>we,requireProjectFieldDefinitionAccess:()=>xe,requireWriteAccess:()=>Se,withJwtRetry:()=>be});var ke,Ie,Ee=I({"src/db/client.ts"(){fe(),ie(),se(),le=null,me=null,pe=null,ue=0,_e=0}}),Ae={};async function Oe(){const e=a.randomBytes(32).toString("base64url"),t=a.createHash("sha256").update(e).digest("base64url"),r=`http://localhost:${ke}${Ie}`,i=new s.URL(`${re}/auth/mcp-consent`);return i.searchParams.set("redirect_uri",r),i.searchParams.set("code_challenge",t),i.searchParams.set("code_challenge_method","S256"),new Promise((t,r)=>{let a;function o(){clearTimeout(a)}const d=n.createServer(async(i,n)=>{const a=new s.URL(i.url??"/",`http://localhost:${ke}`);if(a.pathname!==Ie)return n.writeHead(404),void n.end("Not found");try{if("access_denied"===a.searchParams.get("error"))return n.writeHead(200,{"Content-Type":"text/html"}),n.end(De("Authorization was cancelled.")),o(),d.close(),void r(new Error("Authorization cancelled by user."));const i=a.searchParams.get("code");if(i){const a=await fetch(`${ee}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:te},body:JSON.stringify({auth_code:i,code_verifier:e})}),s=await a.json();if(!a.ok||!s.access_token){const e=s.error_description??s.msg??"Unknown error";return n.writeHead(200,{"Content-Type":"text/html"}),n.end(De(`Code exchange failed: ${e}`)),o(),d.close(),void r(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(s.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(ee,te,{global:{headers:{Authorization:`Bearer ${s.access_token}`}}}),{data:p,error:u}=await m.from("org_members").select("org_id").limit(1);return u||!p||0===p.length?(n.writeHead(200,{"Content-Type":"text/html"}),n.end(De('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.')),o(),d.close(),void r(new Error("No ATOMS account found. Sign up at atoms.tech first."))):(await G({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:Date.now()+1e3*(s.expires_in??3600),user_email:c}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(Re(c)),o(),d.close(),void t({email:c}))}const s=a.searchParams.get("access_token"),c=a.searchParams.get("refresh_token"),l=parseInt(a.searchParams.get("expires_in")??"3600",10);s&&c?(await G({access_token:s,refresh_token:c,expires_at:Date.now()+1e3*l}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(Re("authenticated")),o(),d.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"),o(),d.close(),r(e)}});d.on("request",async(e,i)=>{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 G({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!0})),o(),d.close(),t({email:e.user_email??"authenticated"})}catch(e){i.writeHead(500),i.end("Failed to store credentials"),o(),d.close(),r(e)}})}}),d.listen(ke,"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${i.toString()}\n\n`);try{const{default:e}=await import("open");await e(i.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),a=setTimeout(()=>{d.close(),r(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function Re(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 De(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>`}E(Ae,{login:()=>Oe});var He,Ce,Ue,ze,qe=I({"src/auth/login.ts"(){ie(),se(),ke=19275,Ie="/callback"}});function Te(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Ue)if(t.test(e.trim()))return"[redacted]";return e.length>ze?e.slice(0,ze)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Te(e,t+1));if(null!==e&&"object"==typeof e){const r={};for(const[i,n]of Object.entries(e)){const e=i.toLowerCase();He.has(e)?r[i]="[redacted]":Ce.has(e)?r[i]="string"==typeof n?"[content]":Te(n,t+1):r[i]=Te(n,t+1)}return r}return e}function Me(e){return Te(e)}var Pe,$e,Ne,Le,Fe,We=I({"src/middleware/audit.ts"(){He=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),Ce=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Ue=[/^[^\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_-]+$/],ze=200}}),Ve=I({"src/middleware/rate-limiter.ts"(){Pe=60,$e=6e4}});function Be(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?Ne.test(e)?e:(Le||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),Le=!0),null):null}var Je,Qe=I({"src/middleware/project-scope.ts"(){Ne=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Le=!1,Fe=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 Ge(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")?Je:t:Je}var Ye,Ke,Ze,Xe,et,tt,rt=I({"src/core/client-identity.ts"(){Je="claude_desktop"}}),it=I({"src/core/timestamps.ts"(){Ye=o.z.string().datetime({offset:!0})}}),nt=I({"src/core/errors.ts"(){}}),at={};function st(e,t=Ze){if("string"!=typeof e)return"";const r=e.replace(et,"").replace(tt,"");return r.length<=t?r:r.slice(0,t)+"..."}function ot(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function dt(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function ct(e,t,r){return{total_count:e,limit:t,offset:r,has_more:r+t<e}}function lt(e,t){return{status:"error",message:e,next_steps:t}}function mt(e,t){return lt(`${e} '${st(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function pt(e){return lt(`${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 ut(e){return lt(`Validation error: ${st(e,Xe)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function _t(){return lt("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 ft(){return lt("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 ht(e){return lt("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 gt(e){return lt("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 yt(e){return lt(`Parse error: ${st(e,Xe)}`,["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 wt(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function bt(){return lt("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 vt(){return lt("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 jt(){return lt("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 St(){return lt("Item save rejected because this item is in Trash.",["Restore the item before changing it","Do not retry the same save while the item remains in Trash"])}function xt(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e),r=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return/not authenticated/i.test(t)?_t():function(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const r=e;t="string"==typeof r.message?r.message:"string"==typeof r.code?r.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)?ft():/rate.?limit|too many requests|429/i.test(t)?gt():wt(t)?bt():/soft_deleted_item_write/i.test(t)?St():/save_temporarily_unavailable/i.test(t)?jt():"55P03"===r||"57014"===r||/item_save_busy|statement timeout|request timeout|upstream request timeout/i.test(t)?vt():"42501"===r&&/org_project_field_admin_required/i.test(t)?pt("Org admin"):"42501"===r&&/project_field/i.test(t)?pt("Project admin or owner"):"P0002"===r&&/project_field/i.test(t)?lt("Project field not found.",["Refresh the field list and retry with an existing field name"]):["22023","23505","23514"].includes(r)&&/project_field/i.test(t)?ut(t.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?yt(t):It(t)}function kt(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??""),r=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return["40001","PT409","55P03","57014"].includes(r)||/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 It(e){return/row.level security|permission denied for/i.test(e)?lt("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"]):lt(`Database error: ${st(e,Xe)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function Et(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function At(e){const t=JSON.stringify(e,null,2);if(t.length>Ke&&"success"===e.status&&Array.isArray(e.data)){const t=Math.max(1,Math.floor(e.data.length/2)),r={...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(r,null,2)}],structuredContent:r}}return{content:[{type:"text",text:t}],structuredContent:e}}function Ot(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}E(at,{CHARACTER_LIMIT:()=>Ke,accessDeniedError:()=>pt,authError:()=>_t,classifyError:()=>xt,dbError:()=>It,errorResponse:()=>lt,formatErrorResult:()=>Ot,formatToolResult:()=>At,isItemSaveStopError:()=>kt,isStaleWriteErrorMessage:()=>wt,jwtExpiredError:()=>ft,notFoundError:()=>mt,paginationMeta:()=>ct,parseError:()=>yt,rateLimitError:()=>gt,sanitizeForEcho:()=>st,sanitizeTagOrLevel:()=>ot,saveBusyError:()=>vt,saveUnavailableError:()=>jt,scopeError:()=>ht,softDeletedItemError:()=>St,staleWriteError:()=>bt,success:()=>dt,validationError:()=>ut,wrapUserContent:()=>Et});var Rt,Dt=I({"src/tools/_base.ts"(){nt(),Ke=25e3,Ze=50,Xe=200,et=new RegExp("[\\u0000-\\u001F\\u007F]","g"),tt=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g")}});var Ht=I({"src/apps/register.ts"(){Rt={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function Ct(e){return function(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(`*${t=e,t.replace(/[\\%_*]/g,e=>`\\${e}`)}*`);var t}var Ut=I({"src/core/postgrest.ts"(){}});async function zt(e,t,r){let i=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0});r.type&&(i=i.eq("type",r.type)),r.domain&&(i=i.filter("data->tags->domains","cs",JSON.stringify([r.domain]))),r.level&&(i=i.filter("data->tags->>level","eq",r.level)),i=i.range(r.offset,r.offset+r.limit-1);const{data:n,error:a,count:s}=await i;if(a)throw new Error(a.message);return{items:n??[],totalCount:s??0}}async function qt(e,t,r){const{data:i,error:n}=await e.from("items").select("*").eq("id",r).eq("project_id",t).is("deleted_at",null).maybeSingle();if(n)throw new Error(n.message);return i}async function Tt(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:r,error:i}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",t.baseline_id).maybeSingle();if(i)throw new Error(`resolveSnapshotAt: ${i.message}`);if(!r||null!==r.deleted_at)throw new Error(`Baseline not found: ${t.baseline_id}`);if(r.project_id!==t.project_id)throw new Error("Baseline does not belong to this project");return r.snapshot_at}return null}async function Mt(e,t){const{data:r,error:i}=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, release_version, release_status").eq("id",t).maybeSingle();if(i)throw new Error(`getBaselineById: ${i.message}`);return r&&null===r.deleted_at?r:null}function Pt(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 $t(e,t,r){const{data:i,error:n}=await e.rpc("project_state_at",{p_project_id:t,p_snapshot_at:r});if(n)throw new Error(`projectStateAt: ${n.message}`);return i??[]}async function Nt(e,t,r,i){const n=r.trim();if(!n)return{items:[],totalCount:0};let a=null;if(i.asset&&i.asset.trim()){const{data:r,error:n}=await e.from("test_results").select("item_id").eq("project_id",t).eq("asset",i.asset.trim());if(n)throw new Error(n.message);const s=new Set;for(const e of r??[])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.${Ct(n)},data->>body.ilike.${Ct(n)},data->>summary.ilike.${Ct(n)}`).limit(i.limit);i.type&&(s=s.eq("type",i.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 Lt(e,t){const r=new Set(e.map(e=>e.id)),i=new Set,n=[],a=(e,t,a)=>{if(e===t)return;if(!r.has(e)||!r.has(t))return;const s=`${e}|${t}|${a}`;i.has(s)||(i.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??{},r=t=>Array.isArray(e[t])?e[t].filter(e=>"string"==typeof e):[];for(const e of r("parents"))a(t.id,e,"parent");for(const e of r("children"))a(t.id,e,"child");for(const e of r("related"))a(t.id,e,"related");for(const e of r("verifies"))a(t.id,e,"verifies");for(const e of r("verified_by"))a(t.id,e,"verified_by");for(const e of r("mitigated_by"))a(t.id,e,"mitigated_by");for(const e of r("mitigates"))a(t.id,e,"mitigates")}return n}async function Ft(e,t,r){const i="requirement"===r?"REQ":"test-case"===r?"TC":"note"===r?"NOTE":"TABLE",{data:n,error:a}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:i});if(a)throw new Error(`ID generation failed: ${a.message}`);return n}var Wt=I({"src/db/queries.ts"(){Ut()}}),Vt={};async function Bt(){try{const e=await be(async()=>{const e=await ge();return await async function(e){const{data:t,error:r}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(r)throw new Error(r.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=Be(),r=q,i=P().project_scope,n=i?new Set(i):null;return At(dt(e.filter(e=>!r||e.org_id===r).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 Ot(xt(e))}}E(Vt,{listProjectsHandler:()=>Bt});var Jt=I({"src/tools/list-projects.ts"(){Ee(),Wt(),Qe(),$(),Dt()}}),Qt={};async function Gt(e){try{const t=await ge();let r,i,n=null;try{n=await Tt(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ot(It(e.message))}if(n){const a=(await $t(t,e.project_id,n)).filter(t=>{if(e.type&&t.type!==e.type)return!1;const r=t.data??{};if(e.domain){const t=r?.tags?.domains??[];if(!Array.isArray(t)||!t.includes(e.domain))return!1}return!e.level||r?.tags?.level===e.level});i=a.length,r=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 zt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});r=n.items,i=n.totalCount}return At(dt(r.map(e=>({id:e.id,title:Et(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ct(i,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(Qt,{listItemsHandler:()=>Gt});var Yt=I({"src/tools/list-items.ts"(){Ee(),Wt(),Dt()}}),Kt={};async function Zt(e){try{const r=await ge();let i=null;try{i=await Tt(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ot(lt(e.message,["Pass baseline_id OR as_of, not both"]))}const n=i?await async function(e,t,r,i){const{data:n,error:a}=await e.rpc("item_state_at",{p_item_id:r,p_project_id:t,p_snapshot_at:i});if(a)throw new Error(`itemStateAt: ${a.message}`);return(n??[])[0]??null}(r,e.project_id,e.item_id,i).then(e=>e?Pt(e):null):await qt(r,e.project_id,e.item_id);if(!n)return Ot(mt("Item",e.item_id));const a={parents:[],children:[],related:[],verified_by:[],verifies:[],mitigated_by:[],mitigates:[]};if(i){const e=n.data?.relationships??{};for(const t of Object.keys(a)){const r=e[t];Array.isArray(r)&&(a[t]=r.slice())}}else{const t=await async function(e,t,r){const{data:i,error:n}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${r},to_id.eq.${r}`);if(n)throw new Error(n.message);return i??[]}(r,e.project_id,e.item_id),i={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 r=a[e];r.includes(t)||r.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:i}=await r.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",m);if(i)throw new Error(i.message);l=new Set((t??[]).map(e=>e.id)),l.add(e.item_id)}const p=e=>l.has(e);for(const r of t)if(r.from_id===e.item_id){if(!p(r.to_id))continue;o(i[r.type]??r.type,r.to_id)}else{if(!p(r.from_id))continue;o(s[r.type]??r.type,r.from_id)}for(const t of Object.keys(a)){const r=c[t];if(Array.isArray(r))for(const i of r)"string"==typeof i&&i!==e.item_id&&p(i)&&o(t,i)}}let s=[];if("test-case"===n.type)if(i)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:i}=await r.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);!i&&t&&(s=t)}return At(dt({id:n.id,type:n.type,title:Et(n.title),summary:Et(n.data?.summary),body:Et(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,Et(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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}var t}E(Kt,{getItemHandler:()=>Zt});var Xt=I({"src/tools/get-item.ts"(){Ee(),Wt(),Dt()}}),er={};async function tr(e){try{const t=await ge();let r,i,n=null;try{n=await Tt(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return Ot(It(e.message))}if(n){const a=await $t(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 r=t.data??{};return[t.title,r?.body,r?.summary].filter(e=>"string"==typeof e).map(e=>e.toLowerCase()).some(e=>e.includes(s))});i=o.length,r=o.slice(0,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,e.query,{type:e.type,limit:e.limit,asset:e.asset});r=n.items,i=n.totalCount}return At(dt(r.map(e=>({id:e.id,title:Et(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ct(i,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(er,{searchHandler:()=>tr});var rr=I({"src/tools/search.ts"(){Ee(),Wt(),Dt()}}),ir={};async function nr(e){try{const t=await ge(),{access_token:r}=await de(),{items:i,totalCount:n}=await async function(e,t,r,i){const{ATOMS_SUPABASE_URL:n,ATOMS_SUPABASE_ANON_KEY:a}=await Promise.resolve().then(()=>(se(),ne)),s=await fetch(`${n}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.accessToken}`,apikey:a},body:JSON.stringify({input:r})});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:i.limit,p_type:i.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:r});return At(dt(i.map(e=>({id:e.id,title:Et(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ct(n,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(ir,{semanticSearchHandler:()=>nr});var ar=I({"src/tools/semantic-search.ts"(){Ee(),fe(),Wt(),Dt()}}),sr={};async function or(e){try{if(e.baseline_id&&e.as_of)return Ot(ut("baseline_id and as_of are mutually exclusive"));const t=await ge();let r;if(e.baseline_id){const i=await Mt(t,e.baseline_id);if(!i)return Ot(ut(`Baseline ${e.baseline_id} not found`));if(i.project_id!==e.project_id)return Ot(ut("Baseline does not belong to this project"));r=i.snapshot_at}else e.as_of&&(r=e.as_of);const{covered:i,uncovered:n,total:a}=await async function(e,t,r){let i,n,a;if(r.snapshotAt){const s=(await $t(e,t,r.snapshotAt)).map(Pt);i=s.filter(e=>"requirement"===e.type),n=s.map(e=>({id:e.id,data:e.data})),a=[]}else{const{data:r,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);i=r??[];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=i.filter(e=>!(r.domain&&!(e.data?.tags?.domains??[]).includes(r.domain)||r.level&&e.data?.tags?.level!==r.level)),o=Lt(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:r}),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 At(dt({covered:i.length,uncovered:n.length,total:a,coverage_percent:a>0?Math.round(i.length/a*1e3)/10:100,uncovered_items:s}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(sr,{getCoverageHandler:()=>or});var dr=I({"src/tools/get-coverage.ts"(){Ee(),Wt(),Dt()}}),cr={};async function lr(e){try{const t=await ge(),r=await async function(e,t,r,i){const{data:n,error:a}=await e.from("change_history").select("*").eq("item_id",r).eq("project_id",t).order("changed_at",{ascending:!1}).limit(i);if(a)throw new Error(a.message);return n??[]}(t,e.project_id,e.item_id,e.limit),i=r.map(e=>{const t=[],r=e.old_data,i=e.new_data;if(r&&i){const e=new Set([...Object.keys(r),...Object.keys(i)]);for(const n of e)JSON.stringify(r[n])!==JSON.stringify(i[n])&&t.push(n)}else i?t.push("(created)"):r&&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 At(dt(i,ct(i.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(cr,{getHistoryHandler:()=>lr});var mr=I({"src/tools/get-history.ts"(){Ee(),Wt(),Dt()}});function pr(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function ur(e){const t=fr(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:`["${t}"]`}function _r(e){const t=pr(e.from_id),r=pr(e.to_id);return"child"===e.type?`${t} --\x3e ${r}`:"verified_by"===e.type?`${t} -.-> ${r}`:"related"===e.type?`${t} -.- ${r}`:null}function fr(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var hr=I({"src/core/mermaid.ts"(){}}),gr={};async function yr(e){try{if(e.baseline_id&&e.as_of)return Ot(ut("baseline_id and as_of are mutually exclusive"));const t=await ge();let r,i,n;if(e.baseline_id){const i=await Mt(t,e.baseline_id);if(!i)return Ot(ut(`Baseline ${e.baseline_id} not found`));if(i.project_id!==e.project_id)return Ot(ut("Baseline does not belong to this project"));r=i.snapshot_at}else e.as_of&&(r=e.as_of);if(r){i=(await $t(t,e.project_id,r)).map(Pt).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),n=Lt(i,[])}else{const{data:r,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);i=r??[];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=Lt(i,s??[])}return At(dt(function(e){const t=e.items,r=e.relationships??[],i=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${fr(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,r,i){if(r)return[r];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=>i||"test-case"!==e.type).map(e=>e.id)}(t,r,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>i)continue;const m=n.get(t);if(m&&(e.includeTests||"test-case"!==m.type)){o.add(t),c.push(` ${pr(t)}${ur(m)}`);for(const c of r){if(c.from_id!==t)continue;const r=n.get(c.to_id);if(!r)continue;if(!e.includeTests&&"test-case"===r.type)continue;if(a+1>i)continue;const m=_r(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:i,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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(gr,{exportMermaidHandler:()=>yr});var wr=I({"src/tools/export-mermaid.ts"(){Ee(),Wt(),Dt(),hr()}}),br={};function vr(e){const t=ot(e??"");return"sub-system"===t?"subsystem":t}async function jr(e,t){const{data:r}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:r?.domains??[],levels:r?.levels??[]}}async function Sr(e,t,r,i){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:r,levels:i},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function xr(e,t,r){const i=ot(r??""),n=vr(i);if(!i)return!1;try{const{domains:r,levels:a}=await jr(e,t);return!a.some(e=>vr(e)===n)&&(await Sr(e,t,r,[...a,i]),!0)}catch{return!1}}async function kr(e){try{const t=await ge(),{levels:r}=await jr(t,e.project_id),{data:i}=await t.from("items").select("data").eq("project_id",e.project_id).is("deleted_at",null),n={};for(const e of i??[]){const t=e.data?.tags,r=vr(t?.level);r&&(n[r]=(n[r]??0)+1)}return At(dt({levels:r.map((e,t)=>({name:e,prefix:`L${t}`,item_count:n[vr(e)]??0})),total:r.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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function Ir(e){try{const t=await ge();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const{domains:r,levels:i}=await jr(t,e.project_id),n=ot(e.name),a=vr(n);if(!n)return Ot(ut("Level name cannot be empty."));if(i.some(e=>vr(e)===a))return Ot(ut(`Level "${n}" already exists in this project.`));const s=i.length;return await Sr(t,e.project_id,r,[...i,n]),At(dt({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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(br,{createLevelHandler:()=>Ir,ensureLevelRegistered:()=>xr,listLevelsHandler:()=>kr});var Er,Ar,Or=I({"src/tools/levels.ts"(){Ee(),Dt()}}),Rr=I({"src/core/project-field-counts.ts"(){}}),Dr={};async function Hr(e,t){const{data:r,error:i}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(i)throw i;return Cr(r?.fields)}function Cr(e){if(!Array.isArray(e))return[];const t=[],r=new Set;for(const i of e){if(!i||"object"!=typeof i)continue;const e=i,n="string"==typeof e.name?e.name.trim():"";if(!n)continue;const a=n.toLowerCase();if(r.has(a))continue;r.add(a);const s=void 0===e.type?"text":"string"==typeof e.type&&Ar.has(e.type)?e.type:"text",o=Array.isArray(e.options)?Lr(e.options):[];t.push({name:n,type:s,..."select"===s?{options:o}:{}})}return t}function Ur(e,t){const r=e.name.trim();if(!r)return"Field name cannot be empty.";if(r.length>60)return"Field name must be 60 characters or fewer.";if(!Ar.has(e.type))return"Field type is not supported.";const i=t.find(e=>e.name.toLowerCase()===r.toLowerCase());if(i)return`Field "${i.name}" already exists.`;if("select"===e.type){const t=Lr(e.options??[]);if(0===t.length)return"Select fields need at least one option.";if(t.length>100)return"Select fields support at most 100 options.";if(t.some(e=>e.length>120))return"Select options must be 120 characters or fewer."}return null}function zr(e,t){const r=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!r.has(e.toLowerCase()))}function qr(e,t){const r=new Map(e.map(e=>[e.name.toLowerCase(),e.name])),i={};for(const[e,n]of Object.entries(t))i[r.get(e.toLowerCase())??e]=n;return i}function Tr(e,t,r=new Set){const i=zr(e,t);if(i.length>0)return{error:`Unknown field${i.length>1?"s":""}: ${i.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,i]of Object.entries(t)){const t=a.get(e.toLowerCase());if(!t)continue;const s=Mr(t,i,r);if(s.error)return{error:s.error};s.value&&(n[t.name]=s.value)}return{fields:n}}function Mr(e,t,r){const i=t.trim();if(!i)return{value:""};if(i.length>1e4)return{error:`${e.name} is too long.`};switch(e.type){case"text":case"long":return{value:i};case"bool":{const t=i.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}(i)?{value:i}:{error:`${e.name} must be an ISO date.`};case"person":return Nr(i)&&r.has(i)?{value:i}:{error:`${e.name} must be an active project member ID.`};case"select":return(e.options??[]).includes(i)?{value:i}:{error:`${e.name} must be one of: ${(e.options??[]).join(", ")}.`};case"number":return Number.isFinite(Number(i))?{value:i}:{error:`${e.name} must be numeric.`};case"link":{const t=function(e){if(!e)return{label:"",url:""};try{const t=JSON.parse(e);if(t&&"object"==typeof t&&"string"==typeof t.url){const e=t.label;return{label:"string"==typeof e?e:"",url:t.url}}}catch{}return{label:"",url:e}}(i);return function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(t.url)?{value:Pr(t.label,t.url)}:{error:`${e.name} must be an http(s) URL.`}}}}function Pr(e,t){const r=t.trim();return r?JSON.stringify({label:e.trim(),url:r}):""}async function $r(e,t,r,i){const n=new Map(r.map(e=>[e.name.toLowerCase(),e])),a=new Map;for(const[e,t]of Object.entries(i)){const r=n.get(e.toLowerCase());"person"===r?.type&&t.trim()&&a.set(t.trim(),r)}const s=new Set;for(const[r,i]of a){if(!Nr(r))return{error:`${i.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:r,p_actor_user_id:ve()});if(a)return{error:a.message};!0===n&&s.add(r)}return Tr(r,i,s)}function Nr(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 Lr(e){const t=[],r=new Set;for(const i of e){if("string"!=typeof i)continue;const e=i.trim();if(!e)continue;const n=e.toLowerCase();r.has(n)||(r.add(n),t.push(e))}return t}async function Fr(e){try{const t=await ge(),r=await Hr(t,e.project_id),i=await async function(e,t,r,i=500){const n=Object.fromEntries(r.map(e=>[e.name,0])),a=new Map(r.map(e=>[e.name.toLowerCase(),e.name]));let s=0;for(;;){const{data:r,error:o}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null).order("id",{ascending:!0}).range(s,s+i-1);if(o)throw o;const d=r??[];for(const e of d){const t=e.data?.fields;if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,r]of Object.entries(t)){const t=a.get(e.toLowerCase());t&&"string"==typeof r&&r.length>0&&(n[t]+=1)}}if(d.length<i)return n;s+=d.length}}(t,e.project_id,r);return At(dt({fields:r.map(e=>({name:e.name,type:e.type,options:e.options??[],item_count:i[e.name]??0})),total:r.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(xt(e))}}async function Wr(e){try{const t=await ge();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ot(pt("Project admin or owner"));throw e}const{data:r}=await t.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),i=Cr(r?.fields),n={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:Lr(e.options??[])}:{}},a=Ur(n,i);if(a)return Ot(ut(a));const{data:s,error:o}="organization"===e.scope?await t.rpc("create_org_project_field_definition",{p_project_id:e.project_id,p_field:n,p_actor_user_id:ve()}):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:ve()});if(o)throw o;return At(dt({field:s?.field??n,..."organization"===e.scope?{created_projects:s?.created_projects??[],skipped_projects:s?.skipped_projects??[]}:{},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")?Ot(_t()):Ot(xt(e))}}async function Vr(e){try{const t=await ge();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ot(pt("Project admin or owner"));throw e}const r=e.name.trim(),{data:i,error:n}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"delete",p_field:null,p_field_name:r,p_actor_user_id:ve()});if(n)throw n;return At(dt({deleted:i?.deleted??r}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(xt(e))}}async function Br(e){try{const t=await ge();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ot(pt("Project admin or owner"));throw e}const r=Array.isArray(e.names)?e.names.map(e=>String(e??"").trim()).filter(e=>e.length>0):[];if(0===r.length)return Ot(ut("names must be a non-empty array of existing field names, in the order you want them"));const i=await Hr(t,e.project_id),n=i.map(e=>e.name.toLowerCase()).sort(),a=r.map(e=>e.toLowerCase()).sort();if(n.length!==a.length||n.some((e,t)=>e!==a[t]))return Ot(ut(`names must list every existing field exactly once. Defined: ${i.length>0?i.map(e=>e.name).join(", "):"(none)"}`));const{data:s,error:o}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"reorder",p_field:r,p_field_name:null,p_actor_user_id:ve()});if(o)throw o;return At(dt({fields:Cr(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(xt(e))}}E(Dr,{PROJECT_FIELD_TYPES:()=>Er,canonicalizeFieldKeys:()=>qr,createFieldHandler:()=>Wr,deleteFieldHandler:()=>Vr,findUnknownFieldNames:()=>zr,getProjectFields:()=>Hr,listFieldsHandler:()=>Fr,normalizeProjectFields:()=>Cr,reorderFieldsHandler:()=>Br,validateAndCanonicalizeFieldValues:()=>Tr,validateProjectFieldDefinition:()=>Ur,validateProjectFieldValuesForWrite:()=>$r});var Jr=I({"src/tools/fields.ts"(){Ee(),Dt(),Rr(),Er=["text","long","bool","date","person","select","number","link"],Ar=new Set(Er)}}),Qr={};async function Gr(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=(e.domains??[]).map(ot).filter(e=>e.length>0),n=void 0!==e.level?ot(e.level):void 0;if(i.length>0){const{data:r}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),n=r?.domains??[];if(n.length>0){const e=new Set(n.map(ot).filter(e=>e.length>0)),t=i.filter(t=>!e.has(t));if(t.length>0)return Ot(ut(`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:r,validateProjectFieldValuesForWrite:i}=await Promise.resolve().then(()=>(Jr(),Dr)),n=await r(t,e.project_id),s=await i(t,e.project_id,n,e.fields);if(s.error)return Ot(ut(s.error));a=s.fields}const s=await Ft(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:i,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:r,updated_at:o,updated_by:r}},{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:r,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null});if(c)throw new Error(c.message);if(n&&await xr(t,e.project_id,n),e.parent_ids&&e.parent_ids.length>0)for(const i 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:i,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"});n&&process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${i}: ${n.message}\n`)}return await t.from("change_history").insert({item_id:s,project_id:e.project_id,changed_by:r,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?At(dt({id:s,type:e.type})):At(dt({id:s,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",domains:i,level:n??"",project_id:e.project_id}))}catch(e){return Ot(xt(e))}}E(Qr,{createItemHandler:()=>Gr});var Yr=I({"src/tools/create-item.ts"(){Ee(),Wt(),ka(),Dt(),Or()}});function Kr(e,t){const r=function(e){return`SG-${e}`}(t);return{id:e,outcome:"captured_as_change",change:{id:r,sg_number:t,status:"open"},message:`Captured as change ${r}, awaiting approval. This requirement stays at its approved revision until a human approver approves the change; no MCP tool can approve, dismiss, or apply it.`}}function Zr(e){return{id:e,outcome:"under_review",message:"This requirement is under change control. Your edit was submitted; if it changed the requirement's meaning it is now a change awaiting a human approver, otherwise it wrote through live. Reload the item to confirm. No MCP tool can approve, dismiss, or apply a change."}}var Xr=I({"src/core/change-control.ts"(){}}),ei={};async function ti(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=async(i,n,a,s)=>{const o=await qt(t,e.project_id,i);if(!o)return{updated_fields:[],error:`Item "${i}" not found`};const d="approved"===o.approval_state,c=void 0!==n.domains?n.domains.map(ot).filter(e=>e.length>0):void 0,l=void 0!==n.level?ot(n.level):void 0;if(void 0!==c&&c.length>0){const{data:r}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),i=r?.domains??[];if(i.length>0){const e=new Set(i.map(ot).filter(e=>e.length>0)),t=c.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const m={...o.data},p={...o.data},u=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==n.title&&_(o.data.title,n.title)&&(p.title=n.title,u.push("title")),void 0!==n.body&&_(o.data.body,n.body)&&(p.body=n.body,u.push("body")),void 0!==n.summary&&_(o.data.summary,n.summary)&&(p.summary=n.summary,u.push("summary")),void 0!==c&&_(o.data.tags?.domains??[],c)&&(p.tags={...p.tags,domains:c},u.push("domains")),void 0!==l&&_(o.data.tags?.level,l)&&(p.tags={...p.tags,level:l},u.push("level")),void 0!==n.status&&_(o.data.status,n.status)&&(p.status=n.status,u.push("status")),void 0!==n.fields&&Object.keys(n.fields).length>0){const{getProjectFields:r,validateProjectFieldValuesForWrite:i,canonicalizeFieldKeys:a}=await Promise.resolve().then(()=>(Jr(),Dr)),s=await r(t,e.project_id),d=await i(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)&&(p.fields=c,u.push("fields"))}if(0===u.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};p.metadata={...p.metadata,updated_at:(new Date).toISOString(),updated_by:r};const f=n.title??o.title,{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:i,p_project_id:e.project_id,p_type:o.type,p_title:f,p_data:p,p_user_id:r,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(g)return{updated_fields:[],error:g};if(!h)return{updated_fields:[],error:`Update silently failed for "${i}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};u.includes("level")&&l&&await xr(t,e.project_id,l);const y={item_id:i,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:m,new_data:p,actor:Sa(),session_id:ja()};if(a&&(y.batch_id=a),s&&(y.reason=s),await t.from("change_history").insert(y).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),d&&function(e){return e.some(e=>"title"===e||"body"===e||"type"===e)}(u)){const r=await async function(e,t,r){const{data:i,error:n}=await e.from("item_suggestions").select("sg_number").eq("project_id",t).eq("item_id",r).eq("status","open").maybeSingle();return n||!i?null:"number"==typeof i.sg_number?i.sg_number:null}(t,e.project_id,i);return null!==r?{updated_fields:u,updatedData:p,itemType:o.type,capturedSg:r}:{updated_fields:u,updatedData:p,itemType:o.type,capturedUnknown:!0}}return{updated_fields:u,updatedData:p,itemType:o.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),r=!0===e.continue_on_error,n=[],a=[];for(const s of e.updates){const{updated_fields:o,capturedSg:d,capturedUnknown:c,error:l}=await i(s.item_id,s,t,e.reason);if(l){if(kt(l))return Ot(xt(l));if(!r){const e=l instanceof Error?l.message:String("object"==typeof l&&l&&"message"in l?l.message??"":l);return Ot(ut(`Batch stopped at "${s.item_id}": ${e}. ${n.length} item(s) already updated.`))}a.push({item_id:s.item_id,error:String(l)})}else void 0!==d?n.push(Kr(s.item_id,d)):c?n.push(Zr(s.item_id)):n.push({id:s.item_id,updated_fields:o})}return At(dt({batch_id:t,updated:n.length,results:!1===e.echo?void 0:n,errors:a}))}if(!e.item_id)return Ot(ut("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:n,updatedData:a,itemType:s,capturedSg:o,capturedUnknown:d,error:c}=await i(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(c){const t=c instanceof Error?c.message:String("object"==typeof c&&c&&"message"in c?c.message??"":c);return t.includes("not found")?Ot(mt("Item",e.item_id)):t.includes("Unknown domain")||t.includes("Unknown field")?Ot(ut(t)):wt(t)||kt(c)?Ot(xt(c)):Ot(It(t))}if(void 0!==o)return At(dt(Kr(e.item_id,o)));if(d)return At(dt(Zr(e.item_id)));if(!1===e.echo)return At(dt({id:e.item_id,updated_fields:n}));const l=a??{};return At(dt({id:e.item_id,type:s,title:l.title??"",summary:l.summary??"",body:l.body??"",domains:l.tags?.domains??[],level:l.tags?.level??"",updated_fields:n}))}catch(e){return Ot(xt(e))}}E(ei,{updateItemHandler:()=>ti});var ri,ii,ni=I({"src/tools/update-item.ts"(){Ee(),Wt(),ka(),Dt(),Or(),Xr()}});function ai(e){const t=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(t){const r=t.toLowerCase();if("1"===r||"true"===r||"all"===r)return!0;if(t.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!P().require_confirmation_for.includes(e)}function si(e,t=ri){const r=Date.now()+t,i={...e,exp:r},n=Buffer.from(JSON.stringify(i)).toString("base64url");return{token:`${n}.${S.default.createHmac("sha256",ii).update(n).digest("base64url")}`,expires_at:new Date(r).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function oi(e,t){if("string"!=typeof e||!e.includes("."))return{valid:!1,reason:"Token format invalid"};const[r,i]=e.split(".");if(!r||!i)return{valid:!1,reason:"Token format invalid"};const n=S.default.createHmac("sha256",ii).update(r).digest("base64url"),a=Buffer.from(i,"utf8"),s=Buffer.from(n,"utf8");if(a.length!==s.length||!S.default.timingSafeEqual(a,s))return{valid:!1,reason:"Token signature invalid"};let o;try{o=JSON.parse(Buffer.from(r,"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 di(e){if(Array.isArray(e))return e.map(di);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e).sort())t[r]=di(e[r]);return t}return e}function ci(e){const t=JSON.stringify(di(e));return S.default.createHash("sha256").update(t).digest("base64url").slice(0,16)}var li,mi=I({"src/middleware/confirmation.ts"(){$(),ri=6e4,ii=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:S.default.randomBytes(32).toString("base64url")})()}}),pi={};async function ui(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=await async function(e,t,r){const{data:i,error:n}=await e.from("items").select("*").eq("id",r).eq("project_id",t).maybeSingle();if(n)throw new Error(n.message);return i}(t,e.project_id,e.item_id);if(!i)return Ot(mt("Item",e.item_id));if(i.deleted_at)return Ot(ut(`Item ${e.item_id} is already deleted`));if(ai(li)){const t={tool:li,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const r=si(t);return At(dt({status:"confirmation_required",preview:{id:e.item_id,title:i.title,type:i.type,would_soft_delete:!0},confirmation_token:r.token,expires_at:r.expires_at,expires_in_seconds:r.expires_in_seconds,message:`Re-call atoms_delete_item with the same project_id, item_id, and confirmation_token within ${r.expires_in_seconds}s to execute.`}))}const r=oi(e.confirmation_token,t);if(!r.valid)return Ot(ut(`confirmation_token rejected: ${r.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:r,p_expected_updated_at:i.updated_at,p_event_source:"mcp",p_actor:Sa(),p_session_id:ja()});if(n)throw new Error(n.message);return At(dt({id:e.item_id,title:i.title,type:i.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return Ot(xt(e))}}E(pi,{deleteItemHandler:()=>ui});var _i=I({"src/tools/delete-item.ts"(){Ee(),Wt(),ka(),mi(),Dt(),li="atoms_delete_item"}}),fi={};async function hi(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const{data:i,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(!i)return Ot(mt("Item",e.item_id));if(!i.deleted_at)return Ot(lt(`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:i.type,p_title:i.title,p_data:i.data,p_user_id:r,p_event_source:"restore",p_event_session_id:ja()??null,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:i.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:r,event_type:"restored",old_data:null,new_data:i.data,actor:Sa(),session_id:ja()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),At(dt({id:e.item_id,title:i.title,type:i.type,restored:!0,message:`Item ${e.item_id} restored successfully.`}))}catch(e){return Ot(xt(e))}}E(fi,{restoreItemHandler:()=>hi});var gi=I({"src/tools/restore-item.ts"(){Ee(),ka(),Dt()}}),yi={};async function wi(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=async(i,n,a)=>{const s=await qt(t,e.project_id,i.from_id);if(!s)throw new Error(`Item "${i.from_id}" not found`);const o=await qt(t,e.project_id,i.to_id);if(!o)throw new Error(`Item "${i.to_id}" not found`);const{error:d}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:i.from_id,p_to_id:i.to_id,p_type:i.type,p_action:i.action,p_user_id:r,p_event_source:"mcp",p_expected_from_updated_at:i.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:i.expected_to_updated_at??o.updated_at});if(d)throw new Error(d.message);const c={item_id:i.from_id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:null,new_data:{relationship_change:{action:i.action,type:i.type,from:i.from_id,to:i.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 Ot(ut(`Self-reference in batch: "${t.from_id}"`));const r=[...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",r),a=new Set((n??[]).map(e=>e.id)),s=r.filter(e=>!a.has(e));if(s.length>0)return Ot(mt("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,r]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?d.get(e)?.delete(r):(d.has(e)||d.set(e,new Set),d.get(e).add(r))}const c=0,l=1,m=2,p=new Map,u=new Set;for(const[e,t]of d){u.add(e);for(const e of t)u.add(e)}const _=e=>{if((p.get(e)??c)!==c)return null;const t=[],r=[],i=e=>{p.set(e,l),r.push(e),t.push({node:e,parents:[...d.get(e)??[]],idx:0})};for(i(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){p.set(e.node,m),r.pop(),t.pop();continue}const n=e.parents[e.idx];e.idx++;const a=p.get(n)??c;if(a===l){const e=r.indexOf(n);return[...r.slice(e),n]}a!==m&&i(n)}return null};for(const e of u){const t=_(e);if(t)return Ot(ut(`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 i(t,f,e.reason);return At(dt({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?Ot(ut("Cannot create a relationship between an item and itself")):(await i({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?At(dt({action:e.action,from_id:e.from_id,to_id:e.to_id})):At(dt({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}`}))):Ot(ut("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."))}catch(e){return Ot(xt(e))}}E(yi,{linkItemsHandler:()=>wi});var bi=I({"src/tools/link-items.ts"(){Ee(),Wt(),ka(),Dt()}}),vi=I({"src/core/bulk-parent-links.ts"(){}}),ji={};function Si(e){return new Set(["22023","23503","23505","23514"]).has(e.code??"")}async function xi(e){try{if(!e.items||0===e.items.length)return Ot(ut("items array must contain at least 1 item"));if(e.items.length>100)return Ot(ut(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=await async function(e,t,r){const{data:i}=await e.from("metadata").select("domains").eq("project_id",t).maybeSingle(),n=i?.domains??[],a=n.length>0?new Set(n.map(ot).filter(e=>e.length>0)):null,s=ci(n.map(ot).filter(e=>e.length>0).sort()),o=[],d=new Set,c={};for(let e=0;e<r.length;e++){const t=r[e];if(c[t.type]=(c[t.type]??0)+1,!a)continue;const i=(t.domains??[]).map(ot).filter(e=>e.length>0);if(0===i.length)continue;const s=i.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(ai("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:ci({items:e.items,registered_domain_hash:i.registeredDomainHash})};if(!e.confirmation_token){const r=si(t);return At(dt({status:"confirmation_required",preview:{total_items:e.items.length,by_type:i.typeBreakdown,sample_titles:e.items.slice(0,5).map(e=>e.title),would_fail:i.errors.length>0,errors:i.errors,registered_domain_hash:i.registeredDomainHash},confirmation_token:r.token,expires_at:r.expires_at,expires_in_seconds:r.expires_in_seconds,message:`Re-call atoms_bulk_import with the same project_id, items array, and confirmation_token within ${r.expires_in_seconds}s to execute. Changing items or project domains will invalidate the token.`}))}const r=oi(e.confirmation_token,t);if(!r.valid)return Ot(ut(`confirmation_token rejected: ${r.reason}`))}const n=(new Date).toISOString(),a=ja(),s=[],o=[...i.errors],d=[],c=new Map,l=async r=>{let i=c.get(r);if(!i){const n=await Ft(t,e.project_id,r),a=/^([A-Z]+)-(\d+)$/.exec(n);if(!a)throw new Error(`Unexpected item id format from next_item_id: ${n}`);i={prefix:a[1],next:Number(a[2])},c.set(r,i)}const n=`${i.prefix}-${String(i.next).padStart(3,"0")}`;return i.next+=1,n};for(let t=0;t<e.items.length;t++){const r=e.items[t];if(i.invalidDomainIndexes.has(t))continue;const n=(r.domains??[]).map(ot).filter(e=>e.length>0),a=void 0!==r.level?ot(r.level):void 0;try{const e=await l(r.type);d.push({itemId:e,input:r,sanitizedDomains:n,sanitizedLevel:a,index:t})}catch(e){o.push({index:t,title:r.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===d.length)return At(dt({created:0,items:[],errors:o}));const m=[],p=new Map;for(const{itemId:t,input:i,sanitizedDomains:a,sanitizedLevel:s}of d){const o={id:t,type:i.type,title:i.title,summary:i.summary,body:i.body,tags:{domains:a,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:i.parent_id?[i.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:n,created_by:r,updated_at:n,updated_by:r}};p.set(t,o),m.push({id:t,project_id:e.project_id,type:i.type,title:i.title,data:o,created_by:r,updated_by:r})}const u=m.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:_}=await t.rpc("bulk_save_items_with_revisions",{p_project_id:e.project_id,p_items:u,p_user_id:r,p_event_source:"mcp"});if(_&&Si(_))for(const{itemId:i,input:n,index:c}of d){const d=m.find(e=>e.id===i);if(!d)continue;const{error:l}=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:r,p_event_source:"mcp",p_event_session_id:a,p_diff_summary:null});l?o.push({index:c,title:n.title,error:l.message}):s.push({id:i,title:n.title,type:n.type})}else{if(_)throw _;for(const{itemId:e,input:t}of d)s.push({id:e,title:t.title,type:t.type})}const f=d.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:t,input:r})=>({from_id:t,to_id:r.parent_id,type:"parent",project_id:e.project_id}));await async function(e){for(const t of e.links){const{error:r}=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"});r&&e.warn(`bulk parent link sync failed for ${t.to}: ${r.message??"unknown error"}`)}}({client:t,projectId:e.project_id,links:f.map(e=>({from:e.from_id,to:e.to_id})),userId:r,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const h=s.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:p.get(t.id)??null,actor:Sa(),session_id:a}));h.length>0&&await t.from("change_history").insert(h).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const g=new Set(s.map(e=>e.id)),y=new Set(d.filter(({itemId:e,sanitizedLevel:t})=>t&&g.has(e)).map(({sanitizedLevel:e})=>e));for(const r of y)await xr(t,e.project_id,r);return At(dt({created:s.length,items:s,errors:o.length>0?o:[],project_id:e.project_id}))}catch(e){return Ot(xt(e))}}E(ji,{bulkImportHandler:()=>xi,canRetryBulkImportPerItem:()=>Si});var ki=I({"src/tools/bulk-import.ts"(){Ee(),Wt(),ka(),mi(),Dt(),vi(),Or()}}),Ii={};async function Ei(e){try{const t=await ge(),r=ve(),i=je();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const n=await qt(t,e.project_id,e.item_id);if(!n)return Ot(mt("Item",e.item_id));if("test-case"!==n.type)return Ot(ut(`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:i||r,p_actor_user_id:r,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:r,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 At(dt({item_id:e.item_id,result:e.result,run_at:s,run_by:i||r,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 Ot(xt(e))}}E(Ii,{recordTestResultHandler:()=>Ei});var Ai=I({"src/tools/record-test-result.ts"(){Ee(),Wt(),ka(),Dt()}}),Oi={};async function Ri(e){try{const t=await ge(),r=ve(),i=je();if(!Array.isArray(e.results)||0===e.results.length)return Ot(ut("results must be a non-empty array"));if(e.results.length>100)return Ot(ut(`results must have at most 100 entries (got ${e.results.length})`));try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const n=await qt(t,e.project_id,e.item_id);if(!n)return Ot(mt("Item",e.item_id));if("test-case"!==n.type)return Ot(ut(`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:i||r,p_actor_user_id:r,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:r,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`)}),At(dt({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 Ot(xt(e))}}E(Oi,{recordTestResultsBulkHandler:()=>Ri});var Di,Hi,Ci,Ui,zi=I({"src/tools/record-test-results-bulk.ts"(){Ee(),Wt(),ka(),Dt()}});function qi(e){return Math.min(Math.max(e??5,1),10)}var Ti=I({"src/core/trace-graph.ts"(){Di=200,Hi=new Set(["parent","verifies","mitigated_by"]),Ci=new Set(["child","verified_by","mitigates"]),Ui={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"}}}),Mi={};async function Pi(e){try{const t=qi(e.depth),r=await ge(),i=await qt(r,e.project_id,e.item_id);if(!i)return Ot(mt("Item",e.item_id));const{data:n,error:a}=await r.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 r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);const d=Lt(n??[],s??[]);return At(dt(function(e){const t=qi(e.depth),r=e.relationshipTypes?.length?new Set(e.relationshipTypes):null,i=new Map(e.items.map(e=>[e.id,e]));i.has(e.rootItemId)||i.set(e.rootItemId,e.rootItem);const n=new Map,a=(e,t,r)=>{n.has(e)||n.set(e,[]),n.get(e).push({neighbor:t,relType:r})};for(const t of e.relationships){const i=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(!Hi.has(i)||r&&!r.has(i)||a(t.from_id,t.to_id,i),Ci.has(i))){const e=Ui[i]??i;r&&!r.has(e)||a(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!Ci.has(i)||r&&!r.has(i)||a(t.from_id,t.to_id,i),Hi.has(i))){const e=Ui[i]??i;r&&!r.has(e)||a(t.to_id,t.from_id,e)}"related"!==i||r&&!r.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<Di;){const{id:e,depth:r,relType:a,from:l}=c.shift();if(s.has(e)||r>t)continue;s.add(e);const m=i.get(e);if(m&&(o.push({id:e,title:m.title,type:m.type,relationship:a,depth:r,from:l}),d.push({from:l,to:e,type:a}),r<t))for(const t of n.get(e)??[])s.has(t.neighbor)||c.push({id:t.neighbor,depth:r+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>=Di?{truncated:!0,truncation_message:`Results capped at ${Di} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:i.title??e.item_id,type:i.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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(Mi,{traceHandler:()=>Pi});var $i=I({"src/tools/trace.ts"(){Ee(),Wt(),Ti(),Dt()}}),Ni={};async function Li(e){try{let t=(await ge()).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:r,error:i}=await t;if(i)throw new Error(i.message);return At(dt({assets:r||[],total:(r||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(Ni,{listAssetsHandler:()=>Li});var Fi=I({"src/tools/assets.ts"(){Ee(),Dt()}}),Wi={};async function Vi(e,t,r,i){if(r&&i)throw new Error("baseline_id and as_of are mutually exclusive");if(i)return i;if(!r)return null;const{data:n,error:a}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",r).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 Bi(e,t,r){if(r){const{data:i,error:n}=await e.rpc("variables_at",{p_project_id:t,p_snapshot_at:r});if(n)throw new Error(n.message);return i??[]}const{data:i,error:n}=await e.from("project_variables").select("*").eq("project_id",t).order("name");if(n)throw new Error(n.message);return i??[]}async function Ji(e,t,r,i){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:r,p_event_source:i,p_variable_id:t.id??null});if(a)throw new Error(a.message);return n}async function Qi(e){try{const t=await ge(),r=await Vi(t,e.project_id,e.baseline_id,e.as_of),i=await Bi(t,e.project_id,r);return At(dt({variables:i,total:i.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function Gi(e){try{const t=await ge(),r=await Vi(t,e.project_id,e.baseline_id,e.as_of),i=(await Bi(t,e.project_id,r)).find(t=>t.name===e.variable_name)??null;if(!i)return Ot(mt("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 At(dt({variable:i,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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function Yi(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(!i.data)return Ot(mt("Variable",e.variable_name));const n={updated_by:r,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),At(dt({variable:await Ji(t,{...i.data,...n,project_id:e.project_id,name:e.variable_name,value:n.value??i.data.value,unit:n.unit??i.data.unit,description:n.description??i.data.description},r,"mcp")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function Ki(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const n=e.variables.filter(e=>!i.test(e.name));if(n.length>0)return Ot(ut(`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 Ot(ut(`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 Ot(ut(`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:r,updated_by:r})),l=await async function(e,t,r,i){const{data:n,error:a}=await e.rpc("bulk_save_variables_with_revisions",{p_project_id:t,p_variables:r,p_user_id:i,p_event_source:"mcp"});if(a)throw new Error(a.message);return n??[]}(t,e.project_id,c,r);return At(dt({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 Ot(ut("Provide either (name, value) for single variable or variables[] for batch."));if(!i.test(e.name))return Ot(ut(`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 Ot(ut(`Variable "${e.name}" already exists in this project.`));const a=await Ji(t,{project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null},r,"mcp");return!1===e.echo?At(dt({name:e.name})):At(dt({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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function Zi(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const{data:i}=await t.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!i)return Ot(mt("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 Ot(ut(`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(ai("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const r=si(t);return At(dt({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:a,would_orphan_references:a>0},confirmation_token:r.token,expires_at:r.expires_at,expires_in_seconds:r.expires_in_seconds,message:`Re-call atoms_delete_variable with the same project_id, name, and confirmation_token within ${r.expires_in_seconds}s to execute.`}))}const r=oi(e.confirmation_token,t);if(!r.valid)return Ot(ut(`confirmation_token rejected: ${r.reason}`))}const s=await async function(e,t,r,i){const{data:n,error:a}=await e.rpc("delete_variable_with_revision",{p_project_id:t,p_variable_id:r,p_user_id:i,p_event_source:"mcp"});if(a)throw new Error(a.message);return Boolean(n)}(t,e.project_id,i.id,r);return s?At(dt({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})):Ot(mt("Variable",e.name))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(Wi,{createVariableHandler:()=>Ki,deleteVariableHandler:()=>Zi,getVariableHandler:()=>Gi,listVariablesHandler:()=>Qi,updateVariableHandler:()=>Yi});var Xi=I({"src/tools/variables.ts"(){Ee(),mi(),Dt()}}),en={};async function tn(e,t){const{data:r}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:r?.domains??[],levels:r?.levels??[]}}async function rn(e,t,r,i){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:r,levels:i},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function nn(e){try{const t=await ge(),{domains:r}=await tn(t,e.project_id),{counts:i,orphans:n}=await async function(e,t,r){const{data:i}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null),n={};for(const e of r)n[e]=0;const a={};for(const e of i??[]){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(r),o={};for(const[e,t]of Object.entries(a))s.has(e)||(o[e]=t);return{counts:n,orphans:o}}(t,e.project_id,r),a=r.map(e=>({name:e,registered:!0,item_count:i[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 At(dt({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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function an(e){try{const t=await ge();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const{domains:r,levels:i}=await tn(t,e.project_id),n=e.name.trim().toLowerCase();return n?r.includes(n)?Ot(ut(`Domain "${n}" already exists in this project.`)):(await rn(t,e.project_id,[...r,n],i),At(dt({domain:{name:n},message:`Domain "${n}" registered. You can now tag items with domains=["${n}"].`}))):Ot(ut("Domain name cannot be empty."))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function sn(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const{domains:i,levels:n}=await tn(t,e.project_id),a=e.name.trim().toLowerCase(),s=e.new_name.trim().toLowerCase();if(!s)return Ot(ut("new_name cannot be empty."));const o=i.includes(a);if(!o){const{data:r}=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(!r||0===r.length)return Ot(mt("Domain",a))}if(s!==a&&i.includes(s))return Ot(ut(`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 At(dt({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?i.map(e=>e===a?s:e):i.includes(s)?i:[...i,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:r,p_event_source:"mcp"});if(p)throw new Error(p.message);return At(dt({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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}async function on(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const{domains:i,levels:n}=await tn(t,e.project_id),a=e.name.trim().toLowerCase(),s=i.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 Ot(mt("Domain",a));if(c>0&&!e.force)return Ot(ut(`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(ai("atoms_delete_domain")){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:a};if(!e.confirmation_token){const e=si(t);return At(dt({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 r=oi(e.confirmation_token,t);if(!r.valid)return Ot(ut(`confirmation_token rejected: ${r.reason}`))}const l=s?i.filter(e=>e!==a):i;if(await rn(t,e.project_id,l,n),c>0){const{error:i}=await t.rpc("apply_domain_change",{p_project_id:e.project_id,p_old_domain:a,p_new_domain:null,p_user_id:r,p_event_source:"mcp"});if(i)throw new Error(i.message)}return At(dt({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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(en,{createDomainHandler:()=>an,deleteDomainHandler:()=>on,listDomainsHandler:()=>nn,updateDomainHandler:()=>sn});var dn=I({"src/tools/domains.ts"(){Ee(),mi(),Dt()}}),cn={};async function ln(e){try{const t=await ge(),{data:r,error:i}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle(),n=r?.name??null,a=i?.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 Ot(mt("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:r,error:i}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(i)throw new Error(i.message);const n=new Map;for(const e of r??[])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:u,error:_}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(_)throw new Error(_.message);const f=Lt(s??[],u??[]),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)"],r=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++,r&&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 At(dt({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")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(cn,{projectSummaryHandler:()=>ln});var mn,pn=I({"src/tools/project-summary.ts"(){Ee(),Wt(),Dt()}}),un={};async function _n(e){try{const t=await ge();let r,i;if(e.query&&e.query.trim().length>0){const n=await Nt(t,e.project_id,e.query,{type:e.type,limit:e.limit});r=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})),i=n.totalCount}else{const n=await zt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});r=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})),i=n.totalCount}const n=await async function(e,t){const{data:r,error:i}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(i)throw new Error(i.message);const n=new Set,a=new Set;for(const e of r??[]){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)n.add(t);const r=t.level;r&&a.add(r)}}return{domains:[...n].sort(),levels:[...a].sort()}}(t,e.project_id);return At(dt({items:r,filters:{domains:n.domains,levels:n.levels,types:mn},project_id:e.project_id},ct(i,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(un,{browseHandler:()=>_n});var fn,hn,gn,yn,wn=I({"src/tools/browse.ts"(){Ee(),Wt(),Dt(),mn=["requirement","test-case","note","table"]}}),bn={};async function vn(e){try{const t=e.direction??"downstream",r=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,i=await ge(),n=await qt(i,e.project_id,e.item_id);if(!n)return Ot(mt("Item",e.item_id));const{data:a,error:s}=await i.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 i.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,r)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:r})};for(const e of a??[]){const r=e.type;"upstream"!==t&&"both"!==t||(hn.includes(r)&&m(e.from_id,e.to_id,r),gn.includes(r)&&m(e.to_id,e.from_id,yn[r]??r)),"downstream"!==t&&"both"!==t||(gn.includes(r)&&m(e.from_id,e.to_id,r),hn.includes(r)&&m(e.to_id,e.from_id,yn[r]??r)),"related"===r&&(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 u=[];let _=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&&u.length<fn;){const{id:e,depth:t,path:i}=f.shift();if(p.has(e))continue;if(null!==r&&t>r)continue;p.add(e);const n=c.get(e);if(n&&(u.push({item_id:e,title:Et(n.title),type:n.type,depth:t,relationship_path:i}),t>_&&(_=t),null===r||t<r))for(const r of l.get(e)??[])p.has(r.neighbor)||f.push({id:r.neighbor,depth:t+1,path:[...i,{from_id:e,to_id:r.neighbor,relationship_type:r.relType}]})}let h=0;if(e.include_variable_refs){const{data:t}=await i.from("variable_references").select("variable_id").eq("item_id",e.item_id).eq("project_id",e.project_id),r=[...new Set((t??[]).map(e=>e.variable_id))];if(r.length>0){const{data:t}=await i.from("project_variables").select("id, name").in("id",r),n=new Map((t??[]).map(e=>[e.id,e.name])),{data:a}=await i.from("variable_references").select("variable_id, item_id").in("variable_id",r).eq("project_id",e.project_id).neq("item_id",e.item_id);for(const t of a??[]){const r=t.item_id;if(p.has(r))continue;if(u.length>=fn)break;p.add(r);const i=c.get(r);if(!i)continue;const a=n.get(t.variable_id)??t.variable_id;u.push({item_id:r,title:Et(i.title),type:i.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:r,relationship_type:`variable_ref:${a}`}]}),h++}}}const g={};for(const e of u)g[e.type]=(g[e.type]??0)+1;const y=c.get(e.item_id);return At(dt({root:{item_id:e.item_id,title:Et(y?.title??n.title),type:y?.type??n.type},impacted_items:u,summary:{total_impacted:u.length,by_type:g,max_depth_reached:_,...h>0?{variable_impact_count:h}:{},...u.length>=fn?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):Ot(It(e instanceof Error?e.message:String(e)))}}E(bn,{impactAnalysisHandler:()=>vn});var jn=I({"src/tools/impact-analysis.ts"(){Ee(),Wt(),Dt(),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=I({"src/core/relationship-sync.ts"(){}}),xn={};function kn(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ot(_t()):null}async function In(e,t){const{data:r,error:i}=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(i)throw new Error(i.message);return r}async function En(e,t,r){const{data:i,error:n}=await e.from("items").select("id, deleted_at").eq("project_id",t).eq("id",r).maybeSingle();if(n)throw new Error(n.message);if(a=i,!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:r});if(s)throw new Error(s.message)}async function An(e,t,r){const{data:i,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n)return Ot(It(n.message));if(!i)return Ot(mt("Project",t));const{data:a,error:s}=await e.from("organizations").select("feature_flags").eq("id",i.org_id).maybeSingle();return s?Ot(It(s.message)):!0!==(a?.feature_flags??{})[r]?Ot(lt(`Feature '${r}' 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 ge(),r=await async function(e,t){const{data:r,error:i}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, release_version, release_status").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1});if(i)throw new Error(`listBaselines: ${i.message}`);return r??[]}(t,e.project_id),i=Math.max(e.offset??0,0),n=Math.min(Math.max(e.limit??50,1),100);return At(dt({baselines:r.slice(i,i+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,release_version:e.release_version,release_status:e.release_status})),total:r.length,offset:i,limit:n}))}catch(e){return kn(e)??Ot(It(e instanceof Error?e.message:String(e)))}}async function Rn(e){try{const t=await ge(),r=await An(t,e.project_id,"baselines_enabled");if(r)return r;const{data:i,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?Ot(lt(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):Ot(It(n.message)):At(dt({id:i.id,name:i.name,description:i.description,field_definitions_snapshot:i.field_definitions_snapshot,snapshot_at:i.snapshot_at,created_at:i.created_at,locked:!1}))}catch(e){return kn(e)??Ot(It(e instanceof Error?e.message:String(e)))}}async function Dn(e){try{const t=await ge(),r=await Mt(t,e.baseline_id);if(!r)return Ot(mt("Baseline",e.baseline_id));const i=await An(t,r.project_id,"baselines_enabled");if(i)return i;if(null!==r.locked_at)return Ot(lt("Baseline is already locked",["Locks are one-way; nothing to do"]));const{data:n}=await t.from("projects").select("org_id").eq("id",r.project_id).maybeSingle();if(!n)return Ot(mt("Project",r.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ot(_t());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 Ot(lt("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?Ot(It(c.message)):At(dt({id:d.id,locked_at:d.locked_at,locked_by:d.locked_by}))}catch(e){return kn(e)??Ot(It(e instanceof Error?e.message:String(e)))}}async function Hn(e){try{const t=await ge(),[r,i]=await Promise.all([Mt(t,e.baseline_a_id),Mt(t,e.baseline_b_id)]);if(!r||!i)return Ot(mt("Baseline","one of the baseline_ids"));if(r.project_id!==i.project_id)return Ot(lt("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[n,a]=await Promise.all([$t(t,r.project_id,r.snapshot_at),$t(t,i.project_id,i.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),r=o.get(e);if(!t&&r)l++,c.push({item_id:e,change_type:"added"});else if(t&&!r)m++,c.push({item_id:e,change_type:"removed"});else if(t&&r){const i=[];t.title!==r.title&&i.push("title"),t.type!==r.type&&i.push("type");JSON.stringify(t.data??{})!==JSON.stringify(r.data??{})&&i.push("data"),i.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:i}))}}const u=Math.max(e.offset??0,0),_=Math.min(Math.max(e.limit??50,1),200),f=e.detail?c.slice(u,u+_):c.slice(u,u+_).map(({item_id:e,change_type:t,fields_changed:r})=>({item_id:e,change_type:t,fields_changed:r}));return At(dt({summary:{added:l,removed:m,modified:p,total_compared:d.length},items:f,page_info:{offset:u,limit:_,total:c.length},baselines:{a:{id:r.id,name:r.name,snapshot_at:r.snapshot_at},b:{id:i.id,name:i.name,snapshot_at:i.snapshot_at}}}))}catch(e){return kn(e)??Ot(It(e instanceof Error?e.message:String(e)))}}async function Cn(e){try{const t=await ge(),r=await Mt(t,e.baseline_id);if(!r)return Ot(mt("Baseline",e.baseline_id));const i=await An(t,r.project_id,"baselines_enabled");if(i)return i;const{data:n}=await t.from("projects").select("org_id").eq("id",r.project_id).maybeSingle();if(!n)return Ot(mt("Project",r.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ot(_t());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 Ot(lt("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const d=await $t(t,r.project_id,r.snapshot_at),c=d.map(e=>e.id),{data:l,error:m}=c.length>0?await t.from("items").select("*").eq("project_id",r.project_id).in("id",c):{data:[],error:null};if(m)return Ot(It(m.message));const p=function(e,t){const r=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=r.get(e.id),i=[];var n,a;return t?(null!==t.deleted_at&&i.push("deleted_at"),t.type!==e.type&&i.push("type"),t.title!==e.title&&i.push("title"),n=t.data,a=e.data,JSON.stringify(n??{})!==JSON.stringify(a??{})&&i.push("data")):i.push("missing"),0===i.length?[]:[{id:e.id,type:e.type,title:e.title,data:e.data??{},diff_summary:{changed_fields:i,restored:!0},oldData:t?.data??null}]})}(d,l??[]),{data:u,error:_}=await t.rpc("variables_at",{p_project_id:r.project_id,p_snapshot_at:r.snapshot_at});if(_)return Ot(It(_.message));const f=u??[];if(!0!==e.confirm)return At(dt({preview:!0,items_to_restore:p.length,variables_to_restore:f.length,field_definitions_to_restore:r.field_definitions_snapshot?.length??null}));const h=await In(t,{baselineId:r.id,projectId:r.project_id,userId:s});return At(dt({ok:!0,items_restored:h.items_restored,variables_restored:h.variables_restored,field_definitions_restored:h.field_definitions.length}))}catch(e){return kn(e)??Ot(It(e instanceof Error?e.message:String(e)))}}E(xn,{createBaselineHandler:()=>Rn,diffBaselinesHandler:()=>Hn,listBaselinesHandler:()=>On,lockBaselineHandler:()=>Dn,restoreBaselineHandler:()=>Cn,restoreBaselineStateAtomically:()=>In,syncRestoredItemRelationships:()=>En});var Un,zn,qn,Tn,Mn,Pn,$n,Nn,Ln,Fn,Wn=I({"src/tools/baselines.ts"(){Ee(),ka(),Dt(),Wt(),Sn()}});function Vn(e){const t=e?.severity||"",r=e?.exposure||"",i=e?.controllability||"";return t&&r&&i?"S0"===t||"E0"===r||"C0"===i?"QM":qn[`${t}-${r}-${i}`]||Un:Un}function Bn(e){const t=parseInt(e?.severity||"",10),r=parseInt(e?.occurrence||"",10),i=parseInt(e?.detection||"",10);return Number.isNaN(t)||Number.isNaN(r)||Number.isNaN(i)?Un:String(t*r*i)}function Jn(e,t){return"hara"===e?Vn(t):Bn(t)}function Qn(e,t,r){if(r)return!1;if("hara"===e){const e=Vn(t);return"C"===e||"D"===e}const i=parseInt(Bn(t),10);return!Number.isNaN(i)&&i>=200}function Gn(e,t,r){if(!e?.approved||!e.approved_at)return!1;const i=Date.parse(e.approved_at);return!Number.isNaN(i)&&[...e.source_req?[e.source_req]:[],...t].some(e=>{const t=r(e),n=t?Date.parse(t):NaN;return!Number.isNaN(n)&&n>i})}var Yn,Kn,Zn=I({"src/core/analysis.ts"(){Un="—",zn=["prevention","detection","mitigation"],qn={"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"},Mn={hara:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea:{severity:Tn=["1","2","3","4","5","6","7","8","9","10"],occurrence:Tn,detection:Tn}},Pn={hara:["failure_mode","operating_scenario","severity","exposure","controllability","safe_state","ftti","rationale"],dfmea:["failure_mode","cause","severity","occurrence","detection","rationale"]},$n={hara:"safety-goal",dfmea:"failure-mode"},Nn={hara:"SG",dfmea:"FM"},Ln={hara:"HARA",dfmea:"DFMEA"},Fn={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,r){const{data:i,error:n}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(n)throw new Error(`ID generation failed: ${n.message}`);return i}function ra(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function ia(e){return JSON.parse(JSON.stringify(e??{}))}async function na(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=e.source_req_ids??[];if(i.length>50)return Ot(ut("source_req_ids supports at most 50 entries per call"));if(i.length>0){const{data:r,error:n}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null).in("id",i);if(n)throw new Error(n.message);const a=new Map((r??[]).map(e=>[e.id,e])),s=i.filter(e=>!a.has(e));if(s.length>0)return Ot(mt("Source requirement(s)",s.join(", ")));const o=i.filter(e=>{const t=a.get(e);return"requirement"!==t.type||Yn.has(t.data?.req_type)});if(o.length>0)return Ot(ut(`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,Ln[n]),s=e.title??("hara"===n?"New HARA":"New DFMEA"),o=e.revision??"1.0",d=$n[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:Fn[n],revision:o},metadata:{created_at:c,created_by:r,updated_at:c,updated_by:r}},{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:r,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null});if(m)throw new Error(m.message);const p=[],u=[];for(const s of i){const i=await ta(t,e.project_id,Nn[n]),o={id:i,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:r,updated_at:c,updated_by:r}},{error:l}=await t.rpc("save_item_with_revision",{p_item_id:i,p_project_id:e.project_id,p_type:"requirement",p_title:"",p_data:o,p_user_id:r,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:i,p_to_id:a,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"});m&&(process.stderr.write(`[atoms-mcp] Warning: analysis row parent link sync failed for ${i}: ${m.message}\n`),u.push({row_id:i,source_req:s,message:m.message})),await t.from("change_history").insert({item_id:i,project_id:e.project_id,changed_by:r,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:i,source_req:s})}return await t.from("change_history").insert({item_id:a,project_id:e.project_id,changed_by:r,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`)}),At(dt({id:a,subtype:n,title:Et(s),revision:o,rows:p,...u.length>0?{link_warnings:u,warning:`${u.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 Ot(xt(e))}}async function aa(e){try{const t=await ge(),r=ve();try{await Se(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}const i=await qt(t,e.project_id,e.row_id);if(!i)return Ot(mt("Analysis row",e.row_id));const n=i.data,a=ea(n?.req_type);if(!a)return Ot(ut(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const s=new Set([...Pn[a],"effect"]);"hara"===a&&s.add("title");const o=Object.keys(e.fields??{});if(0===o.length)return Ot(ut("fields must contain at least one key"));const d=o.filter(e=>!s.has(e));if(d.length>0)return Ot(ut(`Unknown field(s) for ${a}: ${d.join(", ")}. Allowed: ${[...s].sort().join(", ")}`));const c=Mn[a],l={};for(const t of o){const r=e.fields[t];if(c[t]){const e="number"==typeof r&&"dfmea"===a?String(r):r;if("string"!=typeof e||!c[t].includes(e))return Ot(ut(`Invalid ${t} value ${JSON.stringify(r)} for ${a}. Allowed: ${c[t].join(", ")}`));l[t]=e}else{if("string"!=typeof r)return Ot(ut(`Field '${t}' must be a string`));l[t]=r}}const m=n?.analysis_props??null,p=ia(n);p.analysis_props&&"object"==typeof p.analysis_props||(p.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const u=p.analysis_props;u.field_source&&"object"==typeof u.field_source||(u.field_source={});let _=i.title;for(const[e,t]of Object.entries(l))"effect"===e?p.body=t:"title"===e?(p.title=t,_=t):(u[e]=t,"failure_mode"===e&&"dfmea"===a&&(p.title=t,_=t)),u.field_source[e]="mcp";const f=(new Date).toISOString();p.metadata={...p.metadata??{},updated_at:f,updated_by:r};const{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:i.id,p_project_id:e.project_id,p_type:i.type,p_title:_,p_data:p,p_user_id:r,p_event_source:"mcp",p_event_session_id:ja()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});if(g)throw new Error(g.message);if(!h)return Ot(lt(`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:i.id,project_id:e.project_id,changed_by:r,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,u),w=[];if("hara"===a){const n=Jn("hara",m),a=ra(p);if(a.length>0&&y!==Un&&y!==n)for(const n of a){const a=await qt(t,e.project_id,n);if(!a)continue;const s=a.data;if(s?.asil===y&&s?.asil_source===i.id)continue;const o=s?.asil??null,d=s?.asil_source??null,c=ia(s);c.asil=y,c.asil_source=i.id,c.metadata={...c.metadata??{},updated_at:f,updated_by:r};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:r,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:r,event_type:"updated",old_data:{asil:o,asil_source:d},new_data:{asil:y,asil_source:i.id},actor:Sa(),session_id:ja(),reason:`ASIL propagated from ${i.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 At(dt({row_id:i.id,subtype:a,written_fields:Object.keys(l),computed_level:y,...w.length>0?{asil_propagated_to:w}:{}}))}catch(e){return Ot(xt(e))}}async function sa(e,t,r){const i=await qt(e,t,r);if(!i)return{ok:!1,result:Ot(mt("Analysis",r))};if("analysis"!==i.type)return{ok:!1,result:Ot(ut(`Item ${r} is not an analysis (type='${i.type}')`))};const n=i.data,a=ea("hara"===n?.analysis?.subtype?"safety-goal":"dfmea"===n?.analysis?.subtype?"failure-mode":null);if(!a)return{ok:!1,result:Ot(ut(`Analysis ${r} is missing a valid analysis.subtype`))};const s=$n[a],o=Array.isArray(n?.relationships?.children)?n.relationships.children.filter(e=>"string"==typeof e):[];let d=[];if(o.length>0){const{data:r,error:i}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",o);if(i)throw new Error(i.message);const n=new Map((r??[]).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 ra(e.data))c.add(t)}const l=new Map;if(c.size>0){const{data:r,error:i}=await e.from("items").select("id, updated_at").eq("project_id",t).is("deleted_at",null).in("id",[...c]);if(i)throw new Error(i.message);for(const e of r??[])l.set(e.id,e.updated_at)}const m=d.map(e=>{const t=e.data?.analysis_props??{},r=ra(e.data).filter(e=>l.has(e)),i=r.length>0,n=Jn(a,t),s=function(e,t,r){if(r)return null;if("hara"===e){const e=Vn(t);return"QM"!==e&&e!==Un?`asil ${e} unmitigated`:null}const i=parseInt(Bn(t),10),n=parseInt(t?.severity||"",10);return!Number.isNaN(i)&&i>=100?"rpn >= 100":!Number.isNaN(n)&&n>=9?"severity >= 9":null}(a,t,i),o={id:e.id,title:Et("string"==typeof e.title?e.title:""),source_req:"string"==typeof t.source_req?t.source_req:null,effect:Et("string"==typeof e.data?.body?e.data.body:""),computed_level:n,is_gap:null!==s,gap_rule:s,is_critical:Qn(a,t,i),is_stale:Gn(t,r,e=>l.get(e)??null),mitigated_by:r,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 Pn[a]){const r=t[e]??null;o[e]=Kn.has(e)&&"string"==typeof r?Et(r):r}return o});return{ok:!0,analysis:{id:i.id,title:Et("string"==typeof i.title?i.title:""),subtype:a,scheme:"string"==typeof n?.analysis?.scheme?n.analysis.scheme:Fn[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 ge(),r=await sa(t,e.project_id,e.analysis_id);return r.ok?At(dt({analysis:r.analysis,rows:r.rows,counts:r.counts})):r.result}catch(e){return Ot(xt(e))}}async function da(e){try{const n=await ge(),a=ve();try{await Se(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ot(pt("Viewer"));throw e}if(e.row_id===e.req_id)return Ot(ut("row_id and req_id must be different items"));const s=await qt(n,e.project_id,e.row_id);if(!s)return Ot(mt("Analysis row",e.row_id));const o=s.data,d=ea(o?.req_type);if(!d)return Ot(ut(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const c=await qt(n,e.project_id,e.req_id);if(!c)return Ot(mt("Requirement",e.req_id));const l=c.data;if("requirement"!==c.type||Yn.has(l?.req_type))return Ot(ut(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));if("dfmea"===d&&!e.role)return Ot(ut(`role is required for dfmea mitigation links. Choose one of: ${zn.join(", ")}`));if("hara"===d&&e.role)return Ot(ut("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 Ot((r=m,{...lt(`ASIL conflict: the target requirement already carries asil '${t=n}' but ${i=s.id} computes '${r}'.`,["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:r,source_row:i,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:u}=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(u)throw new Error(u.message);let _;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 qt(n,e.project_id,e.req_id);if(t){const r=t.data,i=r?.asil??null,o=r?.asil_source??null,d=ia(r);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:i,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 '${i??"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`)}),_=m}}return At(dt({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:p,..._?{asil_written:_}:{}}))}catch(e){return Ot(xt(e))}var t,r,i}async function ca(e){try{const t=await ge(),r=await sa(t,e.project_id,e.analysis_id);if(!r.ok)return r.result;const i=r.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 At(dt({analysis_id:r.analysis.id,subtype:r.analysis.subtype,gaps:i,count:i.length}))}catch(e){return Ot(xt(e))}}E(Xn,{createAnalysisHandler:()=>na,fillRowHandler:()=>aa,getAnalysisHandler:()=>oa,getGapsHandler:()=>ca,linkMitigationHandler:()=>da});var la,ma,pa,ua,_a,fa,ha,ga,ya=I({"src/tools/analysis.ts"(){Ee(),Wt(),ka(),Dt(),Zn(),Yn=new Set(["safety-goal","failure-mode"]),Kn=new Set(["failure_mode","cause","operating_scenario","safe_state","ftti","rationale"])}}),wa={};function ba(e){F(e.toolName)&&function(e,t){const r=`ui://${t.toolName}/${t.htmlFile}`,i=function(e,t){const r=s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("index.cjs",document.baseURI).href),i=j.default.dirname(r);return j.default.resolve(i,"apps","src","apps",e,t)}(t.appName,t.htmlFile),n=[...Rt.resourceDomains,...t.extraResourceDomains??[]];d.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:r}}},t.handler),d.registerAppResource(e,`${t.title} UI`,r,{mimeType:d.RESOURCE_MIME_TYPE},async()=>{const e=await v.default.readFile(i,"utf-8");return{contents:[{uri:r,mimeType:d.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:n}}}}]}})}(ua,e)}function va(e,t){return async r=>{const i=R(P(),e);if(!i.allowed)return Ot(lt(`Tool ${e} is blocked by org policy.`,[H(i.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=Be();if(!t)return;if("object"!=typeof e||null===e)return;const r=e.project_id;if("string"==typeof r&&r!==t)throw new Fe(t,r)}(r)}catch(e){if(e instanceof Fe)return Ot(ht(e.expectedProjectId));throw e}{const e=P(),t=r?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return Ot(lt("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 ge(),n=ve()}catch{return t(r)}const s=await async function(e,t){const r=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Pe,i=new Date,n=new Date(i.getTime()-$e);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)>=r){const{data:r,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=(r?new Date(r.requested_at).getTime():i.getTime())+$e-i.getTime();return{allowed:!1,retryAfterSeconds:Math.max(1,Math.ceil(s/1e3))}}t.from("mcp_rate_limits").insert({user_id:e,requested_at:i.toISOString()}).then(({error:e})=>{e&&process.stderr.write(`[rate-limiter] insert failed: ${e.message}\n`)});const o=new Date(i.getTime()-2*$e);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 Ot(gt(s.retryAfterSeconds));if("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN){const e=r?.project_id;if("string"==typeof e)try{const{requireWriteAccess:t}=await Promise.resolve().then(()=>(Ee(),he));await t(a,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(Dt(),at));return Ot(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(r),i=e;if(!0===i?.isError){c="error";const e=i?.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:r,status:c,duration_ms:o(),error_msg:d,project_id:r.project_id,session_id:fa,client_name:ha};try{!function(e,t,r){const i=Me(r.params);e.from("mcp_audit_log").insert({user_id:t,tool_name:r.tool_name,params:i,status:r.status,duration_ms:r.duration_ms,error_msg:r.error_msg??null,project_id:r.project_id??null,session_id:r.session_id??null,client_name:r.client_name??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await ge(),n,t)}catch{}}}}function ja(){return fa}function Sa(){return ga}function xa(){return ha}E(wa,{ATOMS_MCP_SERVER_VERSION:()=>pa,getMcpActor:()=>Sa,getMcpClientName:()=>xa,getMcpSessionId:()=>ja,server:()=>ua});var ka=I({"src/server.ts"(){We(),Ve(),B(),Qe(),$(),T(),rt(),it(),Ee(),Dt(),Ht(),la=l.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("index.cjs",document.baseURI).href),ma=la("../package.json"),pa=ma.version,ua=new c.McpServer({name:"atoms-mcp-server",version:pa}),_a=(e,t,r)=>{if(F(e))return ua.registerTool(e,t,r)},fa=a.randomUUID(),ha=Ge(process.env.ATOMS_CLIENT_NAME),ga=function(){const e=Ge(ha);return"cursor"===e?"mcp_cursor":"copilot"===e?"mcp_copilot":"mcp_claude"}(),_a("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(()=>(ie(),J)),r=await e();if(!r)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(r))try{const{getValidToken:e}=await Promise.resolve().then(()=>(fe(),oe)),{email:t}=await e(),{invalidateClient:r}=await Promise.resolve().then(()=>(Ee(),he));return r(),{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:r.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:r.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)}]}}}),_a("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(()=>(Jt(),Vt));return e()})),_a("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:o.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:o.z.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:o.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:o.z.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(()=>(Yt(),Qt));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:o.z.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:o.z.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(()=>(Xt(),Kt));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),query:o.z.string().min(1).max(1e3).describe("Search text"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),asset:o.z.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:o.z.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(()=>(rr(),er));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),query:o.z.string().min(1).max(1e3).describe("Natural-language concept query"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:o.z.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(()=>(ar(),ir));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:o.z.string().uuid().describe("UUID of the project"),domain:o.z.string().max(64).optional().describe("Filter by domain tag"),level:o.z.string().max(32).optional().describe("Filter by level"),baseline_id:o.z.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:o.z.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(()=>(dr(),sr));return t(e)})}),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID"),limit:o.z.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(()=>(mr(),cr));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:o.z.string().uuid().describe("UUID of the project"),root_item_id:o.z.string().max(20).optional().describe("Root item ID to start from"),depth:o.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:o.z.boolean().default(!0).describe("Include test case links"),baseline_id:o.z.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:o.z.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(()=>(wr(),gr));return t(e)})}),_a("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:o.z.string().uuid().describe("UUID of the target project"),type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),body:o.z.string().max(5e4).optional().describe("Rich text body"),summary:o.z.string().max(2e3).optional().describe("Brief summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("Domain tags"),level:o.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:o.z.array(o.z.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional().describe("Project-field values keyed by defined field name"),echo:o.z.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(()=>(Yr(),Qr));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).optional().describe("Item ID (single form)"),title:o.z.string().min(1).max(500).optional().describe("New title"),body:o.z.string().max(5e4).optional().describe("New body"),summary:o.z.string().max(2e3).optional().describe("New summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("New domain tags"),level:o.z.string().max(32).optional().describe("New level"),status:o.z.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status"),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),expected_updated_at:Ye.optional().describe("metadata.updated_at value from atoms_get_item; rejects stale writes"),echo:o.z.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:o.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:o.z.array(o.z.object({item_id:o.z.string().min(1).max(20),title:o.z.string().min(1).max(500).optional(),body:o.z.string().max(5e4).optional(),summary:o.z.string().max(2e3).optional(),domains:o.z.array(o.z.string().max(64)).max(20).optional(),level:o.z.string().max(32).optional(),status:o.z.enum(["passed","failed","blocked","not-run"]).optional(),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional(),expected_updated_at:Ye.optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:o.z.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:o.z.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(()=>(ni(),ei));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:o.z.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(()=>(_i(),pi));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.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(()=>(gi(),fi));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),from_id:o.z.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:o.z.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:o.z.enum(["parent","child","related","verifies","verified_by"]).optional().describe("Relationship type"),action:o.z.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:Ye.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:Ye.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:o.z.boolean().optional().describe("false → lean response"),reason:o.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:o.z.array(o.z.object({action:o.z.enum(["add","remove"]),from_id:o.z.string().min(1).max(20),to_id:o.z.string().min(1).max(20),type:o.z.enum(["parent","child","related","verifies","verified_by"]),expected_from_updated_at:Ye.optional(),expected_to_updated_at:Ye.optional()})).optional().describe("Array form: batch relationship ops. Always atomic with DAG cycle detection."),idempotency_key:o.z.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(()=>(bi(),yi));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:o.z.string().uuid().describe("UUID of the target project"),items:o.z.array(o.z.object({type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),body:o.z.string().max(5e4).optional().describe("Rich text body"),summary:o.z.string().max(2e3).optional().describe("Brief summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("Domain tags"),level:o.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:o.z.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)"),confirmation_token:o.z.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(()=>(ki(),ji));return t(e)})}),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:o.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:o.z.string().max(1e3).optional().describe("Reason or comment for this result"),asset:o.z.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(()=>(Ai(),Ii));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:o.z.array(o.z.object({asset:o.z.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:o.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:o.z.string().max(500).optional().describe("Run note"),date:o.z.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(()=>(zi(),Oi));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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Starting item ID"),direction:o.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:o.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:o.z.array(o.z.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(()=>($i(),Mi));return t(e)})}),_a("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:o.z.string().uuid().describe("UUID of the project"),include_archived:o.z.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(()=>(Fi(),Ni));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:o.z.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(()=>(Xi(),Wi));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).max(64).describe("Variable name"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:o.z.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(()=>(Xi(),Wi));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).max(64).describe("Variable name"),value:o.z.string().max(500).optional().describe("New value"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.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(()=>(Xi(),Wi));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).optional().describe("Variable name (single form)"),value:o.z.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description"),echo:o.z.boolean().optional().describe("false → lean response (default true)"),variables:o.z.array(o.z.object({name:o.z.string().min(1).max(64).describe("Variable name"),value:o.z.string().min(1).max(500).describe("Initial value"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:o.z.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(()=>(Xi(),Wi));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Variable name to delete"),force:o.z.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:o.z.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(()=>(Xi(),Wi));return t(e)})),_a("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:o.z.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)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.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)})),_a("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:o.z.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(()=>(Or(),br));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.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(()=>(Or(),br));return t(e)})),_a("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:o.z.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(()=>(Jr(),Dr));return t(e)})),_a("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 - scope (string, optional): project (default) or organization (org admin only)\n\nReturns:\n { field: { name, type, options }, message }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:o.z.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:o.z.array(o.z.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:o.z.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},va("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(Jr(),Dr));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.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(()=>(Jr(),Dr));return t(e)})),_a("atoms_reorder_fields",{title:"Reorder Project Fields",description:"Reorder project field definitions. Definition order drives the Column Picker listing and a fresh user's Matrix column order.\n\nOrdering only: no definition is added, dropped, renamed, or retyped, and no item value moves. Use this instead of deleting and recreating definitions to change their order.\n\nArgs:\n - project_id (string, UUID): Project containing the fields\n - names (string[]): Every existing field name exactly once, in the order you want them. A list that is not a permutation of the current names is refused, not partially applied.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),names:o.z.array(o.z.string().min(1).max(60)).describe("Every existing field name exactly once, in the desired order")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},va("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(Jr(),Dr));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Current domain name"),new_name:o.z.string().min(1).max(64).describe("New domain name"),dry_run:o.z.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)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Domain name to delete"),force:o.z.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:o.z.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:o.z.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:o.z.string().uuid().describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:o.z.string().max(64).optional().describe("Filter by domain tag"),level:o.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:o.z.string().max(1e3).optional().describe("Full-text search query"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:o.z.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(),un));return t(e)})}),_a("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:o.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:o.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:o.z.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)})),_a("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:o.z.string().uuid().describe("UUID of the project"),limit:o.z.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:o.z.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(()=>(Wn(),xn));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:o.z.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(()=>(Wn(),xn));return t(e)})),_a("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:o.z.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(()=>(Wn(),xn));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:o.z.string().uuid().describe("UUID of the second (newer) baseline"),detail:o.z.boolean().default(!1).describe("Include per-item field-level diffs (default false)"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:o.z.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(()=>(Wn(),xn));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the baseline to restore from"),confirm:o.z.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(()=>(Wn(),xn));return t(e)})),_a("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:o.z.string().uuid().describe("UUID of the target project"),subtype:o.z.enum(["hara","dfmea"]).describe("Analysis subtype"),title:o.z.string().min(1).max(500).optional().describe("Analysis title"),source_req_ids:o.z.array(o.z.string().min(1).max(20)).max(50).optional().describe("Requirement IDs to seed rows from (0-50)"),revision:o.z.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)})),_a("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:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),fields:o.z.record(o.z.string().max(64),o.z.union([o.z.string().max(5e4),o.z.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)})),_a("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:o.z.string().uuid().describe("UUID of the project"),analysis_id:o.z.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)})),_a("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:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:o.z.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:o.z.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows; must be omitted for hara rows."),override:o.z.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)})),_a("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:o.z.string().uuid().describe("UUID of the project"),analysis_id:o.z.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)}))}});B(),$(),Ee(),M();var Ia=l.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("index.cjs",document.baseURI).href)("../package.json"),Ea=process.argv.slice(2)[0];(async function(){switch(Ea){case"login":{const{login:e}=await Promise.resolve().then(()=>(qe(),Ae));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(()=>(fe(),oe));try{const{email:t,user_id:r}=await e();process.stderr.write(`\n [32m✓[0m Logged in as ${t}\n [90mUser ID: ${r}[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(()=>(ie(),J));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(()=>(fe(),oe)),{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(()=>(qe(),Ae)),{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 ge(),r=ve(),i=await async function(e,t){const r=process.env.ATOMS_MCP_ORG_ID?.trim();if(r)return r;const{data:i,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):i?.org_id??null}(t,r),n=await async function(e,t,r){if(!r)return{role:null,is_member:!1,effective:C};const{data:i,error:n}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:r});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:U}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:C};const t=e,r="string"==typeof t.role?t.role:null,i=!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:r,is_member:i,effective:{read_only:s(n.read_only,C.read_only),lockdown:s(n.lockdown,C.lockdown),block_destructive:s(n.block_destructive,C.block_destructive),block_bulk_import:s(n.block_bulk_import,C.block_bulk_import),cross_project_browse:s(n.cross_project_browse,C.cross_project_browse),allowed_toolsets:a(n.allowed_toolsets,C.allowed_toolsets),forbidden_tools:a(n.forbidden_tools,C.forbidden_tools),project_scope:d,require_confirmation_for:a(n.require_confirmation_for,C.require_confirmation_for)}}}(i)}(t,r,i);e={effective:n.effective,role:n.role,org_id:i},z=e.effective,q=e.org_id,n.is_member&&i?process.stderr.write(`[atoms-mcp] Org policy loaded: org=${i.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=L(),t=N(),r=[];r.push(e?"read-only":"read+write"),null===t?r.push("all toolsets"):(r.push(`toolsets=${[...t.allowed].sort().join(",")||"(none — only always-on tools)"}`),t.unknown.length>0&&r.push(`unknown=${t.unknown.join(",")}`));const i=process.env.ATOMS_MCP_PROJECT_ID?.trim();return i&&r.push(`project_scope=${i.slice(0,8)}…`),("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN)&&r.push("lockdown=on"),r.join(" | ")}()}\n`);const{server:t}=await Promise.resolve().then(()=>(ka(),wa)),r=new m.StdioServerTransport;await t.connect(r),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
|
+
var e=require("fs/promises"),t=require("os"),r=require("path"),i=require("@supabase/supabase-js"),n=require("http"),a=require("crypto"),s=require("url"),o=require("zod"),d=require("@modelcontextprotocol/ext-apps/server"),c=require("@modelcontextprotocol/sdk/server/mcp.js"),l=require("module"),m=require("@modelcontextprotocol/sdk/server/stdio.js"),p="undefined"!=typeof document?document.currentScript:null;function u(e){return e&&e.__esModule?e:{default:e}}var _,f,h,g,y,w,b,v=u(e),j=u(r),S=u(a),x=Object.defineProperty,k=Object.getOwnPropertyNames,I=(e,t,r)=>function(){if(r)throw r[0];try{return e&&(t=(0,e[k(e)[0]])(e=0)),t}catch(e){throw r=[e],e}},E=(e,t)=>{for(var r in t)x(e,r,{get:t[r],enumerable:!0})};function A(e){return b.get(e)}var O=I({"src/core/tool-catalog.ts"(){_=new Set(["atoms_status","atoms_list_projects"]),f=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_reorder_fields","atoms_create_baseline","atoms_lock_baseline","atoms_restore_baseline","atoms_create_analysis","atoms_fill_row","atoms_link_mitigation"]),h=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_field","atoms_restore_baseline"]),g=new Set(["atoms_bulk_import"]),y={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","atoms_reorder_fields"],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"]},w=Object.keys(y),b=new Map;for(const[e,t]of Object.entries(y))for(const r of t)b.set(r,e)}});function R(e,t){if(_.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&&f.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&h.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&g.has(t))return{allowed:!1,reason:"block_bulk_import"};const r=A(t);return void 0===r||e.allowed_toolsets.includes(r)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function D(e,t){return R(e,t).allowed}function H(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 C,U,z,T,q=I({"src/core/policy.ts"(){O()}}),M=I({"src/core/types.ts"(){C={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:[]},U={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 P(){return z}var $=I({"src/middleware/session-policy.ts"(){M(),z=C,T=null}});function N(){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 r=new Set,i=[];for(const e of t)w.includes(e)?r.add(e):i.push(e);return{allowed:r,unknown:i}}function L(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function F(e){if(L()&&f.has(e))return!1;if(_.has(e))return!0;const t=N();if(null===t)return D(P(),e);const r=A(e);return!!r&&!!t.allowed.has(r)&&D(P(),e)}var W,V,B=I({"src/middleware/tool-registry.ts"(){O(),q(),$()}}),J={};async function Q(){try{const t=await e.readFile(V,"utf-8"),r=JSON.parse(t);return r.access_token&&r.refresh_token?r:null}catch{return null}}async function G(t){await e.mkdir(W,{recursive:!0,mode:448}),await e.writeFile(V,JSON.stringify(t,null,2),{mode:384})}async function Y(){const e=await Q();return!!e&&e.expires_at>Date.now()+6e4}function K(e){return e.expires_at>Date.now()+6e4}async function Z(){try{await e.unlink(V)}catch{}}function X(){return V}E(J,{clearCredentials:()=>Z,getCredentialsPath:()=>X,hasValidCredentials:()=>Y,isTokenValid:()=>K,readCredentials:()=>Q,writeCredentials:()=>G});var ee,te,re,ie=I({"src/auth/token-store.ts"(){W=r.join(t.homedir(),".atoms"),V=r.join(W,"credentials.json")}}),ne={};function ae(e){return e.trim().replace(/\/+$/,"")}E(ne,{ATOMS_APP_URL:()=>re,ATOMS_SUPABASE_ANON_KEY:()=>te,ATOMS_SUPABASE_URL:()=>ee,resolveUrl:()=>ae});var se=I({"src/config.ts"(){ee=ae(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),te=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",re=process.env.ATOMS_APP_URL??"https://atoms.tech"}}),oe={};async function de(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=le(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await Q();if(t&&t.expires_at>Date.now()+6e4){const e=le(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}return null}async function ce(){const e=await de();if(e)return e;const t=await Q();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' to connect your ATOMS account.");process.stderr.write("[atoms-mcp] Refreshing access token...\n");const r=i.createClient(ee,te);let n=await r.auth.refreshSession({refresh_token:t.refresh_token});if(n.error||!n.data.session){const e=await Q();if(e&&e.expires_at>Date.now()+6e4){const t=le(e.access_token);return{access_token:e.access_token,refresh_token:e.refresh_token,user_id:t.sub,email:t.email??e.user_email??""}}e&&e.refresh_token&&e.refresh_token!==t.refresh_token&&(process.stderr.write("[atoms-mcp] Refresh token was rotated by another session; retrying with the latest...\n"),n=await r.auth.refreshSession({refresh_token:e.refresh_token}))}if(n.error||!n.data.session){const e=n.error?[n.error.status,n.error.message].filter(Boolean).join(" ").trim():"no session returned";throw new Error(`Token refresh failed (${e}). Your saved ATOMS session is no longer valid — re-run 'npx @atoms-tech/atoms-mcp login'.`)}const a=n.data.session;return await G({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 le(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),i=JSON.parse(Buffer.from(r,"base64").toString("utf-8"));if(!i.sub)throw new Error("JWT missing 'sub' claim");return i}E(oe,{getValidToken:()=>ce,readValidToken:()=>de});var me,pe,ue,_e,fe,he=I({"src/auth/refresh.ts"(){ie(),se()}}),ge={};async function ye(){if(me)try{const e=await Q();e&&e.expires_at>fe&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),we())}catch{}if(me&&_e>Date.now()+6e4)return me;me&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:r}=await ce(),n=e.split(".");if(3===n.length)try{const e=JSON.parse(Buffer.from(n[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());_e=1e3*(e.exp??0)}catch{_e=Date.now()+36e5}try{const e=await Q();fe=e?.expires_at??0}catch{fe=0}const a=i.createClient(ee,te,{global:{headers:{Authorization:`Bearer ${e}`}}});return pe=t,ue=r,me=a}function we(){me=null,pe=null,ue=null,_e=0,fe=0}function be(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const r=e;t="string"==typeof r.message?r.message:"string"==typeof r.code?r.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 ve(e){try{return await e()}catch(t){if(!be(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),we(),await e()}}function je(){if(!pe)throw new Error("Not authenticated. Call getClient() first.");return pe}function Se(){return ue??""}async function xe(e,t){const r=je(),{data:i,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n||!i)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",r).eq("org_id",i.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 ke(e,t){const r=je(),{data:i,error:n}=await e.from("projects").select("org_id, created_by").eq("id",t).maybeSingle();if(n||!i)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",r).eq("org_id",i.org_id).maybeSingle();if(s||!a)throw new Error("Not a member of this project's organization");if("admin"===a.role)return"admin";if(i.created_by===r)return"owner";throw new Error("PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED")}E(ge,{getClient:()=>ye,getUserEmail:()=>Se,getUserId:()=>je,invalidateClient:()=>we,isJwtExpiredError:()=>be,requireProjectFieldDefinitionAccess:()=>ke,requireWriteAccess:()=>xe,withJwtRetry:()=>ve});var Ie,Ee,Ae=I({"src/db/client.ts"(){he(),ie(),se(),me=null,pe=null,ue=null,_e=0,fe=0}}),Oe={};async function Re(){const e=a.randomBytes(32).toString("base64url"),t=a.createHash("sha256").update(e).digest("base64url"),r=`http://localhost:${Ie}${Ee}`,i=new s.URL(`${re}/auth/mcp-consent`);return i.searchParams.set("redirect_uri",r),i.searchParams.set("code_challenge",t),i.searchParams.set("code_challenge_method","S256"),new Promise((t,r)=>{let a;function o(){clearTimeout(a)}const d=n.createServer(async(i,n)=>{const a=new s.URL(i.url??"/",`http://localhost:${Ie}`);if(a.pathname!==Ee)return n.writeHead(404),void n.end("Not found");try{if("access_denied"===a.searchParams.get("error"))return n.writeHead(200,{"Content-Type":"text/html"}),n.end(He("Authorization was cancelled.")),o(),d.close(),void r(new Error("Authorization cancelled by user."));const i=a.searchParams.get("code");if(i){const a=await fetch(`${ee}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:te},body:JSON.stringify({auth_code:i,code_verifier:e})}),s=await a.json();if(!a.ok||!s.access_token){const e=s.error_description??s.msg??"Unknown error";return n.writeHead(200,{"Content-Type":"text/html"}),n.end(He(`Code exchange failed: ${e}`)),o(),d.close(),void r(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(s.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(ee,te,{global:{headers:{Authorization:`Bearer ${s.access_token}`}}}),{data:p,error:u}=await m.from("org_members").select("org_id").limit(1);return u||!p||0===p.length?(n.writeHead(200,{"Content-Type":"text/html"}),n.end(He('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.')),o(),d.close(),void r(new Error("No ATOMS account found. Sign up at atoms.tech first."))):s.refresh_token?(await G({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:Date.now()+1e3*(s.expires_in??3600),user_email:c}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(De(c)),o(),d.close(),void t({email:c})):(n.writeHead(200,{"Content-Type":"text/html"}),n.end(He("Sign-in succeeded but no refresh token was issued, so the session would expire within the hour. This usually points to a Supabase Auth setting (refresh-token rotation or session policy). Please contact ATOMS support.")),o(),d.close(),void r(new Error("No refresh token issued by Supabase — cannot persist a durable session.")))}const s=a.searchParams.get("access_token"),c=a.searchParams.get("refresh_token"),l=parseInt(a.searchParams.get("expires_in")??"3600",10);s&&c?(await G({access_token:s,refresh_token:c,expires_at:Date.now()+1e3*l}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(De("authenticated")),o(),d.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"),o(),d.close(),r(e)}});d.on("request",async(e,i)=>{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 G({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!0})),o(),d.close(),t({email:e.user_email??"authenticated"})}catch(e){i.writeHead(500),i.end("Failed to store credentials"),o(),d.close(),r(e)}})}}),d.listen(Ie,"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${i.toString()}\n\n`);try{const{default:e}=await import("open");await e(i.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),a=setTimeout(()=>{d.close(),r(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function De(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 He(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>`}E(Oe,{login:()=>Re});var Ce,Ue,ze,Te,qe,Me,Pe,$e=I({"src/auth/login.ts"(){ie(),se(),Ie=19275,Ee="/callback"}}),Ne={};async function Le(){try{await e.mkdir(Ce,{recursive:!0,mode:448});const t=await e.open(Ue,"wx");try{await t.writeFile(`${process.pid} ${Date.now()}`)}finally{await t.close()}return!0}catch(e){if("EEXIST"===e.code)return!1;throw e}}async function Fe(){try{await e.unlink(Ue)}catch{}}async function We(){try{const t=await e.stat(Ue);return Date.now()-t.mtimeMs>ze}catch{return!1}}async function Ve(e,t,r=Pe){const i=r.now()+Te;for(;;){if(await r.tryAcquire())try{try{return await e()}catch{}return await t()}finally{await r.release()}try{return await e()}catch{}if(await r.isStale())await r.release();else{if(r.now()>i)return await t();await r.wait(qe)}}}E(Ne,{runExclusiveAuth:()=>Ve});var Be,Je,Qe,Ge,Ye=I({"src/auth/lock.ts"(){Ce=r.join(t.homedir(),".atoms"),Ue=r.join(Ce,".auth.lock"),ze=7e4,Te=12e4,qe=300,Me=e=>new Promise(t=>setTimeout(t,e)),Pe={now:Date.now,wait:Me,tryAcquire:Le,release:Fe,isStale:We}}});function Ke(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Qe)if(t.test(e.trim()))return"[redacted]";return e.length>Ge?e.slice(0,Ge)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Ke(e,t+1));if(null!==e&&"object"==typeof e){const r={};for(const[i,n]of Object.entries(e)){const e=i.toLowerCase();Be.has(e)?r[i]="[redacted]":Je.has(e)?r[i]="string"==typeof n?"[content]":Ke(n,t+1):r[i]=Ke(n,t+1)}return r}return e}function Ze(e){return Ke(e)}var Xe,et,tt,rt,it,nt=I({"src/middleware/audit.ts"(){Be=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),Je=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Qe=[/^[^\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_-]+$/],Ge=200}}),at=I({"src/middleware/rate-limiter.ts"(){Xe=60,et=6e4}});function st(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?tt.test(e)?e:(rt||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),rt=!0),null):null}var ot,dt=I({"src/middleware/project-scope.ts"(){tt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,rt=!1,it=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 ct(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")?ot:t:ot}var lt,mt,pt,ut,_t,ft,ht=I({"src/core/client-identity.ts"(){ot="claude_desktop"}}),gt=I({"src/core/timestamps.ts"(){lt=o.z.string().datetime({offset:!0})}}),yt=I({"src/core/errors.ts"(){}}),wt={};function bt(e,t=pt){if("string"!=typeof e)return"";const r=e.replace(_t,"").replace(ft,"");return r.length<=t?r:r.slice(0,t)+"..."}function vt(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function jt(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function St(e,t,r){return{total_count:e,limit:t,offset:r,has_more:r+t<e}}function xt(e,t){return{status:"error",message:e,next_steps:t}}function kt(e,t){return xt(`${e} '${bt(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function It(e){return xt(`${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 Et(e){return xt(`Validation error: ${bt(e,ut)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function At(){return xt("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 Ot(){return xt("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 Rt(e){return xt("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 Dt(e){return xt("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 Ht(e){return xt(`Parse error: ${bt(e,ut)}`,["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 Ct(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function Ut(){return xt("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 zt(){return xt("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 Tt(){return xt("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 qt(){return xt("Item save rejected because this item is in Trash.",["Restore the item before changing it","Do not retry the same save while the item remains in Trash"])}function Mt(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e),r=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return/not authenticated/i.test(t)?At():function(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const r=e;t="string"==typeof r.message?r.message:"string"==typeof r.code?r.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)?Ot():/rate.?limit|too many requests|429/i.test(t)?Dt():Ct(t)?Ut():/soft_deleted_item_write/i.test(t)?qt():/save_temporarily_unavailable/i.test(t)?Tt():"55P03"===r||"57014"===r||/item_save_busy|statement timeout|request timeout|upstream request timeout/i.test(t)?zt():"42501"===r&&/org_project_field_admin_required/i.test(t)?It("Org admin"):"42501"===r&&/project_field/i.test(t)?It("Project admin or owner"):"P0002"===r&&/project_field/i.test(t)?xt("Project field not found.",["Refresh the field list and retry with an existing field name"]):["22023","23505","23514"].includes(r)&&/project_field/i.test(t)?Et(t.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?Ht(t):$t(t)}function Pt(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??""),r=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return["40001","PT409","55P03","57014"].includes(r)||/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 $t(e){return/row.level security|permission denied for/i.test(e)?xt("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"]):xt(`Database error: ${bt(e,ut)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function Nt(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function Lt(e){const t=JSON.stringify(e,null,2);if(t.length>mt&&"success"===e.status&&Array.isArray(e.data)){const t=Math.max(1,Math.floor(e.data.length/2)),r={...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(r,null,2)}],structuredContent:r}}return{content:[{type:"text",text:t}],structuredContent:e}}function Ft(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}E(wt,{CHARACTER_LIMIT:()=>mt,accessDeniedError:()=>It,authError:()=>At,classifyError:()=>Mt,dbError:()=>$t,errorResponse:()=>xt,formatErrorResult:()=>Ft,formatToolResult:()=>Lt,isItemSaveStopError:()=>Pt,isStaleWriteErrorMessage:()=>Ct,jwtExpiredError:()=>Ot,notFoundError:()=>kt,paginationMeta:()=>St,parseError:()=>Ht,rateLimitError:()=>Dt,sanitizeForEcho:()=>bt,sanitizeTagOrLevel:()=>vt,saveBusyError:()=>zt,saveUnavailableError:()=>Tt,scopeError:()=>Rt,softDeletedItemError:()=>qt,staleWriteError:()=>Ut,success:()=>jt,validationError:()=>Et,wrapUserContent:()=>Nt});var Wt,Vt=I({"src/tools/_base.ts"(){yt(),mt=25e3,pt=50,ut=200,_t=new RegExp("[\\u0000-\\u001F\\u007F]","g"),ft=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g")}});var Bt=I({"src/apps/register.ts"(){Wt={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function Jt(e){return function(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(`*${t=e,t.replace(/[\\%_*]/g,e=>`\\${e}`)}*`);var t}var Qt=I({"src/core/postgrest.ts"(){}});async function Gt(e,t,r){let i=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0});r.type&&(i=i.eq("type",r.type)),r.domain&&(i=i.filter("data->tags->domains","cs",JSON.stringify([r.domain]))),r.level&&(i=i.filter("data->tags->>level","eq",r.level)),i=i.range(r.offset,r.offset+r.limit-1);const{data:n,error:a,count:s}=await i;if(a)throw new Error(a.message);return{items:n??[],totalCount:s??0}}async function Yt(e,t,r){const{data:i,error:n}=await e.from("items").select("*").eq("id",r).eq("project_id",t).is("deleted_at",null).maybeSingle();if(n)throw new Error(n.message);return i}async function Kt(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:r,error:i}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",t.baseline_id).maybeSingle();if(i)throw new Error(`resolveSnapshotAt: ${i.message}`);if(!r||null!==r.deleted_at)throw new Error(`Baseline not found: ${t.baseline_id}`);if(r.project_id!==t.project_id)throw new Error("Baseline does not belong to this project");return r.snapshot_at}return null}async function Zt(e,t){const{data:r,error:i}=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, release_version, release_status").eq("id",t).maybeSingle();if(i)throw new Error(`getBaselineById: ${i.message}`);return r&&null===r.deleted_at?r:null}function Xt(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 er(e,t,r){const{data:i,error:n}=await e.rpc("project_state_at",{p_project_id:t,p_snapshot_at:r});if(n)throw new Error(`projectStateAt: ${n.message}`);return i??[]}async function tr(e,t,r,i){const n=r.trim();if(!n)return{items:[],totalCount:0};let a=null;if(i.asset&&i.asset.trim()){const{data:r,error:n}=await e.from("test_results").select("item_id").eq("project_id",t).eq("asset",i.asset.trim());if(n)throw new Error(n.message);const s=new Set;for(const e of r??[])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.${Jt(n)},data->>body.ilike.${Jt(n)},data->>summary.ilike.${Jt(n)}`).limit(i.limit);i.type&&(s=s.eq("type",i.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 rr(e,t){const r=new Set(e.map(e=>e.id)),i=new Set,n=[],a=(e,t,a)=>{if(e===t)return;if(!r.has(e)||!r.has(t))return;const s=`${e}|${t}|${a}`;i.has(s)||(i.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??{},r=t=>Array.isArray(e[t])?e[t].filter(e=>"string"==typeof e):[];for(const e of r("parents"))a(t.id,e,"parent");for(const e of r("children"))a(t.id,e,"child");for(const e of r("related"))a(t.id,e,"related");for(const e of r("verifies"))a(t.id,e,"verifies");for(const e of r("verified_by"))a(t.id,e,"verified_by");for(const e of r("mitigated_by"))a(t.id,e,"mitigated_by");for(const e of r("mitigates"))a(t.id,e,"mitigates")}return n}async function ir(e,t,r){const i="requirement"===r?"REQ":"test-case"===r?"TC":"note"===r?"NOTE":"TABLE",{data:n,error:a}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:i});if(a)throw new Error(`ID generation failed: ${a.message}`);return n}var nr=I({"src/db/queries.ts"(){Qt()}}),ar={};async function sr(){try{const e=await ve(async()=>{const e=await ye();return await async function(e){const{data:t,error:r}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(r)throw new Error(r.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=st(),r=T,i=P().project_scope,n=i?new Set(i):null;return Lt(jt(e.filter(e=>!r||e.org_id===r).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 Ft(Mt(e))}}E(ar,{listProjectsHandler:()=>sr});var or=I({"src/tools/list-projects.ts"(){Ae(),nr(),dt(),$(),Vt()}}),dr={};async function cr(e){try{const t=await ye();let r,i,n=null;try{n=await Kt(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ft($t(e.message))}if(n){const a=(await er(t,e.project_id,n)).filter(t=>{if(e.type&&t.type!==e.type)return!1;const r=t.data??{};if(e.domain){const t=r?.tags?.domains??[];if(!Array.isArray(t)||!t.includes(e.domain))return!1}return!e.level||r?.tags?.level===e.level});i=a.length,r=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 Gt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});r=n.items,i=n.totalCount}return Lt(jt(r.map(e=>({id:e.id,title:Nt(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),St(i,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(dr,{listItemsHandler:()=>cr});var lr=I({"src/tools/list-items.ts"(){Ae(),nr(),Vt()}}),mr={};async function pr(e){try{const r=await ye();let i=null;try{i=await Kt(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Ft(xt(e.message,["Pass baseline_id OR as_of, not both"]))}const n=i?await async function(e,t,r,i){const{data:n,error:a}=await e.rpc("item_state_at",{p_item_id:r,p_project_id:t,p_snapshot_at:i});if(a)throw new Error(`itemStateAt: ${a.message}`);return(n??[])[0]??null}(r,e.project_id,e.item_id,i).then(e=>e?Xt(e):null):await Yt(r,e.project_id,e.item_id);if(!n)return Ft(kt("Item",e.item_id));const a={parents:[],children:[],related:[],verified_by:[],verifies:[],mitigated_by:[],mitigates:[]};if(i){const e=n.data?.relationships??{};for(const t of Object.keys(a)){const r=e[t];Array.isArray(r)&&(a[t]=r.slice())}}else{const t=await async function(e,t,r){const{data:i,error:n}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${r},to_id.eq.${r}`);if(n)throw new Error(n.message);return i??[]}(r,e.project_id,e.item_id),i={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 r=a[e];r.includes(t)||r.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:i}=await r.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",m);if(i)throw new Error(i.message);l=new Set((t??[]).map(e=>e.id)),l.add(e.item_id)}const p=e=>l.has(e);for(const r of t)if(r.from_id===e.item_id){if(!p(r.to_id))continue;o(i[r.type]??r.type,r.to_id)}else{if(!p(r.from_id))continue;o(s[r.type]??r.type,r.from_id)}for(const t of Object.keys(a)){const r=c[t];if(Array.isArray(r))for(const i of r)"string"==typeof i&&i!==e.item_id&&p(i)&&o(t,i)}}let s=[];if("test-case"===n.type)if(i)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:i}=await r.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);!i&&t&&(s=t)}return Lt(jt({id:n.id,type:n.type,title:Nt(n.title),summary:Nt(n.data?.summary),body:Nt(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,Nt(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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}var t}E(mr,{getItemHandler:()=>pr});var ur=I({"src/tools/get-item.ts"(){Ae(),nr(),Vt()}}),_r={};async function fr(e){try{const t=await ye();let r,i,n=null;try{n=await Kt(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return Ft($t(e.message))}if(n){const a=await er(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 r=t.data??{};return[t.title,r?.body,r?.summary].filter(e=>"string"==typeof e).map(e=>e.toLowerCase()).some(e=>e.includes(s))});i=o.length,r=o.slice(0,e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const n=await tr(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});r=n.items,i=n.totalCount}return Lt(jt(r.map(e=>({id:e.id,title:Nt(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),St(i,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(_r,{searchHandler:()=>fr});var hr=I({"src/tools/search.ts"(){Ae(),nr(),Vt()}}),gr={};async function yr(e){try{const t=await ye(),{access_token:r}=await ce(),{items:i,totalCount:n}=await async function(e,t,r,i){const{ATOMS_SUPABASE_URL:n,ATOMS_SUPABASE_ANON_KEY:a}=await Promise.resolve().then(()=>(se(),ne)),s=await fetch(`${n}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.accessToken}`,apikey:a},body:JSON.stringify({input:r})});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:i.limit,p_type:i.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:r});return Lt(jt(i.map(e=>({id:e.id,title:Nt(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),St(n,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(gr,{semanticSearchHandler:()=>yr});var wr=I({"src/tools/semantic-search.ts"(){Ae(),he(),nr(),Vt()}}),br={};async function vr(e){try{if(e.baseline_id&&e.as_of)return Ft(Et("baseline_id and as_of are mutually exclusive"));const t=await ye();let r;if(e.baseline_id){const i=await Zt(t,e.baseline_id);if(!i)return Ft(Et(`Baseline ${e.baseline_id} not found`));if(i.project_id!==e.project_id)return Ft(Et("Baseline does not belong to this project"));r=i.snapshot_at}else e.as_of&&(r=e.as_of);const{covered:i,uncovered:n,total:a}=await async function(e,t,r){let i,n,a;if(r.snapshotAt){const s=(await er(e,t,r.snapshotAt)).map(Xt);i=s.filter(e=>"requirement"===e.type),n=s.map(e=>({id:e.id,data:e.data})),a=[]}else{const{data:r,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);i=r??[];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=i.filter(e=>!(r.domain&&!(e.data?.tags?.domains??[]).includes(r.domain)||r.level&&e.data?.tags?.level!==r.level)),o=rr(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:r}),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 Lt(jt({covered:i.length,uncovered:n.length,total:a,coverage_percent:a>0?Math.round(i.length/a*1e3)/10:100,uncovered_items:s}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(br,{getCoverageHandler:()=>vr});var jr=I({"src/tools/get-coverage.ts"(){Ae(),nr(),Vt()}}),Sr={};async function xr(e){try{const t=await ye(),r=await async function(e,t,r,i){const{data:n,error:a}=await e.from("change_history").select("*").eq("item_id",r).eq("project_id",t).order("changed_at",{ascending:!1}).limit(i);if(a)throw new Error(a.message);return n??[]}(t,e.project_id,e.item_id,e.limit),i=r.map(e=>{const t=[],r=e.old_data,i=e.new_data;if(r&&i){const e=new Set([...Object.keys(r),...Object.keys(i)]);for(const n of e)JSON.stringify(r[n])!==JSON.stringify(i[n])&&t.push(n)}else i?t.push("(created)"):r&&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 Lt(jt(i,St(i.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(Sr,{getHistoryHandler:()=>xr});var kr=I({"src/tools/get-history.ts"(){Ae(),nr(),Vt()}});function Ir(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function Er(e){const t=Or(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:`["${t}"]`}function Ar(e){const t=Ir(e.from_id),r=Ir(e.to_id);return"child"===e.type?`${t} --\x3e ${r}`:"verified_by"===e.type?`${t} -.-> ${r}`:"related"===e.type?`${t} -.- ${r}`:null}function Or(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var Rr=I({"src/core/mermaid.ts"(){}}),Dr={};async function Hr(e){try{if(e.baseline_id&&e.as_of)return Ft(Et("baseline_id and as_of are mutually exclusive"));const t=await ye();let r,i,n;if(e.baseline_id){const i=await Zt(t,e.baseline_id);if(!i)return Ft(Et(`Baseline ${e.baseline_id} not found`));if(i.project_id!==e.project_id)return Ft(Et("Baseline does not belong to this project"));r=i.snapshot_at}else e.as_of&&(r=e.as_of);if(r){i=(await er(t,e.project_id,r)).map(Xt).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),n=rr(i,[])}else{const{data:r,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);i=r??[];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=rr(i,s??[])}return Lt(jt(function(e){const t=e.items,r=e.relationships??[],i=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${Or(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,r,i){if(r)return[r];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=>i||"test-case"!==e.type).map(e=>e.id)}(t,r,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>i)continue;const m=n.get(t);if(m&&(e.includeTests||"test-case"!==m.type)){o.add(t),c.push(` ${Ir(t)}${Er(m)}`);for(const c of r){if(c.from_id!==t)continue;const r=n.get(c.to_id);if(!r)continue;if(!e.includeTests&&"test-case"===r.type)continue;if(a+1>i)continue;const m=Ar(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:i,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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(Dr,{exportMermaidHandler:()=>Hr});var Cr=I({"src/tools/export-mermaid.ts"(){Ae(),nr(),Vt(),Rr()}}),Ur={};function zr(e){const t=vt(e??"");return"sub-system"===t?"subsystem":t}async function Tr(e,t){const{data:r}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:r?.domains??[],levels:r?.levels??[]}}async function qr(e,t,r,i){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:r,levels:i},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function Mr(e,t,r){const i=vt(r??""),n=zr(i);if(!i)return!1;try{const{domains:r,levels:a}=await Tr(e,t);return!a.some(e=>zr(e)===n)&&(await qr(e,t,r,[...a,i]),!0)}catch{return!1}}async function Pr(e){try{const t=await ye(),{levels:r}=await Tr(t,e.project_id),{data:i}=await t.from("items").select("data").eq("project_id",e.project_id).is("deleted_at",null),n={};for(const e of i??[]){const t=e.data?.tags,r=zr(t?.level);r&&(n[r]=(n[r]??0)+1)}return Lt(jt({levels:r.map((e,t)=>({name:e,prefix:`L${t}`,item_count:n[zr(e)]??0})),total:r.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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function $r(e){try{const t=await ye();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const{domains:r,levels:i}=await Tr(t,e.project_id),n=vt(e.name),a=zr(n);if(!n)return Ft(Et("Level name cannot be empty."));if(i.some(e=>zr(e)===a))return Ft(Et(`Level "${n}" already exists in this project.`));const s=i.length;return await qr(t,e.project_id,r,[...i,n]),Lt(jt({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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(Ur,{createLevelHandler:()=>$r,ensureLevelRegistered:()=>Mr,listLevelsHandler:()=>Pr});var Nr,Lr,Fr=I({"src/tools/levels.ts"(){Ae(),Vt()}}),Wr=I({"src/core/project-field-counts.ts"(){}}),Vr={};async function Br(e,t){const{data:r,error:i}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(i)throw i;return Jr(r?.fields)}function Jr(e){if(!Array.isArray(e))return[];const t=[],r=new Set;for(const i of e){if(!i||"object"!=typeof i)continue;const e=i,n="string"==typeof e.name?e.name.trim():"";if(!n)continue;const a=n.toLowerCase();if(r.has(a))continue;r.add(a);const s=void 0===e.type?"text":"string"==typeof e.type&&Lr.has(e.type)?e.type:"text",o=Array.isArray(e.options)?ri(e.options):[];t.push({name:n,type:s,..."select"===s?{options:o}:{}})}return t}function Qr(e,t){const r=e.name.trim();if(!r)return"Field name cannot be empty.";if(r.length>60)return"Field name must be 60 characters or fewer.";if(!Lr.has(e.type))return"Field type is not supported.";const i=t.find(e=>e.name.toLowerCase()===r.toLowerCase());if(i)return`Field "${i.name}" already exists.`;if("select"===e.type){const t=ri(e.options??[]);if(0===t.length)return"Select fields need at least one option.";if(t.length>100)return"Select fields support at most 100 options.";if(t.some(e=>e.length>120))return"Select options must be 120 characters or fewer."}return null}function Gr(e,t){const r=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!r.has(e.toLowerCase()))}function Yr(e,t){const r=new Map(e.map(e=>[e.name.toLowerCase(),e.name])),i={};for(const[e,n]of Object.entries(t))i[r.get(e.toLowerCase())??e]=n;return i}function Kr(e,t,r=new Set){const i=Gr(e,t);if(i.length>0)return{error:`Unknown field${i.length>1?"s":""}: ${i.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,i]of Object.entries(t)){const t=a.get(e.toLowerCase());if(!t)continue;const s=Zr(t,i,r);if(s.error)return{error:s.error};s.value&&(n[t.name]=s.value)}return{fields:n}}function Zr(e,t,r){const i=t.trim();if(!i)return{value:""};if(i.length>1e4)return{error:`${e.name} is too long.`};switch(e.type){case"text":case"long":return{value:i};case"bool":{const t=i.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}(i)?{value:i}:{error:`${e.name} must be an ISO date.`};case"person":return ti(i)&&r.has(i)?{value:i}:{error:`${e.name} must be an active project member ID.`};case"select":return(e.options??[]).includes(i)?{value:i}:{error:`${e.name} must be one of: ${(e.options??[]).join(", ")}.`};case"number":return Number.isFinite(Number(i))?{value:i}:{error:`${e.name} must be numeric.`};case"link":{const t=function(e){if(!e)return{label:"",url:""};try{const t=JSON.parse(e);if(t&&"object"==typeof t&&"string"==typeof t.url){const e=t.label;return{label:"string"==typeof e?e:"",url:t.url}}}catch{}return{label:"",url:e}}(i);return function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(t.url)?{value:Xr(t.label,t.url)}:{error:`${e.name} must be an http(s) URL.`}}}}function Xr(e,t){const r=t.trim();return r?JSON.stringify({label:e.trim(),url:r}):""}async function ei(e,t,r,i){const n=new Map(r.map(e=>[e.name.toLowerCase(),e])),a=new Map;for(const[e,t]of Object.entries(i)){const r=n.get(e.toLowerCase());"person"===r?.type&&t.trim()&&a.set(t.trim(),r)}const s=new Set;for(const[r,i]of a){if(!ti(r))return{error:`${i.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:r,p_actor_user_id:je()});if(a)return{error:a.message};!0===n&&s.add(r)}return Kr(r,i,s)}function ti(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 ri(e){const t=[],r=new Set;for(const i of e){if("string"!=typeof i)continue;const e=i.trim();if(!e)continue;const n=e.toLowerCase();r.has(n)||(r.add(n),t.push(e))}return t}async function ii(e){try{const t=await ye(),r=await Br(t,e.project_id),i=await async function(e,t,r,i=500){const n=Object.fromEntries(r.map(e=>[e.name,0])),a=new Map(r.map(e=>[e.name.toLowerCase(),e.name]));let s=0;for(;;){const{data:r,error:o}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null).order("id",{ascending:!0}).range(s,s+i-1);if(o)throw o;const d=r??[];for(const e of d){const t=e.data?.fields;if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,r]of Object.entries(t)){const t=a.get(e.toLowerCase());t&&"string"==typeof r&&r.length>0&&(n[t]+=1)}}if(d.length<i)return n;s+=d.length}}(t,e.project_id,r);return Lt(jt({fields:r.map(e=>({name:e.name,type:e.type,options:e.options??[],item_count:i[e.name]??0})),total:r.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft(Mt(e))}}async function ni(e){try{const t=await ye();try{await ke(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ft(It("Project admin or owner"));throw e}const{data:r}=await t.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),i=Jr(r?.fields),n={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:ri(e.options??[])}:{}},a=Qr(n,i);if(a)return Ft(Et(a));const{data:s,error:o}="organization"===e.scope?await t.rpc("create_org_project_field_definition",{p_project_id:e.project_id,p_field:n,p_actor_user_id:je()}):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:je()});if(o)throw o;return Lt(jt({field:s?.field??n,..."organization"===e.scope?{created_projects:s?.created_projects??[],skipped_projects:s?.skipped_projects??[]}:{},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")?Ft(At()):Ft(Mt(e))}}async function ai(e){try{const t=await ye();try{await ke(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ft(It("Project admin or owner"));throw e}const r=e.name.trim(),{data:i,error:n}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"delete",p_field:null,p_field_name:r,p_actor_user_id:je()});if(n)throw n;return Lt(jt({deleted:i?.deleted??r}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft(Mt(e))}}async function si(e){try{const t=await ye();try{await ke(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Ft(It("Project admin or owner"));throw e}const r=Array.isArray(e.names)?e.names.map(e=>String(e??"").trim()).filter(e=>e.length>0):[];if(0===r.length)return Ft(Et("names must be a non-empty array of existing field names, in the order you want them"));const i=await Br(t,e.project_id),n=i.map(e=>e.name.toLowerCase()).sort(),a=r.map(e=>e.toLowerCase()).sort();if(n.length!==a.length||n.some((e,t)=>e!==a[t]))return Ft(Et(`names must list every existing field exactly once. Defined: ${i.length>0?i.map(e=>e.name).join(", "):"(none)"}`));const{data:s,error:o}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"reorder",p_field:r,p_field_name:null,p_actor_user_id:je()});if(o)throw o;return Lt(jt({fields:Jr(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft(Mt(e))}}E(Vr,{PROJECT_FIELD_TYPES:()=>Nr,canonicalizeFieldKeys:()=>Yr,createFieldHandler:()=>ni,deleteFieldHandler:()=>ai,findUnknownFieldNames:()=>Gr,getProjectFields:()=>Br,listFieldsHandler:()=>ii,normalizeProjectFields:()=>Jr,reorderFieldsHandler:()=>si,validateAndCanonicalizeFieldValues:()=>Kr,validateProjectFieldDefinition:()=>Qr,validateProjectFieldValuesForWrite:()=>ei});var oi=I({"src/tools/fields.ts"(){Ae(),Vt(),Wr(),Nr=["text","long","bool","date","person","select","number","link"],Lr=new Set(Nr)}}),di={};async function ci(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=(e.domains??[]).map(vt).filter(e=>e.length>0),n=void 0!==e.level?vt(e.level):void 0;if(i.length>0){const{data:r}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),n=r?.domains??[];if(n.length>0){const e=new Set(n.map(vt).filter(e=>e.length>0)),t=i.filter(t=>!e.has(t));if(t.length>0)return Ft(Et(`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:r,validateProjectFieldValuesForWrite:i}=await Promise.resolve().then(()=>(oi(),Vr)),n=await r(t,e.project_id),s=await i(t,e.project_id,n,e.fields);if(s.error)return Ft(Et(s.error));a=s.fields}const s=await ir(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:i,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:r,updated_at:o,updated_by:r}},{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:r,p_event_source:"mcp",p_event_session_id:Ta()??null,p_diff_summary:null});if(c)throw new Error(c.message);if(n&&await Mr(t,e.project_id,n),e.parent_ids&&e.parent_ids.length>0)for(const i 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:i,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"});n&&process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${i}: ${n.message}\n`)}return await t.from("change_history").insert({item_id:s,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:d,actor:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===e.echo?Lt(jt({id:s,type:e.type})):Lt(jt({id:s,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",domains:i,level:n??"",project_id:e.project_id}))}catch(e){return Ft(Mt(e))}}E(di,{createItemHandler:()=>ci});var li=I({"src/tools/create-item.ts"(){Ae(),nr(),Pa(),Vt(),Fr()}});function mi(e,t){const r=function(e){return`SG-${e}`}(t);return{id:e,outcome:"captured_as_change",change:{id:r,sg_number:t,status:"open"},message:`Captured as change ${r}, awaiting approval. This requirement stays at its approved revision until a human approver approves the change; no MCP tool can approve, dismiss, or apply it.`}}function pi(e){return{id:e,outcome:"under_review",message:"This requirement is under change control. Your edit was submitted; if it changed the requirement's meaning it is now a change awaiting a human approver, otherwise it wrote through live. Reload the item to confirm. No MCP tool can approve, dismiss, or apply a change."}}var ui=I({"src/core/change-control.ts"(){}}),_i={};async function fi(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=async(i,n,a,s)=>{const o=await Yt(t,e.project_id,i);if(!o)return{updated_fields:[],error:`Item "${i}" not found`};const d="approved"===o.approval_state,c=void 0!==n.domains?n.domains.map(vt).filter(e=>e.length>0):void 0,l=void 0!==n.level?vt(n.level):void 0;if(void 0!==c&&c.length>0){const{data:r}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),i=r?.domains??[];if(i.length>0){const e=new Set(i.map(vt).filter(e=>e.length>0)),t=c.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const m={...o.data},p={...o.data},u=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==n.title&&_(o.data.title,n.title)&&(p.title=n.title,u.push("title")),void 0!==n.body&&_(o.data.body,n.body)&&(p.body=n.body,u.push("body")),void 0!==n.summary&&_(o.data.summary,n.summary)&&(p.summary=n.summary,u.push("summary")),void 0!==c&&_(o.data.tags?.domains??[],c)&&(p.tags={...p.tags,domains:c},u.push("domains")),void 0!==l&&_(o.data.tags?.level,l)&&(p.tags={...p.tags,level:l},u.push("level")),void 0!==n.status&&_(o.data.status,n.status)&&(p.status=n.status,u.push("status")),void 0!==n.fields&&Object.keys(n.fields).length>0){const{getProjectFields:r,validateProjectFieldValuesForWrite:i,canonicalizeFieldKeys:a}=await Promise.resolve().then(()=>(oi(),Vr)),s=await r(t,e.project_id),d=await i(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)&&(p.fields=c,u.push("fields"))}if(0===u.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};p.metadata={...p.metadata,updated_at:(new Date).toISOString(),updated_by:r};const f=n.title??o.title,{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:i,p_project_id:e.project_id,p_type:o.type,p_title:f,p_data:p,p_user_id:r,p_event_source:"mcp",p_event_session_id:Ta()??null,p_diff_summary:null,p_expected_updated_at:n.expected_updated_at??o.updated_at});if(g)return{updated_fields:[],error:g};if(!h)return{updated_fields:[],error:`Update silently failed for "${i}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};u.includes("level")&&l&&await Mr(t,e.project_id,l);const y={item_id:i,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:m,new_data:p,actor:qa(),session_id:Ta()};if(a&&(y.batch_id=a),s&&(y.reason=s),await t.from("change_history").insert(y).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),d&&function(e){return e.some(e=>"title"===e||"body"===e||"type"===e)}(u)){const r=await async function(e,t,r){const{data:i,error:n}=await e.from("item_suggestions").select("sg_number").eq("project_id",t).eq("item_id",r).eq("status","open").maybeSingle();return n||!i?null:"number"==typeof i.sg_number?i.sg_number:null}(t,e.project_id,i);return null!==r?{updated_fields:u,updatedData:p,itemType:o.type,capturedSg:r}:{updated_fields:u,updatedData:p,itemType:o.type,capturedUnknown:!0}}return{updated_fields:u,updatedData:p,itemType:o.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),r=!0===e.continue_on_error,n=[],a=[];for(const s of e.updates){const{updated_fields:o,capturedSg:d,capturedUnknown:c,error:l}=await i(s.item_id,s,t,e.reason);if(l){if(Pt(l))return Ft(Mt(l));if(!r){const e=l instanceof Error?l.message:String("object"==typeof l&&l&&"message"in l?l.message??"":l);return Ft(Et(`Batch stopped at "${s.item_id}": ${e}. ${n.length} item(s) already updated.`))}a.push({item_id:s.item_id,error:String(l)})}else void 0!==d?n.push(mi(s.item_id,d)):c?n.push(pi(s.item_id)):n.push({id:s.item_id,updated_fields:o})}return Lt(jt({batch_id:t,updated:n.length,results:!1===e.echo?void 0:n,errors:a}))}if(!e.item_id)return Ft(Et("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:n,updatedData:a,itemType:s,capturedSg:o,capturedUnknown:d,error:c}=await i(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(c){const t=c instanceof Error?c.message:String("object"==typeof c&&c&&"message"in c?c.message??"":c);return t.includes("not found")?Ft(kt("Item",e.item_id)):t.includes("Unknown domain")||t.includes("Unknown field")?Ft(Et(t)):Ct(t)||Pt(c)?Ft(Mt(c)):Ft($t(t))}if(void 0!==o)return Lt(jt(mi(e.item_id,o)));if(d)return Lt(jt(pi(e.item_id)));if(!1===e.echo)return Lt(jt({id:e.item_id,updated_fields:n}));const l=a??{};return Lt(jt({id:e.item_id,type:s,title:l.title??"",summary:l.summary??"",body:l.body??"",domains:l.tags?.domains??[],level:l.tags?.level??"",updated_fields:n}))}catch(e){return Ft(Mt(e))}}E(_i,{updateItemHandler:()=>fi});var hi,gi,yi=I({"src/tools/update-item.ts"(){Ae(),nr(),Pa(),Vt(),Fr(),ui()}});function wi(e){const t=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(t){const r=t.toLowerCase();if("1"===r||"true"===r||"all"===r)return!0;if(t.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!P().require_confirmation_for.includes(e)}function bi(e,t=hi){const r=Date.now()+t,i={...e,exp:r},n=Buffer.from(JSON.stringify(i)).toString("base64url");return{token:`${n}.${S.default.createHmac("sha256",gi).update(n).digest("base64url")}`,expires_at:new Date(r).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function vi(e,t){if("string"!=typeof e||!e.includes("."))return{valid:!1,reason:"Token format invalid"};const[r,i]=e.split(".");if(!r||!i)return{valid:!1,reason:"Token format invalid"};const n=S.default.createHmac("sha256",gi).update(r).digest("base64url"),a=Buffer.from(i,"utf8"),s=Buffer.from(n,"utf8");if(a.length!==s.length||!S.default.timingSafeEqual(a,s))return{valid:!1,reason:"Token signature invalid"};let o;try{o=JSON.parse(Buffer.from(r,"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 r of Object.keys(e).sort())t[r]=ji(e[r]);return t}return e}function Si(e){const t=JSON.stringify(ji(e));return S.default.createHash("sha256").update(t).digest("base64url").slice(0,16)}var xi,ki=I({"src/middleware/confirmation.ts"(){$(),hi=6e4,gi=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:S.default.randomBytes(32).toString("base64url")})()}}),Ii={};async function Ei(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=await async function(e,t,r){const{data:i,error:n}=await e.from("items").select("*").eq("id",r).eq("project_id",t).maybeSingle();if(n)throw new Error(n.message);return i}(t,e.project_id,e.item_id);if(!i)return Ft(kt("Item",e.item_id));if(i.deleted_at)return Ft(Et(`Item ${e.item_id} is already deleted`));if(wi(xi)){const t={tool:xi,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const r=bi(t);return Lt(jt({status:"confirmation_required",preview:{id:e.item_id,title:i.title,type:i.type,would_soft_delete:!0},confirmation_token:r.token,expires_at:r.expires_at,expires_in_seconds:r.expires_in_seconds,message:`Re-call atoms_delete_item with the same project_id, item_id, and confirmation_token within ${r.expires_in_seconds}s to execute.`}))}const r=vi(e.confirmation_token,t);if(!r.valid)return Ft(Et(`confirmation_token rejected: ${r.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:r,p_expected_updated_at:i.updated_at,p_event_source:"mcp",p_actor:qa(),p_session_id:Ta()});if(n)throw new Error(n.message);return Lt(jt({id:e.item_id,title:i.title,type:i.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return Ft(Mt(e))}}E(Ii,{deleteItemHandler:()=>Ei});var Ai=I({"src/tools/delete-item.ts"(){Ae(),nr(),Pa(),ki(),Vt(),xi="atoms_delete_item"}}),Oi={};async function Ri(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const{data:i,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(!i)return Ft(kt("Item",e.item_id));if(!i.deleted_at)return Ft(xt(`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:i.type,p_title:i.title,p_data:i.data,p_user_id:r,p_event_source:"restore",p_event_session_id:Ta()??null,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:i.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:r,event_type:"restored",old_data:null,new_data:i.data,actor:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Lt(jt({id:e.item_id,title:i.title,type:i.type,restored:!0,message:`Item ${e.item_id} restored successfully.`}))}catch(e){return Ft(Mt(e))}}E(Oi,{restoreItemHandler:()=>Ri});var Di=I({"src/tools/restore-item.ts"(){Ae(),Pa(),Vt()}}),Hi={};async function Ci(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=async(i,n,a)=>{const s=await Yt(t,e.project_id,i.from_id);if(!s)throw new Error(`Item "${i.from_id}" not found`);const o=await Yt(t,e.project_id,i.to_id);if(!o)throw new Error(`Item "${i.to_id}" not found`);const{error:d}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:i.from_id,p_to_id:i.to_id,p_type:i.type,p_action:i.action,p_user_id:r,p_event_source:"mcp",p_expected_from_updated_at:i.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:i.expected_to_updated_at??o.updated_at});if(d)throw new Error(d.message);const c={item_id:i.from_id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:null,new_data:{relationship_change:{action:i.action,type:i.type,from:i.from_id,to:i.to_id}},actor:qa(),session_id:Ta()};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 Ft(Et(`Self-reference in batch: "${t.from_id}"`));const r=[...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",r),a=new Set((n??[]).map(e=>e.id)),s=r.filter(e=>!a.has(e));if(s.length>0)return Ft(kt("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,r]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?d.get(e)?.delete(r):(d.has(e)||d.set(e,new Set),d.get(e).add(r))}const c=0,l=1,m=2,p=new Map,u=new Set;for(const[e,t]of d){u.add(e);for(const e of t)u.add(e)}const _=e=>{if((p.get(e)??c)!==c)return null;const t=[],r=[],i=e=>{p.set(e,l),r.push(e),t.push({node:e,parents:[...d.get(e)??[]],idx:0})};for(i(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){p.set(e.node,m),r.pop(),t.pop();continue}const n=e.parents[e.idx];e.idx++;const a=p.get(n)??c;if(a===l){const e=r.indexOf(n);return[...r.slice(e),n]}a!==m&&i(n)}return null};for(const e of u){const t=_(e);if(t)return Ft(Et(`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 i(t,f,e.reason);return Lt(jt({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?Ft(Et("Cannot create a relationship between an item and itself")):(await i({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?Lt(jt({action:e.action,from_id:e.from_id,to_id:e.to_id})):Lt(jt({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}`}))):Ft(Et("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."))}catch(e){return Ft(Mt(e))}}E(Hi,{linkItemsHandler:()=>Ci});var Ui=I({"src/tools/link-items.ts"(){Ae(),nr(),Pa(),Vt()}}),zi=I({"src/core/bulk-parent-links.ts"(){}}),Ti={};function qi(e){return new Set(["22023","23503","23505","23514"]).has(e.code??"")}async function Mi(e){try{if(!e.items||0===e.items.length)return Ft(Et("items array must contain at least 1 item"));if(e.items.length>100)return Ft(Et(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=await async function(e,t,r){const{data:i}=await e.from("metadata").select("domains").eq("project_id",t).maybeSingle(),n=i?.domains??[],a=n.length>0?new Set(n.map(vt).filter(e=>e.length>0)):null,s=Si(n.map(vt).filter(e=>e.length>0).sort()),o=[],d=new Set,c={};for(let e=0;e<r.length;e++){const t=r[e];if(c[t.type]=(c[t.type]??0)+1,!a)continue;const i=(t.domains??[]).map(vt).filter(e=>e.length>0);if(0===i.length)continue;const s=i.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(wi("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:Si({items:e.items,registered_domain_hash:i.registeredDomainHash})};if(!e.confirmation_token){const r=bi(t);return Lt(jt({status:"confirmation_required",preview:{total_items:e.items.length,by_type:i.typeBreakdown,sample_titles:e.items.slice(0,5).map(e=>e.title),would_fail:i.errors.length>0,errors:i.errors,registered_domain_hash:i.registeredDomainHash},confirmation_token:r.token,expires_at:r.expires_at,expires_in_seconds:r.expires_in_seconds,message:`Re-call atoms_bulk_import with the same project_id, items array, and confirmation_token within ${r.expires_in_seconds}s to execute. Changing items or project domains will invalidate the token.`}))}const r=vi(e.confirmation_token,t);if(!r.valid)return Ft(Et(`confirmation_token rejected: ${r.reason}`))}const n=(new Date).toISOString(),a=Ta(),s=[],o=[...i.errors],d=[],c=new Map,l=async r=>{let i=c.get(r);if(!i){const n=await ir(t,e.project_id,r),a=/^([A-Z]+)-(\d+)$/.exec(n);if(!a)throw new Error(`Unexpected item id format from next_item_id: ${n}`);i={prefix:a[1],next:Number(a[2])},c.set(r,i)}const n=`${i.prefix}-${String(i.next).padStart(3,"0")}`;return i.next+=1,n};for(let t=0;t<e.items.length;t++){const r=e.items[t];if(i.invalidDomainIndexes.has(t))continue;const n=(r.domains??[]).map(vt).filter(e=>e.length>0),a=void 0!==r.level?vt(r.level):void 0;try{const e=await l(r.type);d.push({itemId:e,input:r,sanitizedDomains:n,sanitizedLevel:a,index:t})}catch(e){o.push({index:t,title:r.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===d.length)return Lt(jt({created:0,items:[],errors:o}));const m=[],p=new Map;for(const{itemId:t,input:i,sanitizedDomains:a,sanitizedLevel:s}of d){const o={id:t,type:i.type,title:i.title,summary:i.summary,body:i.body,tags:{domains:a,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:i.parent_id?[i.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:n,created_by:r,updated_at:n,updated_by:r}};p.set(t,o),m.push({id:t,project_id:e.project_id,type:i.type,title:i.title,data:o,created_by:r,updated_by:r})}const u=m.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:_}=await t.rpc("bulk_save_items_with_revisions",{p_project_id:e.project_id,p_items:u,p_user_id:r,p_event_source:"mcp"});if(_&&qi(_))for(const{itemId:i,input:n,index:c}of d){const d=m.find(e=>e.id===i);if(!d)continue;const{error:l}=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:r,p_event_source:"mcp",p_event_session_id:a,p_diff_summary:null});l?o.push({index:c,title:n.title,error:l.message}):s.push({id:i,title:n.title,type:n.type})}else{if(_)throw _;for(const{itemId:e,input:t}of d)s.push({id:e,title:t.title,type:t.type})}const f=d.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:t,input:r})=>({from_id:t,to_id:r.parent_id,type:"parent",project_id:e.project_id}));await async function(e){for(const t of e.links){const{error:r}=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"});r&&e.warn(`bulk parent link sync failed for ${t.to}: ${r.message??"unknown error"}`)}}({client:t,projectId:e.project_id,links:f.map(e=>({from:e.from_id,to:e.to_id})),userId:r,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const h=s.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:p.get(t.id)??null,actor:qa(),session_id:a}));h.length>0&&await t.from("change_history").insert(h).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const g=new Set(s.map(e=>e.id)),y=new Set(d.filter(({itemId:e,sanitizedLevel:t})=>t&&g.has(e)).map(({sanitizedLevel:e})=>e));for(const r of y)await Mr(t,e.project_id,r);return Lt(jt({created:s.length,items:s,errors:o.length>0?o:[],project_id:e.project_id}))}catch(e){return Ft(Mt(e))}}E(Ti,{bulkImportHandler:()=>Mi,canRetryBulkImportPerItem:()=>qi});var Pi=I({"src/tools/bulk-import.ts"(){Ae(),nr(),Pa(),ki(),Vt(),zi(),Fr()}}),$i={};async function Ni(e){try{const t=await ye(),r=je(),i=Se();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const n=await Yt(t,e.project_id,e.item_id);if(!n)return Ft(kt("Item",e.item_id));if("test-case"!==n.type)return Ft(Et(`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:i||r,p_actor_user_id:r,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:r,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:s,note:e.note,asset:a||null},actor:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const l=a?` (asset: ${a})`:"";return Lt(jt({item_id:e.item_id,result:e.result,run_at:s,run_by:i||r,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 Ft(Mt(e))}}E($i,{recordTestResultHandler:()=>Ni});var Li=I({"src/tools/record-test-result.ts"(){Ae(),nr(),Pa(),Vt()}}),Fi={};async function Wi(e){try{const t=await ye(),r=je(),i=Se();if(!Array.isArray(e.results)||0===e.results.length)return Ft(Et("results must be a non-empty array"));if(e.results.length>100)return Ft(Et(`results must have at most 100 entries (got ${e.results.length})`));try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const n=await Yt(t,e.project_id,e.item_id);if(!n)return Ft(kt("Item",e.item_id));if("test-case"!==n.type)return Ft(Et(`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:i||r,p_actor_user_id:r,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:r,event_type:"test_result_recorded",old_data:null,new_data:{bulk:!0,count:e.results.length,results:a},actor:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Lt(jt({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 Ft(Mt(e))}}E(Fi,{recordTestResultsBulkHandler:()=>Wi});var Vi,Bi,Ji,Qi,Gi=I({"src/tools/record-test-results-bulk.ts"(){Ae(),nr(),Pa(),Vt()}});function Yi(e){return Math.min(Math.max(e??5,1),10)}var Ki=I({"src/core/trace-graph.ts"(){Vi=200,Bi=new Set(["parent","verifies","mitigated_by"]),Ji=new Set(["child","verified_by","mitigates"]),Qi={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"}}}),Zi={};async function Xi(e){try{const t=Yi(e.depth),r=await ye(),i=await Yt(r,e.project_id,e.item_id);if(!i)return Ft(kt("Item",e.item_id));const{data:n,error:a}=await r.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 r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);const d=rr(n??[],s??[]);return Lt(jt(function(e){const t=Yi(e.depth),r=e.relationshipTypes?.length?new Set(e.relationshipTypes):null,i=new Map(e.items.map(e=>[e.id,e]));i.has(e.rootItemId)||i.set(e.rootItemId,e.rootItem);const n=new Map,a=(e,t,r)=>{n.has(e)||n.set(e,[]),n.get(e).push({neighbor:t,relType:r})};for(const t of e.relationships){const i=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(!Bi.has(i)||r&&!r.has(i)||a(t.from_id,t.to_id,i),Ji.has(i))){const e=Qi[i]??i;r&&!r.has(e)||a(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!Ji.has(i)||r&&!r.has(i)||a(t.from_id,t.to_id,i),Bi.has(i))){const e=Qi[i]??i;r&&!r.has(e)||a(t.to_id,t.from_id,e)}"related"!==i||r&&!r.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<Vi;){const{id:e,depth:r,relType:a,from:l}=c.shift();if(s.has(e)||r>t)continue;s.add(e);const m=i.get(e);if(m&&(o.push({id:e,title:m.title,type:m.type,relationship:a,depth:r,from:l}),d.push({from:l,to:e,type:a}),r<t))for(const t of n.get(e)??[])s.has(t.neighbor)||c.push({id:t.neighbor,depth:r+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>=Vi?{truncated:!0,truncation_message:`Results capped at ${Vi} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:i.title??e.item_id,type:i.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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(Zi,{traceHandler:()=>Xi});var en=I({"src/tools/trace.ts"(){Ae(),nr(),Ki(),Vt()}}),tn={};async function rn(e){try{let t=(await ye()).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:r,error:i}=await t;if(i)throw new Error(i.message);return Lt(jt({assets:r||[],total:(r||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(tn,{listAssetsHandler:()=>rn});var nn=I({"src/tools/assets.ts"(){Ae(),Vt()}}),an={};async function sn(e,t,r,i){if(r&&i)throw new Error("baseline_id and as_of are mutually exclusive");if(i)return i;if(!r)return null;const{data:n,error:a}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",r).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 on(e,t,r){if(r){const{data:i,error:n}=await e.rpc("variables_at",{p_project_id:t,p_snapshot_at:r});if(n)throw new Error(n.message);return i??[]}const{data:i,error:n}=await e.from("project_variables").select("*").eq("project_id",t).order("name");if(n)throw new Error(n.message);return i??[]}async function dn(e,t,r,i){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:r,p_event_source:i,p_variable_id:t.id??null});if(a)throw new Error(a.message);return n}async function cn(e){try{const t=await ye(),r=await sn(t,e.project_id,e.baseline_id,e.as_of),i=await on(t,e.project_id,r);return Lt(jt({variables:i,total:i.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function ln(e){try{const t=await ye(),r=await sn(t,e.project_id,e.baseline_id,e.as_of),i=(await on(t,e.project_id,r)).find(t=>t.name===e.variable_name)??null;if(!i)return Ft(kt("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 Lt(jt({variable:i,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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function mn(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(!i.data)return Ft(kt("Variable",e.variable_name));const n={updated_by:r,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),Lt(jt({variable:await dn(t,{...i.data,...n,project_id:e.project_id,name:e.variable_name,value:n.value??i.data.value,unit:n.unit??i.data.unit,description:n.description??i.data.description},r,"mcp")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function pn(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const n=e.variables.filter(e=>!i.test(e.name));if(n.length>0)return Ft(Et(`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 Ft(Et(`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 Ft(Et(`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:r,updated_by:r})),l=await async function(e,t,r,i){const{data:n,error:a}=await e.rpc("bulk_save_variables_with_revisions",{p_project_id:t,p_variables:r,p_user_id:i,p_event_source:"mcp"});if(a)throw new Error(a.message);return n??[]}(t,e.project_id,c,r);return Lt(jt({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 Ft(Et("Provide either (name, value) for single variable or variables[] for batch."));if(!i.test(e.name))return Ft(Et(`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 Ft(Et(`Variable "${e.name}" already exists in this project.`));const a=await dn(t,{project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null},r,"mcp");return!1===e.echo?Lt(jt({name:e.name})):Lt(jt({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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function un(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const{data:i}=await t.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!i)return Ft(kt("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 Ft(Et(`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(wi("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const r=bi(t);return Lt(jt({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:a,would_orphan_references:a>0},confirmation_token:r.token,expires_at:r.expires_at,expires_in_seconds:r.expires_in_seconds,message:`Re-call atoms_delete_variable with the same project_id, name, and confirmation_token within ${r.expires_in_seconds}s to execute.`}))}const r=vi(e.confirmation_token,t);if(!r.valid)return Ft(Et(`confirmation_token rejected: ${r.reason}`))}const s=await async function(e,t,r,i){const{data:n,error:a}=await e.rpc("delete_variable_with_revision",{p_project_id:t,p_variable_id:r,p_user_id:i,p_event_source:"mcp"});if(a)throw new Error(a.message);return Boolean(n)}(t,e.project_id,i.id,r);return s?Lt(jt({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})):Ft(kt("Variable",e.name))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(an,{createVariableHandler:()=>pn,deleteVariableHandler:()=>un,getVariableHandler:()=>ln,listVariablesHandler:()=>cn,updateVariableHandler:()=>mn});var _n=I({"src/tools/variables.ts"(){Ae(),ki(),Vt()}}),fn={};async function hn(e,t){const{data:r}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:r?.domains??[],levels:r?.levels??[]}}async function gn(e,t,r,i){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:r,levels:i},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function yn(e){try{const t=await ye(),{domains:r}=await hn(t,e.project_id),{counts:i,orphans:n}=await async function(e,t,r){const{data:i}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null),n={};for(const e of r)n[e]=0;const a={};for(const e of i??[]){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(r),o={};for(const[e,t]of Object.entries(a))s.has(e)||(o[e]=t);return{counts:n,orphans:o}}(t,e.project_id,r),a=r.map(e=>({name:e,registered:!0,item_count:i[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 Lt(jt({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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function wn(e){try{const t=await ye();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const{domains:r,levels:i}=await hn(t,e.project_id),n=e.name.trim().toLowerCase();return n?r.includes(n)?Ft(Et(`Domain "${n}" already exists in this project.`)):(await gn(t,e.project_id,[...r,n],i),Lt(jt({domain:{name:n},message:`Domain "${n}" registered. You can now tag items with domains=["${n}"].`}))):Ft(Et("Domain name cannot be empty."))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function bn(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const{domains:i,levels:n}=await hn(t,e.project_id),a=e.name.trim().toLowerCase(),s=e.new_name.trim().toLowerCase();if(!s)return Ft(Et("new_name cannot be empty."));const o=i.includes(a);if(!o){const{data:r}=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(!r||0===r.length)return Ft(kt("Domain",a))}if(s!==a&&i.includes(s))return Ft(Et(`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 Lt(jt({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?i.map(e=>e===a?s:e):i.includes(s)?i:[...i,s],await gn(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:r,p_event_source:"mcp"});if(p)throw new Error(p.message);return Lt(jt({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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}async function vn(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const{domains:i,levels:n}=await hn(t,e.project_id),a=e.name.trim().toLowerCase(),s=i.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 Ft(kt("Domain",a));if(c>0&&!e.force)return Ft(Et(`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(wi("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 Lt(jt({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 r=vi(e.confirmation_token,t);if(!r.valid)return Ft(Et(`confirmation_token rejected: ${r.reason}`))}const l=s?i.filter(e=>e!==a):i;if(await gn(t,e.project_id,l,n),c>0){const{error:i}=await t.rpc("apply_domain_change",{p_project_id:e.project_id,p_old_domain:a,p_new_domain:null,p_user_id:r,p_event_source:"mcp"});if(i)throw new Error(i.message)}return Lt(jt({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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(fn,{createDomainHandler:()=>wn,deleteDomainHandler:()=>vn,listDomainsHandler:()=>yn,updateDomainHandler:()=>bn});var jn=I({"src/tools/domains.ts"(){Ae(),ki(),Vt()}}),Sn={};async function xn(e){try{const t=await ye(),{data:r,error:i}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle(),n=r?.name??null,a=i?.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 Ft(kt("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:r,error:i}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(i)throw new Error(i.message);const n=new Map;for(const e of r??[])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:u,error:_}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(_)throw new Error(_.message);const f=rr(s??[],u??[]),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)"],r=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++,r&&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 Lt(jt({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")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(Sn,{projectSummaryHandler:()=>xn});var kn,In=I({"src/tools/project-summary.ts"(){Ae(),nr(),Vt()}}),En={};async function An(e){try{const t=await ye();let r,i;if(e.query&&e.query.trim().length>0){const n=await tr(t,e.project_id,e.query,{type:e.type,limit:e.limit});r=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})),i=n.totalCount}else{const n=await Gt(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});r=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})),i=n.totalCount}const n=await async function(e,t){const{data:r,error:i}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(i)throw new Error(i.message);const n=new Set,a=new Set;for(const e of r??[]){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)n.add(t);const r=t.level;r&&a.add(r)}}return{domains:[...n].sort(),levels:[...a].sort()}}(t,e.project_id);return Lt(jt({items:r,filters:{domains:n.domains,levels:n.levels,types:kn},project_id:e.project_id},St(i,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(En,{browseHandler:()=>An});var On,Rn,Dn,Hn,Cn=I({"src/tools/browse.ts"(){Ae(),nr(),Vt(),kn=["requirement","test-case","note","table"]}}),Un={};async function zn(e){try{const t=e.direction??"downstream",r=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,i=await ye(),n=await Yt(i,e.project_id,e.item_id);if(!n)return Ft(kt("Item",e.item_id));const{data:a,error:s}=await i.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 i.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,r)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:r})};for(const e of a??[]){const r=e.type;"upstream"!==t&&"both"!==t||(Rn.includes(r)&&m(e.from_id,e.to_id,r),Dn.includes(r)&&m(e.to_id,e.from_id,Hn[r]??r)),"downstream"!==t&&"both"!==t||(Dn.includes(r)&&m(e.from_id,e.to_id,r),Rn.includes(r)&&m(e.to_id,e.from_id,Hn[r]??r)),"related"===r&&(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 u=[];let _=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&&u.length<On;){const{id:e,depth:t,path:i}=f.shift();if(p.has(e))continue;if(null!==r&&t>r)continue;p.add(e);const n=c.get(e);if(n&&(u.push({item_id:e,title:Nt(n.title),type:n.type,depth:t,relationship_path:i}),t>_&&(_=t),null===r||t<r))for(const r of l.get(e)??[])p.has(r.neighbor)||f.push({id:r.neighbor,depth:t+1,path:[...i,{from_id:e,to_id:r.neighbor,relationship_type:r.relType}]})}let h=0;if(e.include_variable_refs){const{data:t}=await i.from("variable_references").select("variable_id").eq("item_id",e.item_id).eq("project_id",e.project_id),r=[...new Set((t??[]).map(e=>e.variable_id))];if(r.length>0){const{data:t}=await i.from("project_variables").select("id, name").in("id",r),n=new Map((t??[]).map(e=>[e.id,e.name])),{data:a}=await i.from("variable_references").select("variable_id, item_id").in("variable_id",r).eq("project_id",e.project_id).neq("item_id",e.item_id);for(const t of a??[]){const r=t.item_id;if(p.has(r))continue;if(u.length>=On)break;p.add(r);const i=c.get(r);if(!i)continue;const a=n.get(t.variable_id)??t.variable_id;u.push({item_id:r,title:Nt(i.title),type:i.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:r,relationship_type:`variable_ref:${a}`}]}),h++}}}const g={};for(const e of u)g[e.type]=(g[e.type]??0)+1;const y=c.get(e.item_id);return Lt(jt({root:{item_id:e.item_id,title:Nt(y?.title??n.title),type:y?.type??n.type},impacted_items:u,summary:{total_impacted:u.length,by_type:g,max_depth_reached:_,...h>0?{variable_impact_count:h}:{},...u.length>=On?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):Ft($t(e instanceof Error?e.message:String(e)))}}E(Un,{impactAnalysisHandler:()=>zn});var Tn=I({"src/tools/impact-analysis.ts"(){Ae(),nr(),Vt(),On=200,Rn=["parent","verifies","traces_to","allocated_from","decomposed_from"],Dn=["child","verified_by","allocated_to","decomposes_to","traced_by"],Hn={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"}}}),qn=I({"src/core/relationship-sync.ts"(){}}),Mn={};function Pn(e){return e instanceof Error&&e.message.includes("Not authenticated")?Ft(At()):null}async function $n(e,t){const{data:r,error:i}=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(i)throw new Error(i.message);return r}async function Nn(e,t,r){const{data:i,error:n}=await e.from("items").select("id, deleted_at").eq("project_id",t).eq("id",r).maybeSingle();if(n)throw new Error(n.message);if(a=i,!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:r});if(s)throw new Error(s.message)}async function Ln(e,t,r){const{data:i,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n)return Ft($t(n.message));if(!i)return Ft(kt("Project",t));const{data:a,error:s}=await e.from("organizations").select("feature_flags").eq("id",i.org_id).maybeSingle();return s?Ft($t(s.message)):!0!==(a?.feature_flags??{})[r]?Ft(xt(`Feature '${r}' 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 ye(),r=await async function(e,t){const{data:r,error:i}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, release_version, release_status").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1});if(i)throw new Error(`listBaselines: ${i.message}`);return r??[]}(t,e.project_id),i=Math.max(e.offset??0,0),n=Math.min(Math.max(e.limit??50,1),100);return Lt(jt({baselines:r.slice(i,i+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,release_version:e.release_version,release_status:e.release_status})),total:r.length,offset:i,limit:n}))}catch(e){return Pn(e)??Ft($t(e instanceof Error?e.message:String(e)))}}async function Wn(e){try{const t=await ye(),r=await Ln(t,e.project_id,"baselines_enabled");if(r)return r;const{data:i,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?Ft(xt(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):Ft($t(n.message)):Lt(jt({id:i.id,name:i.name,description:i.description,field_definitions_snapshot:i.field_definitions_snapshot,snapshot_at:i.snapshot_at,created_at:i.created_at,locked:!1}))}catch(e){return Pn(e)??Ft($t(e instanceof Error?e.message:String(e)))}}async function Vn(e){try{const t=await ye(),r=await Zt(t,e.baseline_id);if(!r)return Ft(kt("Baseline",e.baseline_id));const i=await Ln(t,r.project_id,"baselines_enabled");if(i)return i;if(null!==r.locked_at)return Ft(xt("Baseline is already locked",["Locks are one-way; nothing to do"]));const{data:n}=await t.from("projects").select("org_id").eq("id",r.project_id).maybeSingle();if(!n)return Ft(kt("Project",r.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ft(At());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 Ft(xt("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?Ft($t(c.message)):Lt(jt({id:d.id,locked_at:d.locked_at,locked_by:d.locked_by}))}catch(e){return Pn(e)??Ft($t(e instanceof Error?e.message:String(e)))}}async function Bn(e){try{const t=await ye(),[r,i]=await Promise.all([Zt(t,e.baseline_a_id),Zt(t,e.baseline_b_id)]);if(!r||!i)return Ft(kt("Baseline","one of the baseline_ids"));if(r.project_id!==i.project_id)return Ft(xt("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[n,a]=await Promise.all([er(t,r.project_id,r.snapshot_at),er(t,i.project_id,i.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),r=o.get(e);if(!t&&r)l++,c.push({item_id:e,change_type:"added"});else if(t&&!r)m++,c.push({item_id:e,change_type:"removed"});else if(t&&r){const i=[];t.title!==r.title&&i.push("title"),t.type!==r.type&&i.push("type");JSON.stringify(t.data??{})!==JSON.stringify(r.data??{})&&i.push("data"),i.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:i}))}}const u=Math.max(e.offset??0,0),_=Math.min(Math.max(e.limit??50,1),200),f=e.detail?c.slice(u,u+_):c.slice(u,u+_).map(({item_id:e,change_type:t,fields_changed:r})=>({item_id:e,change_type:t,fields_changed:r}));return Lt(jt({summary:{added:l,removed:m,modified:p,total_compared:d.length},items:f,page_info:{offset:u,limit:_,total:c.length},baselines:{a:{id:r.id,name:r.name,snapshot_at:r.snapshot_at},b:{id:i.id,name:i.name,snapshot_at:i.snapshot_at}}}))}catch(e){return Pn(e)??Ft($t(e instanceof Error?e.message:String(e)))}}async function Jn(e){try{const t=await ye(),r=await Zt(t,e.baseline_id);if(!r)return Ft(kt("Baseline",e.baseline_id));const i=await Ln(t,r.project_id,"baselines_enabled");if(i)return i;const{data:n}=await t.from("projects").select("org_id").eq("id",r.project_id).maybeSingle();if(!n)return Ft(kt("Project",r.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return Ft(At());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 Ft(xt("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const d=await er(t,r.project_id,r.snapshot_at),c=d.map(e=>e.id),{data:l,error:m}=c.length>0?await t.from("items").select("*").eq("project_id",r.project_id).in("id",c):{data:[],error:null};if(m)return Ft($t(m.message));const p=function(e,t){const r=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=r.get(e.id),i=[];var n,a;return t?(null!==t.deleted_at&&i.push("deleted_at"),t.type!==e.type&&i.push("type"),t.title!==e.title&&i.push("title"),n=t.data,a=e.data,JSON.stringify(n??{})!==JSON.stringify(a??{})&&i.push("data")):i.push("missing"),0===i.length?[]:[{id:e.id,type:e.type,title:e.title,data:e.data??{},diff_summary:{changed_fields:i,restored:!0},oldData:t?.data??null}]})}(d,l??[]),{data:u,error:_}=await t.rpc("variables_at",{p_project_id:r.project_id,p_snapshot_at:r.snapshot_at});if(_)return Ft($t(_.message));const f=u??[];if(!0!==e.confirm)return Lt(jt({preview:!0,items_to_restore:p.length,variables_to_restore:f.length,field_definitions_to_restore:r.field_definitions_snapshot?.length??null}));const h=await $n(t,{baselineId:r.id,projectId:r.project_id,userId:s});return Lt(jt({ok:!0,items_restored:h.items_restored,variables_restored:h.variables_restored,field_definitions_restored:h.field_definitions.length}))}catch(e){return Pn(e)??Ft($t(e instanceof Error?e.message:String(e)))}}E(Mn,{createBaselineHandler:()=>Wn,diffBaselinesHandler:()=>Bn,listBaselinesHandler:()=>Fn,lockBaselineHandler:()=>Vn,restoreBaselineHandler:()=>Jn,restoreBaselineStateAtomically:()=>$n,syncRestoredItemRelationships:()=>Nn});var Qn,Gn,Yn,Kn,Zn,Xn,ea,ta,ra,ia,na=I({"src/tools/baselines.ts"(){Ae(),Pa(),Vt(),nr(),qn()}});function aa(e){const t=e?.severity||"",r=e?.exposure||"",i=e?.controllability||"";return t&&r&&i?"S0"===t||"E0"===r||"C0"===i?"QM":Yn[`${t}-${r}-${i}`]||Qn:Qn}function sa(e){const t=parseInt(e?.severity||"",10),r=parseInt(e?.occurrence||"",10),i=parseInt(e?.detection||"",10);return Number.isNaN(t)||Number.isNaN(r)||Number.isNaN(i)?Qn:String(t*r*i)}function oa(e,t){return"hara"===e?aa(t):sa(t)}function da(e,t,r){if(r)return!1;if("hara"===e){const e=aa(t);return"C"===e||"D"===e}const i=parseInt(sa(t),10);return!Number.isNaN(i)&&i>=200}function ca(e,t,r){if(!e?.approved||!e.approved_at)return!1;const i=Date.parse(e.approved_at);return!Number.isNaN(i)&&[...e.source_req?[e.source_req]:[],...t].some(e=>{const t=r(e),n=t?Date.parse(t):NaN;return!Number.isNaN(n)&&n>i})}var la,ma,pa=I({"src/core/analysis.ts"(){Qn="—",Gn=["prevention","detection","mitigation"],Yn={"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"},Zn={hara:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea:{severity:Kn=["1","2","3","4","5","6","7","8","9","10"],occurrence:Kn,detection:Kn}},Xn={hara:["failure_mode","operating_scenario","severity","exposure","controllability","safe_state","ftti","rationale"],dfmea:["failure_mode","cause","severity","occurrence","detection","rationale"]},ea={hara:"safety-goal",dfmea:"failure-mode"},ta={hara:"SG",dfmea:"FM"},ra={hara:"HARA",dfmea:"DFMEA"},ia={hara:"hara_iso26262",dfmea:"dfmea_rpn"}}}),ua={};function _a(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}async function fa(e,t,r){const{data:i,error:n}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(n)throw new Error(`ID generation failed: ${n.message}`);return i}function ha(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function ga(e){return JSON.parse(JSON.stringify(e??{}))}async function ya(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=e.source_req_ids??[];if(i.length>50)return Ft(Et("source_req_ids supports at most 50 entries per call"));if(i.length>0){const{data:r,error:n}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null).in("id",i);if(n)throw new Error(n.message);const a=new Map((r??[]).map(e=>[e.id,e])),s=i.filter(e=>!a.has(e));if(s.length>0)return Ft(kt("Source requirement(s)",s.join(", ")));const o=i.filter(e=>{const t=a.get(e);return"requirement"!==t.type||la.has(t.data?.req_type)});if(o.length>0)return Ft(Et(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${o.join(", ")}`))}const n=e.subtype,a=await fa(t,e.project_id,ra[n]),s=e.title??("hara"===n?"New HARA":"New DFMEA"),o=e.revision??"1.0",d=ea[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:ia[n],revision:o},metadata:{created_at:c,created_by:r,updated_at:c,updated_by:r}},{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:r,p_event_source:"mcp",p_event_session_id:Ta()??null,p_diff_summary:null});if(m)throw new Error(m.message);const p=[],u=[];for(const s of i){const i=await fa(t,e.project_id,ta[n]),o={id:i,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:r,updated_at:c,updated_by:r}},{error:l}=await t.rpc("save_item_with_revision",{p_item_id:i,p_project_id:e.project_id,p_type:"requirement",p_title:"",p_data:o,p_user_id:r,p_event_source:"mcp",p_event_session_id:Ta()??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:i,p_to_id:a,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"});m&&(process.stderr.write(`[atoms-mcp] Warning: analysis row parent link sync failed for ${i}: ${m.message}\n`),u.push({row_id:i,source_req:s,message:m.message})),await t.from("change_history").insert({item_id:i,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:o,actor:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),p.push({id:i,source_req:s})}return await t.from("change_history").insert({item_id:a,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:l,actor:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Lt(jt({id:a,subtype:n,title:Nt(s),revision:o,rows:p,...u.length>0?{link_warnings:u,warning:`${u.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 Ft(Mt(e))}}async function wa(e){try{const t=await ye(),r=je();try{await xe(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}const i=await Yt(t,e.project_id,e.row_id);if(!i)return Ft(kt("Analysis row",e.row_id));const n=i.data,a=_a(n?.req_type);if(!a)return Ft(Et(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const s=new Set([...Xn[a],"effect"]);"hara"===a&&s.add("title");const o=Object.keys(e.fields??{});if(0===o.length)return Ft(Et("fields must contain at least one key"));const d=o.filter(e=>!s.has(e));if(d.length>0)return Ft(Et(`Unknown field(s) for ${a}: ${d.join(", ")}. Allowed: ${[...s].sort().join(", ")}`));const c=Zn[a],l={};for(const t of o){const r=e.fields[t];if(c[t]){const e="number"==typeof r&&"dfmea"===a?String(r):r;if("string"!=typeof e||!c[t].includes(e))return Ft(Et(`Invalid ${t} value ${JSON.stringify(r)} for ${a}. Allowed: ${c[t].join(", ")}`));l[t]=e}else{if("string"!=typeof r)return Ft(Et(`Field '${t}' must be a string`));l[t]=r}}const m=n?.analysis_props??null,p=ga(n);p.analysis_props&&"object"==typeof p.analysis_props||(p.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const u=p.analysis_props;u.field_source&&"object"==typeof u.field_source||(u.field_source={});let _=i.title;for(const[e,t]of Object.entries(l))"effect"===e?p.body=t:"title"===e?(p.title=t,_=t):(u[e]=t,"failure_mode"===e&&"dfmea"===a&&(p.title=t,_=t)),u.field_source[e]="mcp";const f=(new Date).toISOString();p.metadata={...p.metadata??{},updated_at:f,updated_by:r};const{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:i.id,p_project_id:e.project_id,p_type:i.type,p_title:_,p_data:p,p_user_id:r,p_event_source:"mcp",p_event_session_id:Ta()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});if(g)throw new Error(g.message);if(!h)return Ft(xt(`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:i.id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:n,new_data:p,actor:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=oa(a,u),w=[];if("hara"===a){const n=oa("hara",m),a=ha(p);if(a.length>0&&y!==Qn&&y!==n)for(const n of a){const a=await Yt(t,e.project_id,n);if(!a)continue;const s=a.data;if(s?.asil===y&&s?.asil_source===i.id)continue;const o=s?.asil??null,d=s?.asil_source??null,c=ga(s);c.asil=y,c.asil_source=i.id,c.metadata={...c.metadata??{},updated_at:f,updated_by:r};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:r,p_event_source:"mcp",p_event_session_id:Ta()??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:r,event_type:"updated",old_data:{asil:o,asil_source:d},new_data:{asil:y,asil_source:i.id},actor:qa(),session_id:Ta(),reason:`ASIL propagated from ${i.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 Lt(jt({row_id:i.id,subtype:a,written_fields:Object.keys(l),computed_level:y,...w.length>0?{asil_propagated_to:w}:{}}))}catch(e){return Ft(Mt(e))}}async function ba(e,t,r){const i=await Yt(e,t,r);if(!i)return{ok:!1,result:Ft(kt("Analysis",r))};if("analysis"!==i.type)return{ok:!1,result:Ft(Et(`Item ${r} is not an analysis (type='${i.type}')`))};const n=i.data,a=_a("hara"===n?.analysis?.subtype?"safety-goal":"dfmea"===n?.analysis?.subtype?"failure-mode":null);if(!a)return{ok:!1,result:Ft(Et(`Analysis ${r} is missing a valid analysis.subtype`))};const s=ea[a],o=Array.isArray(n?.relationships?.children)?n.relationships.children.filter(e=>"string"==typeof e):[];let d=[];if(o.length>0){const{data:r,error:i}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",o);if(i)throw new Error(i.message);const n=new Map((r??[]).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 ha(e.data))c.add(t)}const l=new Map;if(c.size>0){const{data:r,error:i}=await e.from("items").select("id, updated_at").eq("project_id",t).is("deleted_at",null).in("id",[...c]);if(i)throw new Error(i.message);for(const e of r??[])l.set(e.id,e.updated_at)}const m=d.map(e=>{const t=e.data?.analysis_props??{},r=ha(e.data).filter(e=>l.has(e)),i=r.length>0,n=oa(a,t),s=function(e,t,r){if(r)return null;if("hara"===e){const e=aa(t);return"QM"!==e&&e!==Qn?`asil ${e} unmitigated`:null}const i=parseInt(sa(t),10),n=parseInt(t?.severity||"",10);return!Number.isNaN(i)&&i>=100?"rpn >= 100":!Number.isNaN(n)&&n>=9?"severity >= 9":null}(a,t,i),o={id:e.id,title:Nt("string"==typeof e.title?e.title:""),source_req:"string"==typeof t.source_req?t.source_req:null,effect:Nt("string"==typeof e.data?.body?e.data.body:""),computed_level:n,is_gap:null!==s,gap_rule:s,is_critical:da(a,t,i),is_stale:ca(t,r,e=>l.get(e)??null),mitigated_by:r,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 Xn[a]){const r=t[e]??null;o[e]=ma.has(e)&&"string"==typeof r?Nt(r):r}return o});return{ok:!0,analysis:{id:i.id,title:Nt("string"==typeof i.title?i.title:""),subtype:a,scheme:"string"==typeof n?.analysis?.scheme?n.analysis.scheme:ia[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 va(e){try{const t=await ye(),r=await ba(t,e.project_id,e.analysis_id);return r.ok?Lt(jt({analysis:r.analysis,rows:r.rows,counts:r.counts})):r.result}catch(e){return Ft(Mt(e))}}async function ja(e){try{const n=await ye(),a=je();try{await xe(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Ft(It("Viewer"));throw e}if(e.row_id===e.req_id)return Ft(Et("row_id and req_id must be different items"));const s=await Yt(n,e.project_id,e.row_id);if(!s)return Ft(kt("Analysis row",e.row_id));const o=s.data,d=_a(o?.req_type);if(!d)return Ft(Et(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const c=await Yt(n,e.project_id,e.req_id);if(!c)return Ft(kt("Requirement",e.req_id));const l=c.data;if("requirement"!==c.type||la.has(l?.req_type))return Ft(Et(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));if("dfmea"===d&&!e.role)return Ft(Et(`role is required for dfmea mitigation links. Choose one of: ${Gn.join(", ")}`));if("hara"===d&&e.role)return Ft(Et("role is not applicable to hara mitigation links; omit it (roles are a dfmea concept)"));let m=Qn;if("hara"===d){m=oa("hara",o?.analysis_props);const n=l?.asil;if(m!==Qn&&"string"==typeof n&&n.length>0&&n!==m&&!0!==e.override)return Ft((r=m,{...xt(`ASIL conflict: the target requirement already carries asil '${t=n}' but ${i=s.id} computes '${r}'.`,["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:r,source_row:i,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:u}=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(u)throw new Error(u.message);let _;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:qa(),session_id:Ta()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),"hara"===d&&m!==Qn){const t=await Yt(n,e.project_id,e.req_id);if(t){const r=t.data,i=r?.asil??null,o=r?.asil_source??null,d=ga(r);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:Ta()??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:i,asil_source:o},new_data:{asil:m,asil_source:s.id},actor:qa(),session_id:Ta(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${i??"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`)}),_=m}}return Lt(jt({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:p,..._?{asil_written:_}:{}}))}catch(e){return Ft(Mt(e))}var t,r,i}async function Sa(e){try{const t=await ye(),r=await ba(t,e.project_id,e.analysis_id);if(!r.ok)return r.result;const i=r.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 Lt(jt({analysis_id:r.analysis.id,subtype:r.analysis.subtype,gaps:i,count:i.length}))}catch(e){return Ft(Mt(e))}}E(ua,{createAnalysisHandler:()=>ya,fillRowHandler:()=>wa,getAnalysisHandler:()=>va,getGapsHandler:()=>Sa,linkMitigationHandler:()=>ja});var xa,ka,Ia,Ea,Aa,Oa,Ra,Da,Ha=I({"src/tools/analysis.ts"(){Ae(),nr(),Pa(),Vt(),pa(),la=new Set(["safety-goal","failure-mode"]),ma=new Set(["failure_mode","cause","operating_scenario","safe_state","ftti","rationale"])}}),Ca={};function Ua(e){F(e.toolName)&&function(e,t){const r=`ui://${t.toolName}/${t.htmlFile}`,i=function(e,t){const r=s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("index.cjs",document.baseURI).href),i=j.default.dirname(r);return j.default.resolve(i,"apps","src","apps",e,t)}(t.appName,t.htmlFile),n=[...Wt.resourceDomains,...t.extraResourceDomains??[]];d.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:r}}},t.handler),d.registerAppResource(e,`${t.title} UI`,r,{mimeType:d.RESOURCE_MIME_TYPE},async()=>{const e=await v.default.readFile(i,"utf-8");return{contents:[{uri:r,mimeType:d.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:n}}}}]}})}(Ea,e)}function za(e,t){return async r=>{const i=R(P(),e);if(!i.allowed)return Ft(xt(`Tool ${e} is blocked by org policy.`,[H(i.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=st();if(!t)return;if("object"!=typeof e||null===e)return;const r=e.project_id;if("string"==typeof r&&r!==t)throw new it(t,r)}(r)}catch(e){if(e instanceof it)return Ft(Rt(e.expectedProjectId));throw e}{const e=P(),t=r?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return Ft(xt("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 ye(),n=je()}catch{return t(r)}const s=await async function(e,t){const r=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Xe,i=new Date,n=new Date(i.getTime()-et);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)>=r){const{data:r,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=(r?new Date(r.requested_at).getTime():i.getTime())+et-i.getTime();return{allowed:!1,retryAfterSeconds:Math.max(1,Math.ceil(s/1e3))}}t.from("mcp_rate_limits").insert({user_id:e,requested_at:i.toISOString()}).then(({error:e})=>{e&&process.stderr.write(`[rate-limiter] insert failed: ${e.message}\n`)});const o=new Date(i.getTime()-2*et);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 Ft(Dt(s.retryAfterSeconds));if("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN){const e=r?.project_id;if("string"==typeof e)try{const{requireWriteAccess:t}=await Promise.resolve().then(()=>(Ae(),ge));await t(a,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(Vt(),wt));return Ft(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(r),i=e;if(!0===i?.isError){c="error";const e=i?.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:r,status:c,duration_ms:o(),error_msg:d,project_id:r.project_id,session_id:Oa,client_name:Ra};try{!function(e,t,r){const i=Ze(r.params);e.from("mcp_audit_log").insert({user_id:t,tool_name:r.tool_name,params:i,status:r.status,duration_ms:r.duration_ms,error_msg:r.error_msg??null,project_id:r.project_id??null,session_id:r.session_id??null,client_name:r.client_name??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await ye(),n,t)}catch{}}}}function Ta(){return Oa}function qa(){return Da}function Ma(){return Ra}E(Ca,{ATOMS_MCP_SERVER_VERSION:()=>Ia,getMcpActor:()=>qa,getMcpClientName:()=>Ma,getMcpSessionId:()=>Ta,server:()=>Ea});var Pa=I({"src/server.ts"(){nt(),at(),B(),dt(),$(),q(),ht(),gt(),Ae(),Vt(),Bt(),xa=l.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("index.cjs",document.baseURI).href),ka=xa("../package.json"),Ia=ka.version,Ea=new c.McpServer({name:"atoms-mcp-server",version:Ia}),Aa=(e,t,r)=>{if(F(e))return Ea.registerTool(e,t,r)},Oa=a.randomUUID(),Ra=ct(process.env.ATOMS_CLIENT_NAME),Da=function(){const e=ct(Ra);return"cursor"===e?"mcp_cursor":"copilot"===e?"mcp_copilot":"mcp_claude"}(),Aa("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(()=>(ie(),J)),r=await e();if(!r)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(r))try{const{getValidToken:e}=await Promise.resolve().then(()=>(he(),oe)),{email:t}=await e(),{invalidateClient:r}=await Promise.resolve().then(()=>(Ae(),ge));return r(),{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:r.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:r.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)}]}}}),Aa("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}},za("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(or(),ar));return e()})),Aa("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:o.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:o.z.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:o.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:o.z.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}},za("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(lr(),dr));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:o.z.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:o.z.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}},za("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(ur(),mr));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),query:o.z.string().min(1).max(1e3).describe("Search text"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),asset:o.z.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:o.z.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}},za("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(hr(),_r));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),query:o.z.string().min(1).max(1e3).describe("Natural-language concept query"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:o.z.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(wr(),gr));return t(e)})),Ua({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:o.z.string().uuid().describe("UUID of the project"),domain:o.z.string().max(64).optional().describe("Filter by domain tag"),level:o.z.string().max(32).optional().describe("Filter by level"),baseline_id:o.z.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:o.z.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:za("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(jr(),br));return t(e)})}),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID"),limit:o.z.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(kr(),Sr));return t(e)})),Ua({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:o.z.string().uuid().describe("UUID of the project"),root_item_id:o.z.string().max(20).optional().describe("Root item ID to start from"),depth:o.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:o.z.boolean().default(!0).describe("Include test case links"),baseline_id:o.z.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:o.z.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:za("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(Cr(),Dr));return t(e)})}),Aa("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:o.z.string().uuid().describe("UUID of the target project"),type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),body:o.z.string().max(5e4).optional().describe("Rich text body"),summary:o.z.string().max(2e3).optional().describe("Brief summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("Domain tags"),level:o.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:o.z.array(o.z.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional().describe("Project-field values keyed by defined field name"),echo:o.z.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(li(),di));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).optional().describe("Item ID (single form)"),title:o.z.string().min(1).max(500).optional().describe("New title"),body:o.z.string().max(5e4).optional().describe("New body"),summary:o.z.string().max(2e3).optional().describe("New summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("New domain tags"),level:o.z.string().max(32).optional().describe("New level"),status:o.z.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status"),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),expected_updated_at:lt.optional().describe("metadata.updated_at value from atoms_get_item; rejects stale writes"),echo:o.z.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:o.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:o.z.array(o.z.object({item_id:o.z.string().min(1).max(20),title:o.z.string().min(1).max(500).optional(),body:o.z.string().max(5e4).optional(),summary:o.z.string().max(2e3).optional(),domains:o.z.array(o.z.string().max(64)).max(20).optional(),level:o.z.string().max(32).optional(),status:o.z.enum(["passed","failed","blocked","not-run"]).optional(),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional(),expected_updated_at:lt.optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:o.z.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:o.z.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(yi(),_i));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:o.z.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}},za("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Ai(),Ii));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().max(256).describe("ID of the soft-deleted item to restore")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(Di(),Oi));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),from_id:o.z.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:o.z.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:o.z.enum(["parent","child","related","verifies","verified_by"]).optional().describe("Relationship type"),action:o.z.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:lt.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:lt.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:o.z.boolean().optional().describe("false → lean response"),reason:o.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:o.z.array(o.z.object({action:o.z.enum(["add","remove"]),from_id:o.z.string().min(1).max(20),to_id:o.z.string().min(1).max(20),type:o.z.enum(["parent","child","related","verifies","verified_by"]),expected_from_updated_at:lt.optional(),expected_to_updated_at:lt.optional()})).optional().describe("Array form: batch relationship ops. Always atomic with DAG cycle detection."),idempotency_key:o.z.string().max(128).optional().describe("Safe retry key (24h TTL)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(Ui(),Hi));return t(e)})),Ua({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:o.z.string().uuid().describe("UUID of the target project"),items:o.z.array(o.z.object({type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),body:o.z.string().max(5e4).optional().describe("Rich text body"),summary:o.z.string().max(2e3).optional().describe("Brief summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("Domain tags"),level:o.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:o.z.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)"),confirmation_token:o.z.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:za("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(Pi(),Ti));return t(e)})}),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:o.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:o.z.string().max(1e3).optional().describe("Reason or comment for this result"),asset:o.z.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}},za("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(Li(),$i));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:o.z.array(o.z.object({asset:o.z.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:o.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:o.z.string().max(500).optional().describe("Run note"),date:o.z.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}},za("atoms_record_test_results",async e=>{const{recordTestResultsBulkHandler:t}=await Promise.resolve().then(()=>(Gi(),Fi));return t(e)})),Ua({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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Starting item ID"),direction:o.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:o.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:o.z.array(o.z.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:za("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(en(),Zi));return t(e)})}),Aa("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:o.z.string().uuid().describe("UUID of the project"),include_archived:o.z.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(nn(),tn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:o.z.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(_n(),an));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).max(64).describe("Variable name"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:o.z.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(_n(),an));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).max(64).describe("Variable name"),value:o.z.string().max(500).optional().describe("New value"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(_n(),an));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).optional().describe("Variable name (single form)"),value:o.z.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description"),echo:o.z.boolean().optional().describe("false → lean response (default true)"),variables:o.z.array(o.z.object({name:o.z.string().min(1).max(64).describe("Variable name"),value:o.z.string().min(1).max(500).describe("Initial value"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:o.z.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(_n(),an));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Variable name to delete"),force:o.z.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:o.z.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}},za("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(_n(),an));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(jn(),fn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(jn(),fn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(Fr(),Ur));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(Fr(),Ur));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(oi(),Vr));return t(e)})),Aa("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 - scope (string, optional): project (default) or organization (org admin only)\n\nReturns:\n { field: { name, type, options }, message }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:o.z.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:o.z.array(o.z.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:o.z.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(oi(),Vr));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(60).describe("Field name")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},za("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(oi(),Vr));return t(e)})),Aa("atoms_reorder_fields",{title:"Reorder Project Fields",description:"Reorder project field definitions. Definition order drives the Column Picker listing and a fresh user's Matrix column order.\n\nOrdering only: no definition is added, dropped, renamed, or retyped, and no item value moves. Use this instead of deleting and recreating definitions to change their order.\n\nArgs:\n - project_id (string, UUID): Project containing the fields\n - names (string[]): Every existing field name exactly once, in the order you want them. A list that is not a permutation of the current names is refused, not partially applied.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),names:o.z.array(o.z.string().min(1).max(60)).describe("Every existing field name exactly once, in the desired order")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(oi(),Vr));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Current domain name"),new_name:o.z.string().min(1).max(64).describe("New domain name"),dry_run:o.z.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(jn(),fn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Domain name to delete"),force:o.z.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:o.z.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}},za("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(jn(),fn));return t(e)})),Ua({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:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:za("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(In(),Sn));return t(e)})}),Ua({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:o.z.string().uuid().describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:o.z.string().max(64).optional().describe("Filter by domain tag"),level:o.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:o.z.string().max(1e3).optional().describe("Full-text search query"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:za("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(Cn(),En));return t(e)})}),Aa("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:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:o.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:o.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:o.z.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(Tn(),Un));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),limit:o.z.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(na(),Mn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:o.z.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(na(),Mn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(na(),Mn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:o.z.string().uuid().describe("UUID of the second (newer) baseline"),detail:o.z.boolean().default(!1).describe("Include per-item field-level diffs (default false)"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(na(),Mn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the baseline to restore from"),confirm:o.z.boolean().default(!1).describe("Set true to execute; false (default) returns a preview")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},za("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(na(),Mn));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the target project"),subtype:o.z.enum(["hara","dfmea"]).describe("Analysis subtype"),title:o.z.string().min(1).max(500).optional().describe("Analysis title"),source_req_ids:o.z.array(o.z.string().min(1).max(20)).max(50).optional().describe("Requirement IDs to seed rows from (0-50)"),revision:o.z.string().min(1).max(32).optional().describe("Revision label (default 1.0)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},za("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(Ha(),ua));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),fields:o.z.record(o.z.string().max(64),o.z.union([o.z.string().max(5e4),o.z.number()])).describe("Field name to value map (see description for allowed keys per subtype)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(Ha(),ua));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),analysis_id:o.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, DFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(Ha(),ua));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:o.z.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:o.z.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows; must be omitted for hara rows."),override:o.z.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}},za("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(Ha(),ua));return t(e)})),Aa("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:o.z.string().uuid().describe("UUID of the project"),analysis_id:o.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, DFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},za("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(Ha(),ua));return t(e)}))}});B(),$(),Ae(),M();var $a=l.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("index.cjs",document.baseURI).href)("../package.json"),Na=process.argv.slice(2)[0];(async function(){switch(Na){case"login":{const{login:e}=await Promise.resolve().then(()=>($e(),Oe));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(()=>(he(),oe));try{const{email:t,user_id:r}=await e();process.stderr.write(`\n [32m✓[0m Logged in as ${t}\n [90mUser ID: ${r}[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(()=>(ie(),J));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${$a.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");{const{getValidToken:e,readValidToken:t}=await Promise.resolve().then(()=>(he(),oe)),{runExclusiveAuth:r}=await Promise.resolve().then(()=>(Ye(),Ne)),{login:i}=await Promise.resolve().then(()=>($e(),Oe)),n=async()=>{const e=await t();if(!e)throw new Error("no valid token yet");return e},a=async()=>{try{return await e()}catch(e){return process.stderr.write(`[atoms-mcp] Could not use the saved session: ${e instanceof Error?e.message:String(e)}\n`),process.stderr.write("[atoms-mcp] Starting login flow...\n"),await i()}};try{const e=await t(),i=e?e.email:(await r(n,a)).email;process.stderr.write(`[atoms-mcp] Authenticated as ${i}\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 ye(),r=je(),i=await async function(e,t){const r=process.env.ATOMS_MCP_ORG_ID?.trim();if(r)return r;const{data:i,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):i?.org_id??null}(t,r),n=await async function(e,t,r){if(!r)return{role:null,is_member:!1,effective:C};const{data:i,error:n}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:r});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:U}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:C};const t=e,r="string"==typeof t.role?t.role:null,i=!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:r,is_member:i,effective:{read_only:s(n.read_only,C.read_only),lockdown:s(n.lockdown,C.lockdown),block_destructive:s(n.block_destructive,C.block_destructive),block_bulk_import:s(n.block_bulk_import,C.block_bulk_import),cross_project_browse:s(n.cross_project_browse,C.cross_project_browse),allowed_toolsets:a(n.allowed_toolsets,C.allowed_toolsets),forbidden_tools:a(n.forbidden_tools,C.forbidden_tools),project_scope:d,require_confirmation_for:a(n.require_confirmation_for,C.require_confirmation_for)}}}(i)}(t,r,i);e={effective:n.effective,role:n.role,org_id:i},z=e.effective,T=e.org_id,n.is_member&&i?process.stderr.write(`[atoms-mcp] Org policy loaded: org=${i.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=L(),t=N(),r=[];r.push(e?"read-only":"read+write"),null===t?r.push("all toolsets"):(r.push(`toolsets=${[...t.allowed].sort().join(",")||"(none — only always-on tools)"}`),t.unknown.length>0&&r.push(`unknown=${t.unknown.join(",")}`));const i=process.env.ATOMS_MCP_PROJECT_ID?.trim();return i&&r.push(`project_scope=${i.slice(0,8)}…`),("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN)&&r.push("lockdown=on"),r.join(" | ")}()}\n`);const{server:t}=await Promise.resolve().then(()=>(Pa(),Ca)),r=new m.StdioServerTransport;await t.connect(r),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)});
|