@atoms-tech/atoms-mcp 0.11.1 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import e,{readFile as t,mkdir as r,writeFile as i,unlink as n}from"fs/promises";import{homedir as a}from"os";import s,{join as o}from"path";import{createClient as d}from"@supabase/supabase-js";import{registerAppTool as c,registerAppResource as l,RESOURCE_MIME_TYPE as m}from"@modelcontextprotocol/ext-apps/server";import{URL as p,fileURLToPath as u}from"url";import _,{randomUUID as f,randomBytes as h,createHash as g}from"crypto";import{McpServer as y}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as b}from"zod";import{createServer as w}from"http";import{StdioServerTransport as v}from"@modelcontextprotocol/sdk/server/stdio.js";var j,x,S,k,I=Object.defineProperty,E=Object.getOwnPropertyNames,O=(e,t)=>function(){return e&&(t=(0,e[E(e)[0]])(e=0)),t},T=(e,t)=>{for(var r in t)I(e,r,{get:t[r],enumerable:!0})};function A(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of S)if(t.test(e.trim()))return"[redacted]";return e.length>k?e.slice(0,k)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>A(e,t+1));if(null!==e&&"object"==typeof e){const r={};for(const[i,n]of Object.entries(e)){const e=i.toLowerCase();j.has(e)?r[i]="[redacted]":x.has(e)?r[i]="string"==typeof n?"[content]":A(n,t+1):r[i]=A(n,t+1)}return r}return e}function H(e){return A(e)}var D,U,q,C,R,P,M,$,N,W=O({"src/middleware/audit.ts"(){j=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),x=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),S=[/^[^\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_-]+$/],k=200}}),L=O({"src/middleware/rate-limiter.ts"(){D=60,U=6e4}});function V(e){return N.get(e)}var B=O({"src/core/tool-catalog.ts"(){q=new Set(["atoms_status","atoms_list_projects"]),C=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"]),R=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain"]),P=new Set(["atoms_bulk_import"]),M={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"]},$=Object.keys(M),N=new Map;for(const[e,t]of Object.entries(M))for(const r of t)N.set(r,e)}});function F(){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)$.includes(e)?r.add(e):i.push(e);return{allowed:r,unknown:i}}function J(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function z(e){if(J()&&C.has(e))return!1;if(q.has(e))return!0;const t=F();if(null===t)return!0;const r=V(e);return!!r&&t.allowed.has(r)}var Q,G,Y,K=O({"src/middleware/tool-registry.ts"(){B()}});function Z(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?Q.test(e)?e:(G||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),G=!0),null):null}var X,ee,te=O({"src/middleware/project-scope.ts"(){Q=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,G=!1,Y=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}}}}),re=O({"src/core/types.ts"(){X={read_only:!1,lockdown:!1,block_destructive:!1,block_bulk_import:!1,cross_project_browse:!0,allowed_toolsets:["items","traceability","coverage","variables","domains"],forbidden_tools:[],project_scope:null,require_confirmation_for:[]}}});function ie(){return ee}var ne=O({"src/middleware/session-policy.ts"(){re(),ee=X}});function ae(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 se,oe,de=O({"src/core/policy.ts"(){B()}}),ce={};async function le(){try{const e=await t(oe,"utf-8"),r=JSON.parse(e);return r.access_token&&r.refresh_token?r:null}catch{return null}}async function me(e){await r(se,{recursive:!0,mode:448}),await i(oe,JSON.stringify(e,null,2),{mode:384})}async function pe(){const e=await le();return!!e&&e.expires_at>Date.now()+6e4}function ue(e){return e.expires_at>Date.now()+6e4}async function _e(){try{await n(oe)}catch{}}function fe(){return oe}T(ce,{clearCredentials:()=>_e,getCredentialsPath:()=>fe,hasValidCredentials:()=>pe,isTokenValid:()=>ue,readCredentials:()=>le,writeCredentials:()=>me});var he,ge,ye,be=O({"src/auth/token-store.ts"(){se=o(a(),".atoms"),oe=o(se,"credentials.json")}}),we={};T(we,{ATOMS_APP_URL:()=>ye,ATOMS_SUPABASE_ANON_KEY:()=>ge,ATOMS_SUPABASE_URL:()=>he});var ve=O({"src/config.ts"(){he="https://gmebjyhomsbvhrxffzre.supabase.co",ge="sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",ye=process.env.ATOMS_APP_URL??"https://atoms.tech"}}),je={};async function xe(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=Se(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await le();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=Se(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=d(he,ge),{data:i,error:n}=await r.auth.refreshSession({refresh_token:t.refresh_token});if(n||!i.session)throw new Error(`Token refresh failed: ${n?.message??"No session returned"}. Re-run 'npx @atoms-tech/atoms-mcp login'.`);const a=i.session;return await me({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 Se(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}T(je,{getValidToken:()=>xe});var ke,Ie,Ee,Oe,Te,Ae=O({"src/auth/refresh.ts"(){be(),ve()}}),He={};async function De(){if(ke)try{const e=await le();e&&e.expires_at>Te&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),Ue())}catch{}if(ke&&Oe>Date.now()+6e4)return ke;ke&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:r}=await xe(),i=e.split(".");if(3===i.length)try{const e=JSON.parse(Buffer.from(i[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());Oe=1e3*(e.exp??0)}catch{Oe=Date.now()+36e5}try{const e=await le();Te=e?.expires_at??0}catch{Te=0}const n=d(he,ge,{global:{headers:{Authorization:`Bearer ${e}`}}});return Ie=t,Ee=r,ke=n}function Ue(){ke=null,Ie=null,Ee=null,Oe=0,Te=0}function qe(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 Ce(e){try{return await e()}catch(t){if(!qe(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),Ue(),await e()}}function Re(){if(!Ie)throw new Error("Not authenticated. Call getClient() first.");return Ie}function Pe(){return Ee??""}async function Me(e,t){const r=Re(),{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}T(He,{getClient:()=>De,getUserEmail:()=>Pe,getUserId:()=>Re,invalidateClient:()=>Ue,isJwtExpiredError:()=>qe,requireWriteAccess:()=>Me,withJwtRetry:()=>Ce});var $e,Ne,We,Le,Ve,Be=O({"src/db/client.ts"(){Ae(),be(),ve(),ke=null,Ie=null,Ee=null,Oe=0,Te=0}}),Fe={};function Je(e,t=Ne){if("string"!=typeof e)return"";const r=e.replace(Le,"").replace(Ve,"");return r.length<=t?r:r.slice(0,t)+"..."}function ze(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Qe(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function Ge(e,t,r){return{total_count:e,limit:t,offset:r,has_more:r+t<e}}function Ye(e,t){return{status:"error",message:e,next_steps:t}}function Ke(e,t){return Ye(`${e} '${Je(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function Ze(e){return Ye(`${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 Xe(e){return Ye(`Validation error: ${Je(e,We)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function et(){return Ye("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 tt(){return Ye("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 Ye("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 it(e){return Ye("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 nt(e){return Ye(`Parse error: ${Je(e,We)}`,["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 at(e){const t=e instanceof Error?e.message:String(e);return/not authenticated/i.test(t)?et():/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)?tt():/rate.?limit|too many requests|429/i.test(t)?it():/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?nt(t):st(t)}function st(e){return/row.level security|permission denied for/i.test(e)?Ye("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"]):Ye(`Database error: ${Je(e,We)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function ot(e){return null==e?e:`<user_content>${e}</user_content>`}function dt(e){const t=JSON.stringify(e,null,2);if(t.length>$e&&"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 ct(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}T(Fe,{CHARACTER_LIMIT:()=>$e,accessDeniedError:()=>Ze,authError:()=>et,classifyError:()=>at,dbError:()=>st,errorResponse:()=>Ye,formatErrorResult:()=>ct,formatToolResult:()=>dt,jwtExpiredError:()=>tt,notFoundError:()=>Ke,paginationMeta:()=>Ge,parseError:()=>nt,rateLimitError:()=>it,sanitizeForEcho:()=>Je,sanitizeTagOrLevel:()=>ze,scopeError:()=>rt,success:()=>Qe,validationError:()=>Xe,wrapUserContent:()=>ot});var lt,mt=O({"src/tools/_base.ts"(){$e=25e3,Ne=50,We=200,Le=new RegExp("[\\u0000-\\u001F\\u007F]","g"),Ve=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g")}});var pt=O({"src/apps/register.ts"(){lt={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});async function ut(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 _t(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 ft(e,t){if(t.baseline_id&&t.as_of)throw new Error("baseline_id and as_of are mutually exclusive");if(t.as_of)return t.as_of;if(t.baseline_id){const{data: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 ht(e,t){const{data:r,error:i}=await e.from("baselines").select("id, project_id, name, description, snapshot_at, created_at, created_by, locked_at, locked_by, deleted_at").eq("id",t).maybeSingle();if(i)throw new Error(`getBaselineById: ${i.message}`);return r&&null===r.deleted_at?r:null}function gt(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 yt(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 bt(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.%${n}%,data->>body.ilike.%${n}%,data->>summary.ilike.%${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 wt(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")}return n}async function vt(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 jt=O({"src/db/queries.ts"(){}}),xt={};async function St(){try{const e=await Ce(async()=>{const e=await De();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=Z(),r=ie().project_scope,i=r?new Set(r):null;return dt(Qe(e.filter(e=>!t||e.id===t).filter(e=>!i||i.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 ct(at(e))}}T(xt,{listProjectsHandler:()=>St});var kt=O({"src/tools/list-projects.ts"(){Be(),jt(),te(),ne(),mt()}}),It={};async function Et(e){try{const t=await De();let r,i,n=null;try{n=await ft(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return ct(st(e.message))}if(n){const a=(await yt(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 ut(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 dt(Qe(r.map(e=>({id:e.id,title:ot(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Ge(i,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(It,{listItemsHandler:()=>Et});var Ot=O({"src/tools/list-items.ts"(){Be(),jt(),mt()}}),Tt={};async function At(e){try{const t=await De();let r=null;try{r=await ft(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return ct(Ye(e.message,["Pass baseline_id OR as_of, not both"]))}const i=r?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}(t,e.project_id,e.item_id,r).then(e=>e?gt(e):null):await _t(t,e.project_id,e.item_id);if(!i)return ct(Ke("Item",e.item_id));const n={parents:[],children:[],related:[],verified_by:[],verifies:[]};if(r){const e=i.data?.relationships??{};for(const t of Object.keys(n)){const r=e[t];Array.isArray(r)&&(n[t]=r.slice())}}else{const r=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??[]}(t,e.project_id,e.item_id);for(const t of r)if(t.from_id===e.item_id)t.type in n&&n[t.type].push(t.to_id);else{const e={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",related:"related"}[t.type]??t.type;e in n&&n[e].push(t.from_id)}}let a=[];if("test-case"===i.type)if(r)a=(i.data?.runs??[]).filter(e=>e&&"string"==typeof e.run_at).sort((e,t)=>t.run_at.localeCompare(e.run_at)).slice(0,20).map(e=>({result:e.result,run_by:e.run_by??null,run_at:e.run_at,note:e.note??null}));else{const{data:r,error:i}=await t.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&&r&&(a=r)}return dt(Qe({id:i.id,type:i.type,title:ot(i.title),summary:ot(i.data?.summary),body:ot(i.data?.body),tags:i.data?.tags??{domains:[]},ownership:i.data?.ownership??{primary:null,additional:[]},relationships:n,links:i.data?.links??[],status:i.data?.status,..."test-case"===i.type?{latest_result:a[0]?.result??"not-run",test_results:a}:{},metadata:{created_at:i.created_at,created_by:i.created_by,updated_at:i.updated_at,updated_by:i.updated_by,source_id:i.data?.metadata?.source_id}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Tt,{getItemHandler:()=>At});var Ht=O({"src/tools/get-item.ts"(){Be(),jt(),mt()}}),Dt={};async function Ut(e){try{const t=await De();let r,i,n=null;try{n=await ft(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return ct(st(e.message))}if(n){const a=await yt(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 bt(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});r=n.items,i=n.totalCount}return dt(Qe(r.map(e=>({id:e.id,title:ot(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Ge(i,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Dt,{searchHandler:()=>Ut});var qt=O({"src/tools/search.ts"(){Be(),jt(),mt()}}),Ct={};async function Rt(e){try{const t=await De(),{items:r,totalCount:i}=await async function(e,t,r,i){const{ATOMS_SUPABASE_URL:n,ATOMS_SUPABASE_ANON_KEY:a}=await Promise.resolve().then(()=>(ve(),we)),s=await fetch(`${n}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${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});return dt(Qe(r.map(e=>({id:e.id,title:ot(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Ge(i,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Ct,{semanticSearchHandler:()=>Rt});var Pt=O({"src/tools/semantic-search.ts"(){Be(),jt(),mt()}}),Mt={};async function $t(e){try{if(e.baseline_id&&e.as_of)return ct(Xe("baseline_id and as_of are mutually exclusive"));const t=await De();let r;if(e.baseline_id){const i=await ht(t,e.baseline_id);if(!i)return ct(Xe(`Baseline ${e.baseline_id} not found`));if(i.project_id!==e.project_id)return ct(Xe("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 yt(e,t,r.snapshotAt)).map(gt);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=wt(n,a),d=new Set;for(const e of o)"verifies"===e.type?d.add(e.to_id):"verified_by"===e.type&&d.add(e.from_id);return{covered:s.filter(e=>d.has(e.id)),uncovered:s.filter(e=>!d.has(e.id)),total:s.length}}(t,e.project_id,{domain:e.domain,level:e.level,snapshotAt: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 dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Mt,{getCoverageHandler:()=>$t});var Nt=O({"src/tools/get-coverage.ts"(){Be(),jt(),mt()}}),Wt={};async function Lt(e){try{const t=await De(),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 dt(Qe(i,Ge(i.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Wt,{getHistoryHandler:()=>Lt});var Vt=O({"src/tools/get-history.ts"(){Be(),jt(),mt()}}),Bt={};async function Ft(e){try{if(e.baseline_id&&e.as_of)return ct(Xe("baseline_id and as_of are mutually exclusive"));const t=await De();let r,i,n;if(e.baseline_id){const i=await ht(t,e.baseline_id);if(!i)return ct(Xe(`Baseline ${e.baseline_id} not found`));if(i.project_id!==e.project_id)return ct(Xe("Baseline does not belong to this project"));r=i.snapshot_at}else e.as_of&&(r=e.as_of);if(r){i=(await yt(t,e.project_id,r)).map(gt).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),n=wt(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=wt(i,s??[])}if(0===i.length)return dt(Qe({mermaid:"graph TD\n empty[No items in project]"}));const a=new Map;for(const e of i)a.set(e.id,e);const s=["graph TD"],o=new Set,d=new Set,c=(new Set((n??[]).filter(e=>"child"===e.type).map(e=>e.to_id)),new Set((n??[]).filter(e=>"parent"===e.type).map(e=>e.from_id)));let l;l=e.root_item_id?[e.root_item_id]:i.filter(e=>!c.has(e.id)).filter(t=>!(!e.include_tests&&"test-case"===t.type)).map(e=>e.id);const m=l.map(e=>({id:e,depth:0}));for(;m.length>0;){const{id:t,depth:r}=m.shift();if(o.has(t)||r>e.depth)continue;o.add(t);const i=a.get(t);if(!i)continue;if(!e.include_tests&&"test-case"===i.type)continue;const c=Jt(i.title),l="requirement"===i.type?`["${c}"]`:"test-case"===i.type?`(["${c}"])`:`("${c}")`;s.push(` ${t}${l}`);for(const i of n??[]){if(i.from_id!==t)continue;const n=a.get(i.to_id);if(!n)continue;if(!e.include_tests&&"test-case"===n.type)continue;const c=`${i.from_id}-${i.type}-${i.to_id}`;d.has(c)||(d.add(c),"child"===i.type?s.push(` ${t} --\x3e ${i.to_id}`):"verified_by"===i.type?s.push(` ${t} -.->|verified_by| ${i.to_id}`):"related"===i.type&&s.push(` ${t} -.- ${i.to_id}`),!o.has(i.to_id)&&r+1<=e.depth&&m.push({id:i.to_id,depth:r+1}))}}return dt(Qe({mermaid:s.join("\n"),node_count:o.size,edge_count:d.size}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}function Jt(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,50)}T(Bt,{exportMermaidHandler:()=>Ft});var zt=O({"src/tools/export-mermaid.ts"(){Be(),jt(),mt()}}),Qt={};async function Gt(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const i=(e.domains??[]).map(ze).filter(e=>e.length>0),n=void 0!==e.level?ze(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(ze).filter(e=>e.length>0)),t=i.filter(t=>!e.has(t));if(t.length>0)return ct(Xe(`Unknown domain${t.length>1?"s":""}: ${t.join(", ")}. Registered: ${n.join(", ")}. Add new domains via Taxonomy Management in the ATOMS web app first.`))}}const a=await vt(t,e.project_id,e.type),s=(new Date).toISOString(),o={id:a,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:[]},links:[],metadata:{created_at:s,created_by:r,updated_at:s,updated_by:r}},{error:d}=await t.from("items").insert({id:a,project_id:e.project_id,type:e.type,title:e.title,data:o,created_by:r,updated_by:r}).select().single();if(d)throw new Error(d.message);if(e.parent_ids&&e.parent_ids.length>0){const i=e.parent_ids.map(t=>({from_id:a,to_id:t,type:"parent",project_id:e.project_id}));await t.from("item_relationships").insert(i).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: relationship sync failed: ${e.message}\n`)});const{data:n,error:s}=await t.from("items").select("id, data").eq("project_id",e.project_id).in("id",e.parent_ids);if(s)process.stderr.write(`[atoms-mcp] Warning: parent JSONB read failed: ${s.message}\n`);else for(const i of n??[]){const n=JSON.parse(JSON.stringify(i.data??{}));n.relationships=n.relationships??{};const s=Array.isArray(n.relationships.children)?n.relationships.children:[];if(!s.includes(a)){n.relationships.children=[...s,a];const{error:o}=await t.from("items").update({data:n,updated_by:r}).eq("id",i.id).eq("project_id",e.project_id);o&&process.stderr.write(`[atoms-mcp] Warning: parent JSONB write failed for ${i.id}: ${o.message}\n`)}}}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:o,actor:"mcp_claude",session_id:Ti()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===e.echo?dt(Qe({id:a,type:e.type})):dt(Qe({id:a,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",domains:i,level:n??"",project_id:e.project_id}))}catch(e){return ct(at(e))}}T(Qt,{createItemHandler:()=>Gt});var Yt=O({"src/tools/create-item.ts"(){Be(),jt(),Di(),mt()}}),Kt={};async function Zt(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const i=async(i,n,a,s)=>{const o=await _t(t,e.project_id,i);if(!o)return{updated_fields:[],error:`Item "${i}" not found`};const d=void 0!==n.domains?n.domains.map(ze).filter(e=>e.length>0):void 0,c=void 0!==n.level?ze(n.level):void 0;if(void 0!==d&&d.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(ze).filter(e=>e.length>0)),t=d.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const l={...o.data},m={...o.data},p=[],u=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==n.title&&u(o.data.title,n.title)&&(m.title=n.title,p.push("title")),void 0!==n.body&&u(o.data.body,n.body)&&(m.body=n.body,p.push("body")),void 0!==n.summary&&u(o.data.summary,n.summary)&&(m.summary=n.summary,p.push("summary")),void 0!==d&&u(o.data.tags?.domains??[],d)&&(m.tags={...m.tags,domains:d},p.push("domains")),void 0!==c&&u(o.data.tags?.level,c)&&(m.tags={...m.tags,level:c},p.push("level")),void 0!==n.status&&u(o.data.status,n.status)&&(m.status=n.status,p.push("status")),0===p.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};m.metadata={...m.metadata,updated_at:(new Date).toISOString(),updated_by:r};const{data:_,error:f}=await t.from("items").update({title:n.title??o.title,data:m,updated_by:r}).eq("id",i).eq("project_id",e.project_id).select("id");if(f)return{updated_fields:[],error:f.message};if(!_||0===_.length)return{updated_fields:[],error:`Update silently failed for "${i}" — 0 rows affected. Likely RLS policy denied the write; verify your role and project access.`};const h={item_id:i,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:l,new_data:m,actor:"mcp_claude",session_id:Ti()};return a&&(h.batch_id=a),s&&(h.reason=s),await t.from("change_history").insert(h).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),{updated_fields:p,updatedData:m,itemType:o.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),r=!0===e.continue_on_error,n=[],a=[];for(const s of e.updates){const{updated_fields:o,error:d}=await i(s.item_id,s,t,e.reason);if(d){if(!r)return ct(Xe(`Batch stopped at "${s.item_id}": ${d}. ${n.length} item(s) already updated.`));a.push({item_id:s.item_id,error:d})}else n.push({id:s.item_id,updated_fields:o})}return dt(Qe({batch_id:t,updated:n.length,results:!1===e.echo?void 0:n,errors:a}))}if(!e.item_id)return ct(Xe("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:n,updatedData:a,itemType:s,error:o}=await i(e.item_id,{title:e.title,body:e.body,summary:e.summary,domains:e.domains,level:e.level,status:e.status},void 0,e.reason);if(o)return o.includes("not found")?ct(Ke("Item",e.item_id)):o.includes("Unknown domain")?ct(Xe(o)):ct(st(o));if(!1===e.echo)return dt(Qe({id:e.item_id,updated_fields:n}));const d=a??{};return dt(Qe({id:e.item_id,type:s,title:d.title??"",summary:d.summary??"",body:d.body??"",domains:d.tags?.domains??[],level:d.tags?.level??"",updated_fields:n}))}catch(e){return ct(at(e))}}T(Kt,{updateItemHandler:()=>Zt});var Xt,er,tr=O({"src/tools/update-item.ts"(){Be(),jt(),Di(),mt()}});function rr(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!!ie().require_confirmation_for.includes(e)}function ir(e,t=Xt){const r=Date.now()+t,i={...e,exp:r},n=Buffer.from(JSON.stringify(i)).toString("base64url");return{token:`${n}.${_.createHmac("sha256",er).update(n).digest("base64url")}`,expires_at:new Date(r).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function nr(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=_.createHmac("sha256",er).update(r).digest("base64url"),a=Buffer.from(i,"utf8"),s=Buffer.from(n,"utf8");if(a.length!==s.length||!_.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 ar(e){if(Array.isArray(e))return e.map(ar);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e).sort())t[r]=ar(e[r]);return t}return e}function sr(e){const t=JSON.stringify(ar(e));return _.createHash("sha256").update(t).digest("base64url").slice(0,16)}var or,dr=O({"src/middleware/confirmation.ts"(){ne(),Xt=6e4,er=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:_.randomBytes(32).toString("base64url")})()}}),cr={};async function lr(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const i=await _t(t,e.project_id,e.item_id);if(!i)return ct(Ke("Item",e.item_id));if(rr(or)){const t={tool:or,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const r=ir(t);return dt(Qe({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=nr(e.confirmation_token,t);if(!r.valid)return ct(Xe(`confirmation_token rejected: ${r.reason}`))}const{error:n}=await t.from("items").update({deleted_at:(new Date).toISOString()}).eq("id",e.item_id).eq("project_id",e.project_id);if(n)throw new Error(n.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:r,event_type:"deleted",old_data:i.data,new_data:null,actor:"mcp_claude",session_id:Ti()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),dt(Qe({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 ct(at(e))}}T(cr,{deleteItemHandler:()=>lr});var mr=O({"src/tools/delete-item.ts"(){Be(),jt(),Di(),dr(),mt(),or="atoms_delete_item"}}),pr={};async function ur(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("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 ct(Ke("Item",e.item_id));if(!i.deleted_at)return ct(Ye(`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.from("items").update({deleted_at:null}).eq("id",e.item_id).eq("project_id",e.project_id);if(a)throw new Error(a.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:"mcp_claude",session_id:Ti()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),dt(Qe({id:e.item_id,title:i.title,type:i.type,restored:!0,message:`Item ${e.item_id} restored successfully.`}))}catch(e){return ct(at(e))}}T(pr,{restoreItemHandler:()=>ur});var _r,fr,hr=O({"src/tools/restore-item.ts"(){Be(),Di(),mt()}}),gr={};async function yr(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const i=async(i,n,a)=>{const s=await _t(t,e.project_id,i.from_id);if(!s)throw new Error(`Item "${i.from_id}" not found`);const o=await _t(t,e.project_id,i.to_id);if(!o)throw new Error(`Item "${i.to_id}" not found`);const d=_r(i.type);if("add"===i.action){const{data:n}=await t.from("item_relationships").select("from_id").eq("from_id",i.from_id).eq("to_id",i.to_id).eq("type",i.type).eq("project_id",e.project_id).maybeSingle();if(!n){const{error:r}=await t.from("item_relationships").insert({from_id:i.from_id,to_id:i.to_id,type:i.type,project_id:e.project_id});if(r)throw new Error(r.message)}const a=JSON.parse(JSON.stringify(s.data));a.relationships=a.relationships??{};const c=a.relationships[fr(i.type)]??[];c.includes(i.to_id)||(a.relationships[fr(i.type)]=[...c,i.to_id]),await t.from("items").update({data:a,updated_by:r}).eq("id",i.from_id).eq("project_id",e.project_id);const l=JSON.parse(JSON.stringify(o.data));l.relationships=l.relationships??{};const m=l.relationships[fr(d)]??[];m.includes(i.from_id)||(l.relationships[fr(d)]=[...m,i.from_id]),await t.from("items").update({data:l,updated_by:r}).eq("id",i.to_id).eq("project_id",e.project_id)}else{await Promise.all([t.from("item_relationships").delete().eq("from_id",i.from_id).eq("to_id",i.to_id).eq("type",i.type).eq("project_id",e.project_id),t.from("item_relationships").delete().eq("from_id",i.to_id).eq("to_id",i.from_id).eq("type",d).eq("project_id",e.project_id)]);const n=JSON.parse(JSON.stringify(s.data));n.relationships?.[fr(i.type)]&&(n.relationships[fr(i.type)]=n.relationships[fr(i.type)].filter(e=>e!==i.to_id)),await t.from("items").update({data:n,updated_by:r}).eq("id",i.from_id).eq("project_id",e.project_id);const a=JSON.parse(JSON.stringify(o.data));a.relationships?.[fr(d)]&&(a.relationships[fr(d)]=a.relationships[fr(d)].filter(e=>e!==i.from_id)),await t.from("items").update({data:a,updated_by:r}).eq("id",i.to_id).eq("project_id",e.project_id)}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:"mcp_claude",session_id:Ti()};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 ct(Xe(`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 ct(Ke("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 ct(Xe(`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 dt(Qe({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?ct(Xe("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},void 0,e.reason),!1===e.echo?dt(Qe({action:e.action,from_id:e.from_id,to_id:e.to_id})):dt(Qe({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}`}))):ct(Xe("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."))}catch(e){return ct(at(e))}}T(gr,{linkItemsHandler:()=>yr});var br=O({"src/tools/link-items.ts"(){Be(),jt(),Di(),mt(),_r=e=>"parent"===e?"child":"child"===e?"parent":"verifies"===e?"verified_by":"verified_by"===e?"verifies":"related",fr=e=>"parent"===e?"parents":"child"===e?"children":e}}),wr={};async function vr(e){try{if(!e.items||0===e.items.length)return ct(Xe("items array must contain at least 1 item"));if(e.items.length>100)return ct(Xe(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}if(rr("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:sr(e.items)};if(!e.confirmation_token){const r=ir(t),i={};for(const t of e.items)i[t.type]=(i[t.type]??0)+1;return dt(Qe({status:"confirmation_required",preview:{total_items:e.items.length,by_type:i,sample_titles:e.items.slice(0,5).map(e=>e.title)},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 will invalidate the token.`}))}const r=nr(e.confirmation_token,t);if(!r.valid)return ct(Xe(`confirmation_token rejected: ${r.reason}`))}const i=(new Date).toISOString(),n=Ti(),a=[],s=[],{data:o}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),d=o?.domains??[],c=d.length>0?new Set(d.map(ze).filter(e=>e.length>0)):null,l=[];for(let r=0;r<e.items.length;r++){const i=e.items[r],n=(i.domains??[]).map(ze).filter(e=>e.length>0),a=void 0!==i.level?ze(i.level):void 0;if(c&&n.length>0){const e=n.filter(e=>!c.has(e));if(e.length>0){s.push({index:r,title:i.title,error:`Unknown domain${e.length>1?"s":""}: ${e.join(", ")}. Registered: ${d.join(", ")}.`});continue}}try{const s=await vt(t,e.project_id,i.type);l.push({itemId:s,input:i,sanitizedDomains:n,sanitizedLevel:a,index:r})}catch(e){s.push({index:r,title:i.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===l.length)return dt(Qe({created:0,items:[],errors:s}));const m=[],p=new Map;for(const{itemId:t,input:n,sanitizedDomains:a,sanitizedLevel:s}of l){const o={id:t,type:n.type,title:n.title,summary:n.summary,body:n.body,tags:{domains:a,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:n.parent_id?[n.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:i,created_by:r,updated_at:i,updated_by:r}};p.set(t,o),m.push({id:t,project_id:e.project_id,type:n.type,title:n.title,data:o,created_by:r,updated_by:r})}const{error:u}=await t.from("items").insert(m);if(u)for(const{itemId:e,input:r,index:i}of l){const n=m.find(t=>t.id===e);if(!n)continue;const{error:o}=await t.from("items").insert(n);o?s.push({index:i,title:r.title,error:o.message}):a.push({id:e,title:r.title,type:r.type})}else for(const{itemId:e,input:t}of l)a.push({id:e,title:t.title,type:t.type});const _=l.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>a.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}));if(_.length>0){await t.from("item_relationships").insert(_).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk relationship sync failed: ${e.message}\n`)});const i=new Map;for(const e of _){const t=i.get(e.to_id)??[];t.push(e.from_id),i.set(e.to_id,t)}const n=Array.from(i.keys()),{data:a,error:s}=await t.from("items").select("id, data").eq("project_id",e.project_id).in("id",n);if(s)process.stderr.write(`[atoms-mcp] Warning: bulk parent JSONB read failed: ${s.message}\n`);else for(const n of a??[]){const a=JSON.parse(JSON.stringify(n.data??{}));a.relationships=a.relationships??{};const s=Array.isArray(a.relationships.children)?a.relationships.children:[],o=i.get(n.id)??[],d=Array.from(new Set([...s,...o]));if(d.length!==s.length){a.relationships.children=d;const{error:i}=await t.from("items").update({data:a,updated_by:r}).eq("id",n.id).eq("project_id",e.project_id);i&&process.stderr.write(`[atoms-mcp] Warning: bulk parent JSONB write failed for ${n.id}: ${i.message}\n`)}}}const f=a.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:"mcp_claude",session_id:n}));return f.length>0&&await t.from("change_history").insert(f).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)}),dt(Qe({created:a.length,items:a,errors:s.length>0?s:[],project_id:e.project_id}))}catch(e){return ct(at(e))}}T(wr,{bulkImportHandler:()=>vr});var jr=O({"src/tools/bulk-import.ts"(){Be(),jt(),Di(),dr(),mt()}}),xr={};async function Sr(e){try{const t=await De(),r=Re(),i=Pe();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const n=await _t(t,e.project_id,e.item_id);if(!n)return ct(Ke("Item",e.item_id));if("test-case"!==n.type)return ct(Xe(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const a=(e.asset??"").trim();let s=null,o=!1;if(a){const{data:i,error:n}=await t.from("assets").select("id").eq("project_id",e.project_id).eq("name",a).is("archived_at",null).maybeSingle();if(n)throw new Error(n.message);if(i)s=i.id;else{const{data:i,error:n}=await t.from("assets").insert({project_id:e.project_id,name:a,created_by:r}).select("id").single();if(n){if("23505"!==n.code)throw new Error(n.message);{const{data:r,error:i}=await t.from("assets").select("id").eq("project_id",e.project_id).eq("name",a).is("archived_at",null).single();if(i)throw new Error(i.message);s=r.id}}else s=i.id,o=!0}}const d=(new Date).toISOString(),{error:c}=await t.from("test_results").insert({item_id:e.item_id,project_id:e.project_id,result:e.result,run_by:i||r,run_at:d,note:e.note??null,asset:a||null});if(c)throw new Error(c.message);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:d,note:e.note,asset:a||null},actor:"mcp_claude",session_id:Ti()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const l=a?` (asset: ${a})`:"";return dt(Qe({item_id:e.item_id,result:e.result,run_at:d,run_by:i||r,note:e.note??null,asset:a||null,asset_id:s,asset_created:o,message:`Test result '${e.result}' recorded for ${e.item_id}${l}`}))}catch(e){return ct(at(e))}}T(xr,{recordTestResultHandler:()=>Sr});var kr=O({"src/tools/record-test-result.ts"(){Be(),jt(),Di(),mt()}}),Ir={};async function Er(e){try{const t=await De(),r=Re(),i=Pe();if(!Array.isArray(e.results)||0===e.results.length)return ct(Xe("results must be a non-empty array"));if(e.results.length>100)return ct(Xe(`results must have at most 100 entries (got ${e.results.length})`));try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const n=await _t(t,e.project_id,e.item_id);if(!n)return ct(Ke("Item",e.item_id));if("test-case"!==n.type)return ct(Xe(`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:"mcp_claude",session_id:Ti()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),dt(Qe({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 ct(at(e))}}T(Ir,{recordTestResultsBulkHandler:()=>Er});var Or,Tr,Ar,Hr,Dr=O({"src/tools/record-test-results-bulk.ts"(){Be(),jt(),Di(),mt()}}),Ur={};async function qr(e){try{const t=Math.min(Math.max(e.depth??5,1),10),r=await De(),i=await _t(r,e.project_id,e.item_id);if(!i)return ct(Ke("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=wt(n??[],s??[]),c=new Map;for(const e of n??[])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})},p=e.relationship_types?new Set(e.relationship_types):null;for(const t of d??[]){const r=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(Tr.includes(r)&&(p&&!p.has(r)||m(t.from_id,t.to_id,r)),Ar.includes(r))){const e=Hr[r]??r;p&&!p.has(e)||m(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(Ar.includes(r)&&(p&&!p.has(r)||m(t.from_id,t.to_id,r)),Tr.includes(r))){const e=Hr[r]??r;p&&!p.has(e)||m(t.to_id,t.from_id,e)}"related"===r&&(p&&!p.has("related")||(m(t.from_id,t.to_id,"related"),m(t.to_id,t.from_id,"related")))}const u=new Set;u.add(e.item_id);const _=[],f=[],h=[],g=l.get(e.item_id)??[];for(const t of g)h.push({id:t.neighbor,depth:1,relType:t.relType,from:e.item_id});for(;h.length>0&&_.length<Or;){const{id:e,depth:r,relType:i,from:n}=h.shift();if(u.has(e)||r>t)continue;u.add(e);const a=c.get(e);if(a&&(_.push({id:e,title:a.title,type:a.type,relationship:i,depth:r,from:n}),f.push({from:n,to:e,type:i}),r<t)){const t=l.get(e)??[];for(const i of t)u.has(i.neighbor)||h.push({id:i.neighbor,depth:r+1,relType:i.relType,from:e})}}const y=c.get(e.item_id),b=y?{id:e.item_id,title:y.title,type:y.type,relationship:"root",depth:0,from:e.item_id}:{id:e.item_id,title:i.title??e.item_id,type:i.type??"unknown",relationship:"root",depth:0,from:e.item_id};return dt(Qe({root:e.item_id,direction:e.direction,depth_limit:t,items:[b,..._],edges:f,total_count:_.length+1,..._.length>=Or?{truncated:!0,truncation_message:`Results capped at ${Or} items. Use a smaller depth or filter by relationship_types.`}:{}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Ur,{traceHandler:()=>qr});var Cr=O({"src/tools/trace.ts"(){Be(),jt(),mt(),Or=200,Tr=["parent","verifies"],Ar=["child","verified_by"],Hr={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related"}}}),Rr={};async function Pr(e){try{let t=(await De()).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 dt(Qe({assets:r||[],total:(r||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Rr,{listAssetsHandler:()=>Pr});var Mr=O({"src/tools/assets.ts"(){Be(),mt()}}),$r={};async function Nr(e){try{const t=await De(),{data:r,error:i}=await t.from("project_variables").select("*").eq("project_id",e.project_id).order("name");if(i)throw new Error(i.message);return dt(Qe({variables:r||[],total:(r||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Wr(e){try{const t=await De(),{data:r,error:i}=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(i)throw new Error(i.message);if(!r)return ct(Ke("Variable",e.variable_name));const{data:n}=await t.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null),a=`{${e.variable_name}}`,s=(n||[]).filter(e=>(e.data?.body||"").includes(a));return dt(Qe({variable:r,referenced_by:s.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:s.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Lr(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}if(!(await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle()).data)return ct(Ke("Variable",e.variable_name));const i={updated_by:r,updated_at:(new Date).toISOString()};void 0!==e.value&&(i.value=e.value),void 0!==e.unit&&(i.unit=e.unit||null),void 0!==e.description&&(i.description=e.description||null);const{data:n,error:a}=await t.from("project_variables").update(i).eq("project_id",e.project_id).eq("name",e.variable_name).select().single();if(a)throw new Error(a.message);return dt(Qe({variable:n}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Vr(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("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 ct(Xe(`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 ct(Xe(`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 ct(Xe(`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})),{data:l,error:m}=await t.from("project_variables").insert(c).select();if(m)throw new Error(m.message);return dt(Qe({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 ct(Xe("Provide either (name, value) for single variable or variables[] for batch."));if(!i.test(e.name))return ct(Xe(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const{data:n,error:a}=await t.from("project_variables").insert({project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null,created_by:r,updated_by:r}).select().single();if(a){if(a.message.includes("unique")||a.message.includes("duplicate"))return ct(Xe(`Variable "${e.name}" already exists in this project.`));throw new Error(a.message)}return!1===e.echo?dt(Qe({name:e.name})):dt(Qe({variable:n,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Br(e){try{const t=await De();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{data:r}=await t.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!r)return ct(Ke("Variable",e.name));const{data:i}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->>body","ilike",`%{${e.name}}%`),n=(i??[]).length;if(n>0&&!e.force)return ct(Xe(`Variable "${e.name}" is referenced in ${n} item${n>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(rr("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const r=ir(t);return dt(Qe({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:n,would_orphan_references:n>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=nr(e.confirmation_token,t);if(!r.valid)return ct(Xe(`confirmation_token rejected: ${r.reason}`))}const{error:a}=await t.from("project_variables").delete().eq("project_id",e.project_id).eq("name",e.name);if(a)throw new Error(a.message);return dt(Qe({deleted:!0,name:e.name,referenced_by_items:n,warning:n>0?`${n} item${n>1?"s":""} still contain {${e.name}} — those references are now unresolved.`:void 0}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T($r,{createVariableHandler:()=>Vr,deleteVariableHandler:()=>Br,getVariableHandler:()=>Wr,listVariablesHandler:()=>Nr,updateVariableHandler:()=>Lr});var Fr=O({"src/tools/variables.ts"(){Be(),dr(),mt()}}),Jr={};async function zr(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 Gr(e){try{const t=await De(),{domains:r}=await zr(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 dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Yr(e){try{const t=await De();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{domains:r,levels:i}=await zr(t,e.project_id),n=e.name.trim().toLowerCase();return n?r.includes(n)?ct(Xe(`Domain "${n}" already exists in this project.`)):(await Qr(t,e.project_id,[...r,n],i),dt(Qe({domain:{name:n},message:`Domain "${n}" registered. You can now tag items with domains=["${n}"].`}))):ct(Xe("Domain name cannot be empty."))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Kr(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{domains:i,levels:n}=await zr(t,e.project_id),a=e.name.trim().toLowerCase(),s=e.new_name.trim().toLowerCase();if(!s)return ct(Xe("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 ct(Ke("Domain",a))}if(s!==a&&i.includes(s))return ct(Xe(`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 dt(Qe({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;return m=o?i.map(e=>e===a?s:e):i.includes(s)?i:[...i,s],await Qr(t,e.project_id,m,n),(new Date).toISOString(),await Promise.all((d??[]).map(i=>{const n=(i.data?.tags?.domains??[]).map(e=>e===a?s:e),o={...i.data,tags:{...i.data?.tags??{},domains:n}};return t.from("items").update({data:o,updated_by:r}).eq("id",i.id).eq("project_id",e.project_id)})),dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Zr(e){try{const t=await De(),r=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{domains:i,levels:n}=await zr(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 ct(Ke("Domain",a));if(c>0&&!e.force)return ct(Xe(`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(rr("atoms_delete_domain")){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:a};if(!e.confirmation_token){const e=ir(t);return dt(Qe({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=nr(e.confirmation_token,t);if(!r.valid)return ct(Xe(`confirmation_token rejected: ${r.reason}`))}const l=s?i.filter(e=>e!==a):i;return await Qr(t,e.project_id,l,n),(new Date).toISOString(),c>0&&await Promise.all((o??[]).map(i=>{const n={...i.data,tags:{...i.data?.tags??{},domains:(i.data?.tags?.domains??[]).filter(e=>e!==a)}};return t.from("items").update({data:n,updated_by:r}).eq("id",i.id).eq("project_id",e.project_id)})),dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Jr,{createDomainHandler:()=>Yr,deleteDomainHandler:()=>Zr,listDomainsHandler:()=>Gr,updateDomainHandler:()=>Kr});var Xr=O({"src/tools/domains.ts"(){Be(),dr(),mt()}}),ei={};async function ti(e){try{const t=await De(),{data:r,error:i}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle();if(i)throw new Error(i.message);if(!r)return ct(Ke("Project",e.project_id));const{data:n,error:a}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);const s=n??[],o={requirements:0,test_cases:0,notes:0},d=[],c=[];for(const e of s)if("requirement"===e.type){o.requirements++;const t=e.data?.tags?.domains??[];c.push({id:e.id,domains:t})}else"test-case"===e.type?(o.test_cases++,d.push(e.id)):"note"===e.type&&o.notes++;const l={passed:0,failed:0,blocked:0,not_run:0};if(d.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 d){const t=n.get(e);t&&"not-run"!==t?"passed"===t?l.passed++:"failed"===t?l.failed++:"blocked"===t?l.blocked++:l.not_run++:l.not_run++}}const{data:m,error:p}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(p)throw new Error(p.message);const u=wt(n??[],m??[]),_=new Set;for(const e of u)"verifies"===e.type?_.add(e.to_id):"verified_by"===e.type&&_.add(e.from_id);const f=c.filter(e=>_.has(e.id)).length,h=c.length,g={covered:f,uncovered:h-f,total:h,percent:h>0?Math.round(f/h*1e3)/10:100},y=new Map;for(const e of c){const t=e.domains.length>0?e.domains:["(untagged)"],r=_.has(e.id);for(const e of t){y.has(e)||y.set(e,{covered:0,total:0});const t=y.get(e);t.total++,r&&t.covered++}}const b=Array.from(y.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})),w=new Date;w.setDate(w.getDate()-7);const{count:v,error:j}=await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",w.toISOString());if(j)throw new Error(j.message);return dt(Qe({project_id:e.project_id,project_name:r.name,counts:o,test_status:l,coverage:g,coverage_by_domain:b,recent_changes:v??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(ei,{projectSummaryHandler:()=>ti});var ri,ii=O({"src/tools/project-summary.ts"(){Be(),jt(),mt()}}),ni={};async function ai(e){try{const t=await De();let r,i;if(e.query&&e.query.trim().length>0){const n=await bt(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 ut(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 dt(Qe({items:r,filters:{domains:n.domains,levels:n.levels,types:ri},project_id:e.project_id},Ge(i,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(ni,{browseHandler:()=>ai});var si,oi,di,ci,li=O({"src/tools/browse.ts"(){Be(),jt(),mt(),ri=["requirement","test-case","note","table"]}}),mi={};async function pi(e){try{const t=e.direction??"downstream",r=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,i=await De(),n=await _t(i,e.project_id,e.item_id);if(!n)return ct(Ke("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||(oi.includes(r)&&m(e.from_id,e.to_id,r),di.includes(r)&&m(e.to_id,e.from_id,ci[r]??r)),"downstream"!==t&&"both"!==t||(di.includes(r)&&m(e.from_id,e.to_id,r),oi.includes(r)&&m(e.to_id,e.from_id,ci[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<si;){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:ot(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>=si)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:ot(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 dt(Qe({root:{item_id:e.item_id,title:ot(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>=si?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(mi,{impactAnalysisHandler:()=>pi});var ui=O({"src/tools/impact-analysis.ts"(){Be(),jt(),mt(),si=200,oi=["parent","verifies","traces_to","allocated_from","decomposed_from"],di=["child","verified_by","allocated_to","decomposes_to","traced_by"],ci={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"}}}),_i={};function fi(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):null}async function hi(e,t,r){const{data:i,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n)return ct(st(n.message));if(!i)return ct(Ke("Project",t));const{data:a,error:s}=await e.from("organizations").select("feature_flags").eq("id",i.org_id).maybeSingle();return s?ct(st(s.message)):!0!==(a?.feature_flags??{})[r]?ct(Ye(`Feature '${r}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function gi(e){try{const t=await De(),r=await async function(e,t){const{data:r,error:i}=await e.from("baselines").select("id, project_id, name, description, snapshot_at, created_at, created_by, locked_at, locked_by").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1});if(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 dt(Qe({baselines:r.slice(i,i+n).map(e=>({id:e.id,name:e.name,description:e.description,snapshot_at:e.snapshot_at,created_at:e.created_at,created_by:e.created_by,locked:null!==e.locked_at,locked_at:e.locked_at})),total:r.length,offset:i,limit:n}))}catch(e){return fi(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function yi(e){try{const t=await De(),r=await hi(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?ct(Ye(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):ct(st(n.message)):dt(Qe({id:i.id,name:i.name,description:i.description,snapshot_at:i.snapshot_at,created_at:i.created_at,locked:!1}))}catch(e){return fi(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function bi(e){try{const t=await De(),r=await ht(t,e.baseline_id);if(!r)return ct(Ke("Baseline",e.baseline_id));const i=await hi(t,r.project_id,"baselines_enabled");if(i)return i;if(null!==r.locked_at)return ct(Ye("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 ct(Ke("Project",r.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return ct(et());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 ct(Ye("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?ct(st(c.message)):dt(Qe({id:d.id,locked_at:d.locked_at,locked_by:d.locked_by}))}catch(e){return fi(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function wi(e){try{const t=await De(),[r,i]=await Promise.all([ht(t,e.baseline_a_id),ht(t,e.baseline_b_id)]);if(!r||!i)return ct(Ke("Baseline","one of the baseline_ids"));if(r.project_id!==i.project_id)return ct(Ye("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[n,a]=await Promise.all([yt(t,r.project_id,r.snapshot_at),yt(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 dt(Qe({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 fi(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function vi(e){try{const t=await De(),r=await ht(t,e.baseline_id);if(!r)return ct(Ke("Baseline",e.baseline_id));const i=await hi(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 ct(Ke("Project",r.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return ct(et());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 ct(Ye("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const d=await yt(t,r.project_id,r.snapshot_at);if(!0!==e.confirm)return dt(Qe({preview:!0,items_to_restore:d.length}));if(0===d.length)return dt(Qe({ok:!0,items_restored:0}));const c=d.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{data:l,error:m}=await t.rpc("bulk_save_items_with_revisions",{p_project_id:r.project_id,p_items:c,p_user_id:s,p_event_source:"restore"});return m?ct(st(m.message)):dt(Qe({ok:!0,items_restored:"number"==typeof l?l:d.length}))}catch(e){return fi(e)??ct(st(e instanceof Error?e.message:String(e)))}}T(_i,{createBaselineHandler:()=>yi,diffBaselinesHandler:()=>wi,listBaselinesHandler:()=>gi,lockBaselineHandler:()=>bi,restoreBaselineHandler:()=>vi});var ji,xi,Si,ki,Ii=O({"src/tools/baselines.ts"(){Be(),mt(),jt()}});function Ei(t){z(t.toolName)&&function(t,r){const i=`ui://${r.toolName}/${r.htmlFile}`,n=function(e,t){const r=u(import.meta.url),i=s.dirname(r);return s.resolve(i,"apps","src","apps",e,t)}(r.appName,r.htmlFile),a=[...lt.resourceDomains,...r.extraResourceDomains??[]];c(t,r.toolName,{title:r.title,description:r.description,inputSchema:r.inputSchema,annotations:r.annotations,_meta:{ui:{resourceUri:i}}},r.handler),l(t,`${r.title} UI`,i,{mimeType:m},async()=>{const t=await e.readFile(n,"utf-8");return{contents:[{uri:i,mimeType:m,text:t,_meta:{ui:{csp:{resourceDomains:a}}}}]}})}(ji,t)}function Oi(e,t){return async r=>{const i=function(e,t){if(q.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&&C.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&R.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&P.has(t))return{allowed:!1,reason:"block_bulk_import"};const r=V(t);return void 0===r||e.allowed_toolsets.includes(r)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}(ie(),e);if(!i.allowed)return ct(Ye(`Tool ${e} is blocked by org policy.`,[ae(i.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=Z();if(!t)return;if("object"!=typeof e||null===e)return;const r=e.project_id;if("string"==typeof r&&r!==t)throw new Y(t,r)}(r)}catch(e){if(e instanceof Y)return ct(rt(e.expectedProjectId));throw e}{const e=ie(),t=r?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return ct(Ye("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 De(),n=Re()}catch{return t(r)}const s=await async function(e,t){const r=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||D,i=new Date,n=new Date(i.getTime()-U);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())+U-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*U);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 ct(it(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(()=>(Be(),He));await t(a,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(mt(),Fe));return ct(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:Si,client_name:ki};try{!function(e,t,r){const i=H(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 De(),n,t)}catch{}}}}function Ti(){return Si}var Ai,Hi,Di=O({"src/server.ts"(){W(),L(),K(),te(),ne(),de(),Be(),mt(),pt(),ji=new y({name:"atoms-mcp-server",version:"0.11.1"}),xi=(e,t,r)=>{if(z(e))return ji.registerTool(e,t,r)},Si=f(),ki=process.env.ATOMS_CLIENT_NAME??"unknown",xi("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(()=>(be(),ce)),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(()=>(Ae(),je)),{email:t}=await e(),{invalidateClient:r}=await Promise.resolve().then(()=>(Be(),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)}]}}}),xi("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}},Oi("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(kt(),xt));return e()})),xi("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:b.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:b.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:b.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:b.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:b.number().int().min(0).default(0).describe("Pagination offset (default 0)"),baseline_id:b.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:b.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}},Oi("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(Ot(),It));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:b.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:b.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}},Oi("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(Ht(),Tt));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),query:b.string().min(1).max(1e3).describe("Search text"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),asset:b.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:b.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:b.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}},Oi("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(qt(),Dt));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),query:b.string().min(1).max(1e3).describe("Natural-language concept query"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:b.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(Pt(),Ct));return t(e)})),Ei({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:b.string().uuid().describe("UUID of the project"),domain:b.string().max(64).optional().describe("Filter by domain tag"),level:b.string().max(32).optional().describe("Filter by level"),baseline_id:b.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:b.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Oi("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(Nt(),Mt));return t(e)})}),xi("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_claude) 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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID"),limit:b.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(Vt(),Wt));return t(e)})),Ei({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:b.string().uuid().describe("UUID of the project"),root_item_id:b.string().max(20).optional().describe("Root item ID to start from"),depth:b.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:b.boolean().default(!0).describe("Include test case links"),baseline_id:b.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:b.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},extraResourceDomains:["cdn.jsdelivr.net","mermaid.ink"],handler:Oi("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(zt(),Bt));return t(e)})}),xi("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\nReturns:\n Created item with generated ID (e.g., \"REQ-058\")\n\nSide effects:\n - Logs to change_history with actor='mcp_claude'\n - Creates relationships if parent_ids provided",inputSchema:{project_id:b.string().uuid().describe("UUID of the target project"),type:b.enum(["requirement","test-case","note"]).describe("Item type"),title:b.string().min(1).max(500).describe("Item title"),body:b.string().max(5e4).optional().describe("Rich text body"),summary:b.string().max(2e3).optional().describe("Brief summary"),domains:b.array(b.string().max(64)).max(20).optional().describe("Domain tags"),level:b.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:b.array(b.string().max(20)).max(50).optional().describe("Parent item IDs to link"),echo:b.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Oi("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Yt(),Qt));return t(e)})),xi("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\nReturns:\n Updated item.",inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).optional().describe("Item ID (single form)"),title:b.string().min(1).max(500).optional().describe("New title"),body:b.string().max(5e4).optional().describe("New body"),summary:b.string().max(2e3).optional().describe("New summary"),domains:b.array(b.string().max(64)).max(20).optional().describe("New domain tags"),level:b.string().max(32).optional().describe("New level"),status:b.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status"),echo:b.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:b.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:b.array(b.object({item_id:b.string().min(1).max(20),title:b.string().min(1).max(500).optional(),body:b.string().max(5e4).optional(),summary:b.string().max(2e3).optional(),domains:b.array(b.string().max(64)).max(20).optional(),level:b.string().max(32).optional(),status:b.enum(["passed","failed","blocked","not-run"]).optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:b.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:b.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(tr(),Kt));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:b.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}},Oi("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(mr(),cr));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().max(256).describe("ID of the soft-deleted item to restore")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(hr(),pr));return t(e)})),xi("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\nReturns:\n Updated relationship state for both items.",inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),from_id:b.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:b.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:b.enum(["parent","child","related","verifies","verified_by"]).optional().describe("Relationship type"),action:b.enum(["add","remove"]).optional().describe("Add or remove"),echo:b.boolean().optional().describe("false → lean response"),reason:b.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:b.array(b.object({action:b.enum(["add","remove"]),from_id:b.string().min(1).max(20),to_id:b.string().min(1).max(20),type:b.enum(["parent","child","related","verifies","verified_by"])})).optional().describe("Array form: batch relationship ops. Always atomic with DAG cycle detection."),idempotency_key:b.string().max(128).optional().describe("Safe retry key (24h TTL)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(br(),gr));return t(e)})),Ei({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_claude' for each created item\n - Creates parent relationships for items with parent_id",inputSchema:{project_id:b.string().uuid().describe("UUID of the target project"),items:b.array(b.object({type:b.enum(["requirement","test-case","note"]).describe("Item type"),title:b.string().min(1).max(500).describe("Item title"),body:b.string().max(5e4).optional().describe("Rich text body"),summary:b.string().max(2e3).optional().describe("Brief summary"),domains:b.array(b.string().max(64)).max(20).optional().describe("Domain tags"),level:b.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:b.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)"),confirmation_token:b.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:Oi("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(jr(),wr));return t(e)})}),xi("atoms_record_test_result",{title:"Record Test Result",description:"Record a pass/fail/blocked result for a test case.\n\nAppends to the test results history. 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 test_results table\n - Inserts into assets table if asset name is new in this project\n - Logs to change_history with actor='mcp_claude'",inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:b.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:b.string().max(1e3).optional().describe("Reason or comment for this result"),asset:b.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}},Oi("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(kr(),xr));return t(e)})),xi("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. The whole call is one DB transaction — any entry failure\nrolls 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 - Inserts into test_results (one row per entry)\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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:b.array(b.object({asset:b.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:b.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:b.string().max(500).optional().describe("Run note"),date:b.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}},Oi("atoms_record_test_results",async e=>{const{recordTestResultsBulkHandler:t}=await Promise.resolve().then(()=>(Dr(),Ir));return t(e)})),Ei({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)\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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Starting item ID"),direction:b.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:b.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:b.array(b.enum(["parent","child","related","verifies","verified_by"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Oi("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(Cr(),Ur));return t(e)})}),xi("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:b.string().uuid().describe("UUID of the project"),include_archived:b.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(Mr(),Rr));return t(e)})),xi("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\nReturns:\n { variables: [{ id, name, value, unit, description }], total }",inputSchema:{project_id:b.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(Fr(),$r));return t(e)})),xi("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\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),variable_name:b.string().min(1).max(64).describe("Variable name")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(Fr(),$r));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),variable_name:b.string().min(1).max(64).describe("Variable name"),value:b.string().max(500).optional().describe("New value"),unit:b.string().max(32).optional().describe("Unit abbreviation"),description:b.string().max(2e3).optional().describe("Description")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(Fr(),$r));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).optional().describe("Variable name (single form)"),value:b.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:b.string().max(32).optional().describe("Unit abbreviation"),description:b.string().max(2e3).optional().describe("Description"),echo:b.boolean().optional().describe("false → lean response (default true)"),variables:b.array(b.object({name:b.string().min(1).max(64).describe("Variable name"),value:b.string().min(1).max(500).describe("Initial value"),unit:b.string().max(32).optional().describe("Unit abbreviation"),description:b.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:b.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Oi("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(Fr(),$r));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Variable name to delete"),force:b.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:b.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}},Oi("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(Fr(),$r));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(Xr(),Jr));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Oi("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(Xr(),Jr));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Current domain name"),new_name:b.string().min(1).max(64).describe("New domain name"),dry_run:b.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Oi("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(Xr(),Jr));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Domain name to delete"),force:b.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:b.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}},Oi("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(Xr(),Jr));return t(e)})),Ei({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:b.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Oi("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(ii(),ei));return t(e)})}),Ei({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:b.string().uuid().describe("UUID of the project"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:b.string().max(64).optional().describe("Filter by domain tag"),level:b.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:b.string().max(1e3).optional().describe("Full-text search query"),limit:b.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:b.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Oi("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(li(),ni));return t(e)})}),xi("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:b.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:b.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:b.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(ui(),mi));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),limit:b.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:b.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(Ii(),_i));return t(e)})),xi("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:b.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Oi("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(Ii(),_i));return t(e)})),xi("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:b.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Oi("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(Ii(),_i));return t(e)})),xi("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:b.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:b.string().uuid().describe("UUID of the second (newer) baseline"),detail:b.boolean().default(!1).describe("Include per-item field-level diffs (default false)"),limit:b.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:b.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Oi("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(Ii(),_i));return t(e)})),xi("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:b.string().uuid().describe("UUID of the baseline to restore from"),confirm:b.boolean().default(!1).describe("Set true to execute; false (default) returns a preview")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Oi("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(Ii(),_i));return t(e)}))}}),Ui={};async function qi(){const e=h(32).toString("base64url"),t=g("sha256").update(e).digest("base64url"),r=`http://localhost:${Ai}${Hi}`,i=new p(`${ye}/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 n;function a(){clearTimeout(n)}const s=w(async(i,n)=>{const o=new p(i.url??"/",`http://localhost:${Ai}`);if(o.pathname!==Hi)return n.writeHead(404),void n.end("Not found");try{if("access_denied"===o.searchParams.get("error"))return n.writeHead(200,{"Content-Type":"text/html"}),n.end(Ri("Authorization was cancelled.")),a(),s.close(),void r(new Error("Authorization cancelled by user."));const i=o.searchParams.get("code");if(i){const o=await fetch(`${he}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:ge},body:JSON.stringify({auth_code:i,code_verifier:e})}),d=await o.json();if(!o.ok||!d.access_token){const e=d.error_description??d.msg??"Unknown error";return n.writeHead(200,{"Content-Type":"text/html"}),n.end(Ri(`Code exchange failed: ${e}`)),a(),s.close(),void r(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(d.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(he,ge,{global:{headers:{Authorization:`Bearer ${d.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(Ri('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://atoms.tech">atoms.tech</a> first, then run this login command again.')),a(),s.close(),void r(new Error("No ATOMS account found. Sign up at atoms.tech first."))):(await me({access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Date.now()+1e3*(d.expires_in??3600),user_email:c}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(Ci(c)),a(),s.close(),void t({email:c}))}const d=o.searchParams.get("access_token"),c=o.searchParams.get("refresh_token"),l=parseInt(o.searchParams.get("expires_in")??"3600",10);d&&c?(await me({access_token:d,refresh_token:c,expires_at:Date.now()+1e3*l}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(Ci("authenticated")),a(),s.close(),t({email:"authenticated"})):(n.writeHead(200,{"Content-Type":"text/html"}),n.end("<!DOCTYPE html>\n<html>\n<head><title>ATOMS MCP Login</title></head>\n<body>\n <h1>Completing login...</h1>\n <script>\n const hash = window.location.hash.substring(1);\n const params = new URLSearchParams(hash);\n const data = {\n access_token: params.get('access_token'),\n refresh_token: params.get('refresh_token'),\n expires_in: params.get('expires_in'),\n user_email: ''\n };\n if (data.access_token) {\n // Decode JWT to get email\n try {\n const payload = JSON.parse(atob(data.access_token.split('.')[1]));\n data.user_email = payload.email || '';\n } catch(e) {}\n fetch('/token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data)\n }).then(() => {\n document.body.innerHTML = '<h1>Login successful! You can close this tab.</h1>';\n }).catch(() => {\n document.body.innerHTML = '<h1>Login failed. Please try again.</h1>';\n });\n } else {\n document.body.innerHTML = '<h1>Login failed — no tokens received.</h1>';\n }\n <\/script>\n</body>\n</html>"))}catch(e){n.writeHead(500),n.end("Authentication failed"),a(),s.close(),r(e)}});s.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 me({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})),a(),s.close(),t({email:e.user_email??"authenticated"})}catch(e){i.writeHead(500),i.end("Failed to store credentials"),a(),s.close(),r(e)}})}}),s.listen(Ai,"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")}}),n=setTimeout(()=>{s.close(),r(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function Ci(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 Ri(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>`}T(Ui,{login:()=>qi});var Pi=O({"src/auth/login.ts"(){be(),ve(),Ai=19275,Hi="/callback"}});Di(),K(),ne(),Be(),re();var Mi=process.argv.slice(2)[0];(async function(){switch(Mi){case"login":{const{login:e}=await Promise.resolve().then(()=>(Pi(),Ui));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(()=>(Ae(),je));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(()=>(be(),ce));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 v0.4.0\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(()=>(Ae(),je)),{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(()=>(Pi(),Ui)),{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`)}}process.stderr.write(`[atoms-mcp] Tool registry: ${function(){const e=J(),t=F(),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`);try{const t=await De(),r=Re(),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:X};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 permissive policy.\n`),{role:null,is_member:!1,effective:X}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:X};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,X.read_only),lockdown:s(n.lockdown,X.lockdown),block_destructive:s(n.block_destructive,X.block_destructive),block_bulk_import:s(n.block_bulk_import,X.block_bulk_import),cross_project_browse:s(n.cross_project_browse,X.cross_project_browse),allowed_toolsets:a(n.allowed_toolsets,X.allowed_toolsets),forbidden_tools:a(n.forbidden_tools,X.forbidden_tools),project_scope:d,require_confirmation_for:a(n.require_confirmation_for,X.require_confirmation_for)}}}(i)}(t,r,i);e={effective:n.effective,role:n.role,org_id:i},ee=e.effective,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`)}const t=new v;await ji.connect(t),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}var e})().catch(e=>{process.stderr.write(`[atoms-mcp] Fatal: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)});
|
|
2
|
+
import e,{readFile as t,mkdir as i,writeFile as r,unlink as n}from"fs/promises";import{homedir as a}from"os";import s,{join as o}from"path";import{createClient as d}from"@supabase/supabase-js";import{registerAppTool as c,registerAppResource as l,RESOURCE_MIME_TYPE as m}from"@modelcontextprotocol/ext-apps/server";import{URL as p,fileURLToPath as u}from"url";import _,{randomUUID as f,randomBytes as h,createHash as g}from"crypto";import{McpServer as y}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as b}from"zod";import{createServer as w}from"http";import{StdioServerTransport as v}from"@modelcontextprotocol/sdk/server/stdio.js";var j,x,S,k,I=Object.defineProperty,E=Object.getOwnPropertyNames,O=(e,t)=>function(){return e&&(t=(0,e[E(e)[0]])(e=0)),t},T=(e,t)=>{for(var i in t)I(e,i,{get:t[i],enumerable:!0})};function A(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of S)if(t.test(e.trim()))return"[redacted]";return e.length>k?e.slice(0,k)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>A(e,t+1));if(null!==e&&"object"==typeof e){const i={};for(const[r,n]of Object.entries(e)){const e=r.toLowerCase();j.has(e)?i[r]="[redacted]":x.has(e)?i[r]="string"==typeof n?"[content]":A(n,t+1):i[r]=A(n,t+1)}return i}return e}function H(e){return A(e)}var D,U,C,q,R,P,M,$,N,W=O({"src/middleware/audit.ts"(){j=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),x=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),S=[/^[^\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_-]+$/],k=200}}),L=O({"src/middleware/rate-limiter.ts"(){D=60,U=6e4}});function V(e){return N.get(e)}var B=O({"src/core/tool-catalog.ts"(){C=new Set(["atoms_status","atoms_list_projects"]),q=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_baseline","atoms_lock_baseline","atoms_restore_baseline"]),R=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_restore_baseline"]),P=new Set(["atoms_bulk_import"]),M={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"],baselines:["atoms_list_baselines","atoms_create_baseline","atoms_lock_baseline","atoms_diff_baselines","atoms_restore_baseline"]},$=Object.keys(M),N=new Map;for(const[e,t]of Object.entries(M))for(const i of t)N.set(i,e)}});function F(){const e=process.env.ATOMS_MCP_TOOLSETS?.trim();if(!e)return null;const t=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===t.length)return null;const i=new Set,r=[];for(const e of t)$.includes(e)?i.add(e):r.push(e);return{allowed:i,unknown:r}}function J(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function z(e){if(J()&&q.has(e))return!1;if(C.has(e))return!0;const t=F();if(null===t)return!0;const i=V(e);return!!i&&t.allowed.has(i)}var Q,G,Y,K=O({"src/middleware/tool-registry.ts"(){B()}});function Z(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?Q.test(e)?e:(G||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),G=!0),null):null}var X,ee,te=O({"src/middleware/project-scope.ts"(){Q=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,G=!1,Y=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}}}}),ie=O({"src/core/types.ts"(){X={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:[]}}});function re(){return ee}var ne=O({"src/middleware/session-policy.ts"(){ie(),ee=X}});function ae(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 se,oe,de=O({"src/core/policy.ts"(){B()}}),ce={};async function le(){try{const e=await t(oe,"utf-8"),i=JSON.parse(e);return i.access_token&&i.refresh_token?i:null}catch{return null}}async function me(e){await i(se,{recursive:!0,mode:448}),await r(oe,JSON.stringify(e,null,2),{mode:384})}async function pe(){const e=await le();return!!e&&e.expires_at>Date.now()+6e4}function ue(e){return e.expires_at>Date.now()+6e4}async function _e(){try{await n(oe)}catch{}}function fe(){return oe}T(ce,{clearCredentials:()=>_e,getCredentialsPath:()=>fe,hasValidCredentials:()=>pe,isTokenValid:()=>ue,readCredentials:()=>le,writeCredentials:()=>me});var he,ge,ye,be=O({"src/auth/token-store.ts"(){se=o(a(),".atoms"),oe=o(se,"credentials.json")}}),we={};T(we,{ATOMS_APP_URL:()=>ye,ATOMS_SUPABASE_ANON_KEY:()=>ge,ATOMS_SUPABASE_URL:()=>he});var ve=O({"src/config.ts"(){he="https://gmebjyhomsbvhrxffzre.supabase.co",ge="sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",ye=process.env.ATOMS_APP_URL??"https://atoms.tech"}}),je={};async function xe(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=Se(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await le();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=Se(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}process.stderr.write("[atoms-mcp] Refreshing access token...\n");const i=d(he,ge),{data:r,error:n}=await i.auth.refreshSession({refresh_token:t.refresh_token});if(n||!r.session)throw new Error(`Token refresh failed: ${n?.message??"No session returned"}. Re-run 'npx @atoms-tech/atoms-mcp login'.`);const a=r.session;return await me({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 Se(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const i=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),r=JSON.parse(Buffer.from(i,"base64").toString("utf-8"));if(!r.sub)throw new Error("JWT missing 'sub' claim");return r}T(je,{getValidToken:()=>xe});var ke,Ie,Ee,Oe,Te,Ae=O({"src/auth/refresh.ts"(){be(),ve()}}),He={};async function De(){if(ke)try{const e=await le();e&&e.expires_at>Te&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),Ue())}catch{}if(ke&&Oe>Date.now()+6e4)return ke;ke&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:i}=await xe(),r=e.split(".");if(3===r.length)try{const e=JSON.parse(Buffer.from(r[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());Oe=1e3*(e.exp??0)}catch{Oe=Date.now()+36e5}try{const e=await le();Te=e?.expires_at??0}catch{Te=0}const n=d(he,ge,{global:{headers:{Authorization:`Bearer ${e}`}}});return Ie=t,Ee=i,ke=n}function Ue(){ke=null,Ie=null,Ee=null,Oe=0,Te=0}function Ce(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const i=e;t="string"==typeof i.message?i.message:"string"==typeof i.code?i.code:String(e)}else null!=e&&(t=String(e));return/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)}async function qe(e){try{return await e()}catch(t){if(!Ce(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),Ue(),await e()}}function Re(){if(!Ie)throw new Error("Not authenticated. Call getClient() first.");return Ie}function Pe(){return Ee??""}async function Me(e,t){const i=Re(),{data:r,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n||!r)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",i).eq("org_id",r.org_id).maybeSingle();if(s||!a){const{data:t}=await e.rpc("is_platform_admin");if(!0===t)return"admin";throw new Error("Not a member of this project's organization")}if("viewer"===a.role)throw new Error("VIEWER_ROLE");return a.role}T(He,{getClient:()=>De,getUserEmail:()=>Pe,getUserId:()=>Re,invalidateClient:()=>Ue,isJwtExpiredError:()=>Ce,requireWriteAccess:()=>Me,withJwtRetry:()=>qe});var $e,Ne,We,Le,Ve,Be=O({"src/db/client.ts"(){Ae(),be(),ve(),ke=null,Ie=null,Ee=null,Oe=0,Te=0}}),Fe={};function Je(e,t=Ne){if("string"!=typeof e)return"";const i=e.replace(Le,"").replace(Ve,"");return i.length<=t?i:i.slice(0,t)+"..."}function ze(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Qe(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function Ge(e,t,i){return{total_count:e,limit:t,offset:i,has_more:i+t<e}}function Ye(e,t){return{status:"error",message:e,next_steps:t}}function Ke(e,t){return Ye(`${e} '${Je(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function Ze(e){return Ye(`${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 Xe(e){return Ye(`Validation error: ${Je(e,We)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function et(){return Ye("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 tt(){return Ye("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 it(e){return Ye("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 rt(e){return Ye("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 nt(e){return Ye(`Parse error: ${Je(e,We)}`,["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 at(e){const t=e instanceof Error?e.message:String(e);return/not authenticated/i.test(t)?et():/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)?tt():/rate.?limit|too many requests|429/i.test(t)?rt():/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?nt(t):st(t)}function st(e){return/row.level security|permission denied for/i.test(e)?Ye("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"]):Ye(`Database error: ${Je(e,We)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function ot(e){return null==e?e:`<user_content>${e}</user_content>`}function dt(e){const t=JSON.stringify(e,null,2);if(t.length>$e&&"success"===e.status&&Array.isArray(e.data)){const t=Math.max(1,Math.floor(e.data.length/2)),i={...e,data:e.data.slice(0,t),meta:{...e.meta,truncated:!0,truncation_message:`Response truncated from ${e.data.length} to ${t} items. Use 'offset' parameter or add filters to see more results.`}};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}}return{content:[{type:"text",text:t}],structuredContent:e}}function ct(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}T(Fe,{CHARACTER_LIMIT:()=>$e,accessDeniedError:()=>Ze,authError:()=>et,classifyError:()=>at,dbError:()=>st,errorResponse:()=>Ye,formatErrorResult:()=>ct,formatToolResult:()=>dt,jwtExpiredError:()=>tt,notFoundError:()=>Ke,paginationMeta:()=>Ge,parseError:()=>nt,rateLimitError:()=>rt,sanitizeForEcho:()=>Je,sanitizeTagOrLevel:()=>ze,scopeError:()=>it,success:()=>Qe,validationError:()=>Xe,wrapUserContent:()=>ot});var lt,mt=O({"src/tools/_base.ts"(){$e=25e3,Ne=50,We=200,Le=new RegExp("[\\u0000-\\u001F\\u007F]","g"),Ve=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g")}});var pt=O({"src/apps/register.ts"(){lt={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});async function ut(e,t,i){let r=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0});i.type&&(r=r.eq("type",i.type)),i.domain&&(r=r.filter("data->tags->domains","cs",JSON.stringify([i.domain]))),i.level&&(r=r.filter("data->tags->>level","eq",i.level)),r=r.range(i.offset,i.offset+i.limit-1);const{data:n,error:a,count:s}=await r;if(a)throw new Error(a.message);return{items:n??[],totalCount:s??0}}async function _t(e,t,i){const{data:r,error:n}=await e.from("items").select("*").eq("id",i).eq("project_id",t).is("deleted_at",null).maybeSingle();if(n)throw new Error(n.message);return r}async function ft(e,t){if(t.baseline_id&&t.as_of)throw new Error("baseline_id and as_of are mutually exclusive");if(t.as_of)return t.as_of;if(t.baseline_id){const{data:i,error:r}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",t.baseline_id).maybeSingle();if(r)throw new Error(`resolveSnapshotAt: ${r.message}`);if(!i||null!==i.deleted_at)throw new Error(`Baseline not found: ${t.baseline_id}`);if(i.project_id!==t.project_id)throw new Error("Baseline does not belong to this project");return i.snapshot_at}return null}async function ht(e,t){const{data:i,error:r}=await e.from("baselines").select("id, project_id, name, description, snapshot_at, created_at, created_by, locked_at, locked_by, deleted_at").eq("id",t).maybeSingle();if(r)throw new Error(`getBaselineById: ${r.message}`);return i&&null===i.deleted_at?i:null}function gt(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 yt(e,t,i){const{data:r,error:n}=await e.rpc("project_state_at",{p_project_id:t,p_snapshot_at:i});if(n)throw new Error(`projectStateAt: ${n.message}`);return r??[]}async function bt(e,t,i,r){const n=i.trim();if(!n)return{items:[],totalCount:0};let a=null;if(r.asset&&r.asset.trim()){const{data:i,error:n}=await e.from("test_results").select("item_id").eq("project_id",t).eq("asset",r.asset.trim());if(n)throw new Error(n.message);const s=new Set;for(const e of i??[])s.add(e.item_id);if(a=Array.from(s),0===a.length)return{items:[],totalCount:0}}let s=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.%${n}%,data->>body.ilike.%${n}%,data->>summary.ilike.%${n}%`).limit(r.limit);r.type&&(s=s.eq("type",r.type)),a&&(s=s.in("id",a));const{data:o,error:d,count:c}=await s;if(d)throw new Error(d.message);return{items:o??[],totalCount:c??0}}function wt(e,t){const i=new Set(e.map(e=>e.id)),r=new Set,n=[],a=(e,t,a)=>{if(e===t)return;if(!i.has(e)||!i.has(t))return;const s=`${e}|${t}|${a}`;r.has(s)||(r.add(s),n.push({from_id:e,to_id:t,type:a}))};for(const e of t)a(e.from_id,e.to_id,e.type);for(const t of e){const e=t.data?.relationships??{},i=t=>Array.isArray(e[t])?e[t].filter(e=>"string"==typeof e):[];for(const e of i("parents"))a(t.id,e,"parent");for(const e of i("children"))a(t.id,e,"child");for(const e of i("related"))a(t.id,e,"related");for(const e of i("verifies"))a(t.id,e,"verifies");for(const e of i("verified_by"))a(t.id,e,"verified_by")}return n}async function vt(e,t,i){const r="requirement"===i?"REQ":"test-case"===i?"TC":"note"===i?"NOTE":"TABLE",{data:n,error:a}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(a)throw new Error(`ID generation failed: ${a.message}`);return n}var jt=O({"src/db/queries.ts"(){}}),xt={};async function St(){try{const e=await qe(async()=>{const e=await De();return await async function(e){const{data:t,error:i}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(i)throw new Error(i.message);return(t??[]).map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.organizations?.name??"Unknown",created_at:e.created_at}))}(e)}),t=Z(),i=re().project_scope,r=i?new Set(i):null;return dt(Qe(e.filter(e=>!t||e.id===t).filter(e=>!r||r.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 ct(at(e))}}T(xt,{listProjectsHandler:()=>St});var kt=O({"src/tools/list-projects.ts"(){Be(),jt(),te(),ne(),mt()}}),It={};async function Et(e){try{const t=await De();let i,r,n=null;try{n=await ft(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return ct(st(e.message))}if(n){const a=(await yt(t,e.project_id,n)).filter(t=>{if(e.type&&t.type!==e.type)return!1;const i=t.data??{};if(e.domain){const t=i?.tags?.domains??[];if(!Array.isArray(t)||!t.includes(e.domain))return!1}return!e.level||i?.tags?.level===e.level});r=a.length,i=a.slice(e.offset,e.offset+e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const n=await ut(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});i=n.items,r=n.totalCount}return dt(Qe(i.map(e=>({id:e.id,title:ot(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Ge(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(It,{listItemsHandler:()=>Et});var Ot=O({"src/tools/list-items.ts"(){Be(),jt(),mt()}}),Tt={};async function At(e){try{const t=await De();let i=null;try{i=await ft(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return ct(Ye(e.message,["Pass baseline_id OR as_of, not both"]))}const r=i?await async function(e,t,i,r){const{data:n,error:a}=await e.rpc("item_state_at",{p_item_id:i,p_project_id:t,p_snapshot_at:r});if(a)throw new Error(`itemStateAt: ${a.message}`);return(n??[])[0]??null}(t,e.project_id,e.item_id,i).then(e=>e?gt(e):null):await _t(t,e.project_id,e.item_id);if(!r)return ct(Ke("Item",e.item_id));const n={parents:[],children:[],related:[],verified_by:[],verifies:[]};if(i){const e=r.data?.relationships??{};for(const t of Object.keys(n)){const i=e[t];Array.isArray(i)&&(n[t]=i.slice())}}else{const i=await async function(e,t,i){const{data:r,error:n}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${i},to_id.eq.${i}`);if(n)throw new Error(n.message);return r??[]}(t,e.project_id,e.item_id),a={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by"},s={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",related:"related"},o=(e,t)=>{if(!(e in n))return;const i=n[e];i.includes(t)||i.push(t)};for(const t of i)t.from_id===e.item_id?o(a[t.type]??t.type,t.to_id):o(s[t.type]??t.type,t.from_id);const d=r.data?.relationships??{};for(const t of Object.keys(n)){const i=d[t];if(Array.isArray(i))for(const r of i)"string"==typeof r&&r!==e.item_id&&o(t,r)}}let a=[];if("test-case"===r.type)if(i)a=(r.data?.runs??[]).filter(e=>e&&"string"==typeof e.run_at).sort((e,t)=>t.run_at.localeCompare(e.run_at)).slice(0,20).map(e=>({result:e.result,run_by:e.run_by??null,run_at:e.run_at,note:e.note??null}));else{const{data:i,error:r}=await t.from("test_results").select("result, run_by, run_at, note").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);!r&&i&&(a=i)}return dt(Qe({id:r.id,type:r.type,title:ot(r.title),summary:ot(r.data?.summary),body:ot(r.data?.body),tags:r.data?.tags??{domains:[]},ownership:r.data?.ownership??{primary:null,additional:[]},relationships:n,links:r.data?.links??[],status:r.data?.status,..."test-case"===r.type?{latest_result:a[0]?.result??"not-run",test_results:a}:{},metadata:{created_at:r.created_at,created_by:r.created_by,updated_at:r.updated_at,updated_by:r.updated_by,source_id:r.data?.metadata?.source_id}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Tt,{getItemHandler:()=>At});var Ht=O({"src/tools/get-item.ts"(){Be(),jt(),mt()}}),Dt={};async function Ut(e){try{const t=await De();let i,r,n=null;try{n=await ft(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return ct(st(e.message))}if(n){const a=await yt(t,e.project_id,n),s=e.query.trim().toLowerCase(),o=0===s.length?[]:a.filter(t=>{if(e.type&&t.type!==e.type)return!1;const i=t.data??{};return[t.title,i?.body,i?.summary].filter(e=>"string"==typeof e).map(e=>e.toLowerCase()).some(e=>e.includes(s))});r=o.length,i=o.slice(0,e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const n=await bt(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});i=n.items,r=n.totalCount}return dt(Qe(i.map(e=>({id:e.id,title:ot(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Ge(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Dt,{searchHandler:()=>Ut});var Ct=O({"src/tools/search.ts"(){Be(),jt(),mt()}}),qt={};async function Rt(e){try{const t=await De(),{items:i,totalCount:r}=await async function(e,t,i,r){const{ATOMS_SUPABASE_URL:n,ATOMS_SUPABASE_ANON_KEY:a}=await Promise.resolve().then(()=>(ve(),we)),s=await fetch(`${n}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({input:i})});if(!s.ok)throw new Error(`Embed function failed: ${s.status}`);const{embedding:o}=await s.json(),{data:d,error:c}=await e.rpc("semantic_search",{query_embedding:o,p_project_id:t,match_threshold:.3,match_count:r.limit,p_type:r.type||null});if(c)throw new Error(c.message);return{items:d??[],totalCount:(d??[]).length,method:"semantic"}}(t,e.project_id,e.query,{type:e.type,limit:e.limit});return dt(Qe(i.map(e=>({id:e.id,title:ot(e.title),type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Ge(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(qt,{semanticSearchHandler:()=>Rt});var Pt=O({"src/tools/semantic-search.ts"(){Be(),jt(),mt()}}),Mt={};async function $t(e){try{if(e.baseline_id&&e.as_of)return ct(Xe("baseline_id and as_of are mutually exclusive"));const t=await De();let i;if(e.baseline_id){const r=await ht(t,e.baseline_id);if(!r)return ct(Xe(`Baseline ${e.baseline_id} not found`));if(r.project_id!==e.project_id)return ct(Xe("Baseline does not belong to this project"));i=r.snapshot_at}else e.as_of&&(i=e.as_of);const{covered:r,uncovered:n,total:a}=await async function(e,t,i){let r,n,a;if(i.snapshotAt){const s=(await yt(e,t,i.snapshotAt)).map(gt);r=s.filter(e=>"requirement"===e.type),n=s.map(e=>({id:e.id,data:e.data})),a=[]}else{const{data:i,error:s}=await e.from("items").select("*").eq("project_id",t).eq("type","requirement").is("deleted_at",null);if(s)throw new Error(s.message);r=i??[];const{data:o,error:d}=await e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null);if(d)throw new Error(d.message);n=o??[];const{data:c,error:l}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t);if(l)throw new Error(l.message);a=c??[]}const s=r.filter(e=>!(i.domain&&!(e.data?.tags?.domains??[]).includes(i.domain)||i.level&&e.data?.tags?.level!==i.level)),o=wt(n,a),d=new Set;for(const e of o)"verifies"===e.type?d.add(e.to_id):"verified_by"===e.type&&d.add(e.from_id);return{covered:s.filter(e=>d.has(e.id)),uncovered:s.filter(e=>!d.has(e.id)),total:s.length}}(t,e.project_id,{domain:e.domain,level:e.level,snapshotAt:i}),s=n.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level}));return dt(Qe({covered:r.length,uncovered:n.length,total:a,coverage_percent:a>0?Math.round(r.length/a*1e3)/10:100,uncovered_items:s}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Mt,{getCoverageHandler:()=>$t});var Nt=O({"src/tools/get-coverage.ts"(){Be(),jt(),mt()}}),Wt={};async function Lt(e){try{const t=await De(),i=await async function(e,t,i,r){const{data:n,error:a}=await e.from("change_history").select("*").eq("item_id",i).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r);if(a)throw new Error(a.message);return n??[]}(t,e.project_id,e.item_id,e.limit),r=i.map(e=>{const t=[],i=e.old_data,r=e.new_data;if(i&&r){const e=new Set([...Object.keys(i),...Object.keys(r)]);for(const n of e)JSON.stringify(i[n])!==JSON.stringify(r[n])&&t.push(n)}else r?t.push("(created)"):i&&t.push("(deleted)");return{id:e.id,event_type:e.event_type,changed_by:e.changed_by??null,changed_at:e.changed_at,actor:e.actor??"user",session_id:e.session_id??null,fields_changed:t}});return dt(Qe(r,Ge(r.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Wt,{getHistoryHandler:()=>Lt});var Vt=O({"src/tools/get-history.ts"(){Be(),jt(),mt()}}),Bt={};async function Ft(e){try{if(e.baseline_id&&e.as_of)return ct(Xe("baseline_id and as_of are mutually exclusive"));const t=await De();let i,r,n;if(e.baseline_id){const r=await ht(t,e.baseline_id);if(!r)return ct(Xe(`Baseline ${e.baseline_id} not found`));if(r.project_id!==e.project_id)return ct(Xe("Baseline does not belong to this project"));i=r.snapshot_at}else e.as_of&&(i=e.as_of);if(i){r=(await yt(t,e.project_id,i)).map(gt).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),n=wt(r,[])}else{const{data:i,error:a}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);r=i??[];const{data:s,error:o}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);n=wt(r,s??[])}if(0===r.length)return dt(Qe({mermaid:"graph TD\n empty[No items in project]"}));const a=new Map;for(const e of r)a.set(e.id,e);const s=["graph TD"],o=new Set,d=new Set,c=(new Set((n??[]).filter(e=>"child"===e.type).map(e=>e.to_id)),new Set((n??[]).filter(e=>"parent"===e.type).map(e=>e.from_id)));let l;l=e.root_item_id?[e.root_item_id]:r.filter(e=>!c.has(e.id)).filter(t=>!(!e.include_tests&&"test-case"===t.type)).map(e=>e.id);const m=l.map(e=>({id:e,depth:0}));for(;m.length>0;){const{id:t,depth:i}=m.shift();if(o.has(t)||i>e.depth)continue;o.add(t);const r=a.get(t);if(!r)continue;if(!e.include_tests&&"test-case"===r.type)continue;const c=Jt(r.title),l="requirement"===r.type?`["${c}"]`:"test-case"===r.type?`(["${c}"])`:`("${c}")`;s.push(` ${t}${l}`);for(const r of n??[]){if(r.from_id!==t)continue;const n=a.get(r.to_id);if(!n)continue;if(!e.include_tests&&"test-case"===n.type)continue;const c=`${r.from_id}-${r.type}-${r.to_id}`;d.has(c)||(d.add(c),"child"===r.type?s.push(` ${t} --\x3e ${r.to_id}`):"verified_by"===r.type?s.push(` ${t} -.->|verified_by| ${r.to_id}`):"related"===r.type&&s.push(` ${t} -.- ${r.to_id}`),!o.has(r.to_id)&&i+1<=e.depth&&m.push({id:r.to_id,depth:i+1}))}}return dt(Qe({mermaid:s.join("\n"),node_count:o.size,edge_count:d.size}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}function Jt(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,50)}T(Bt,{exportMermaidHandler:()=>Ft});var zt=O({"src/tools/export-mermaid.ts"(){Be(),jt(),mt()}}),Qt={};async function Gt(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const r=(e.domains??[]).map(ze).filter(e=>e.length>0),n=void 0!==e.level?ze(e.level):void 0;if(r.length>0){const{data:i}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),n=i?.domains??[];if(n.length>0){const e=new Set(n.map(ze).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return ct(Xe(`Unknown domain${t.length>1?"s":""}: ${t.join(", ")}. Registered: ${n.join(", ")}. Add new domains via Taxonomy Management in the ATOMS web app first.`))}}const a=await vt(t,e.project_id,e.type),s=(new Date).toISOString(),o={id:a,type:e.type,title:e.title,summary:e.summary,body:e.body,tags:{domains:r,level:n??""},ownership:{primary:null,additional:[]},relationships:{parents:e.parent_ids??[],children:[],related:[]},links:[],metadata:{created_at:s,created_by:i,updated_at:s,updated_by:i}},{error:d}=await t.rpc("save_item_with_revision",{p_item_id:a,p_project_id:e.project_id,p_type:e.type,p_title:e.title,p_data:o,p_user_id:i,p_event_source:"mcp",p_event_session_id:Tr()??null,p_diff_summary:null});if(d)throw new Error(d.message);if(e.parent_ids&&e.parent_ids.length>0){const r=e.parent_ids.map(t=>({from_id:a,to_id:t,type:"parent",project_id:e.project_id}));await t.from("item_relationships").insert(r).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: relationship sync failed: ${e.message}\n`)});const{data:n,error:s}=await t.from("items").select("id, data").eq("project_id",e.project_id).in("id",e.parent_ids);if(s)process.stderr.write(`[atoms-mcp] Warning: parent JSONB read failed: ${s.message}\n`);else for(const r of n??[]){const n=JSON.parse(JSON.stringify(r.data??{}));n.relationships=n.relationships??{};const s=Array.isArray(n.relationships.children)?n.relationships.children:[];if(!s.includes(a)){n.relationships.children=[...s,a];const{error:o}=await t.from("items").update({data:n,updated_by:i}).eq("id",r.id).eq("project_id",e.project_id);o&&process.stderr.write(`[atoms-mcp] Warning: parent JSONB write failed for ${r.id}: ${o.message}\n`)}}}return await t.from("change_history").insert({item_id:a,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:o,actor:"mcp_claude",session_id:Tr()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===e.echo?dt(Qe({id:a,type:e.type})):dt(Qe({id:a,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",domains:r,level:n??"",project_id:e.project_id}))}catch(e){return ct(at(e))}}T(Qt,{createItemHandler:()=>Gt});var Yt=O({"src/tools/create-item.ts"(){Be(),jt(),Dr(),mt()}}),Kt={};async function Zt(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const r=async(r,n,a,s)=>{const o=await _t(t,e.project_id,r);if(!o)return{updated_fields:[],error:`Item "${r}" not found`};const d=void 0!==n.domains?n.domains.map(ze).filter(e=>e.length>0):void 0,c=void 0!==n.level?ze(n.level):void 0;if(void 0!==d&&d.length>0){const{data:i}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),r=i?.domains??[];if(r.length>0){const e=new Set(r.map(ze).filter(e=>e.length>0)),t=d.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const l={...o.data},m={...o.data},p=[],u=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==n.title&&u(o.data.title,n.title)&&(m.title=n.title,p.push("title")),void 0!==n.body&&u(o.data.body,n.body)&&(m.body=n.body,p.push("body")),void 0!==n.summary&&u(o.data.summary,n.summary)&&(m.summary=n.summary,p.push("summary")),void 0!==d&&u(o.data.tags?.domains??[],d)&&(m.tags={...m.tags,domains:d},p.push("domains")),void 0!==c&&u(o.data.tags?.level,c)&&(m.tags={...m.tags,level:c},p.push("level")),void 0!==n.status&&u(o.data.status,n.status)&&(m.status=n.status,p.push("status")),0===p.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};m.metadata={...m.metadata,updated_at:(new Date).toISOString(),updated_by:i};const _=n.title??o.title,{data:f,error:h}=await t.rpc("save_item_with_revision",{p_item_id:r,p_project_id:e.project_id,p_type:o.type,p_title:_,p_data:m,p_user_id:i,p_event_source:"mcp",p_event_session_id:Tr()??null,p_diff_summary:null});if(h)return{updated_fields:[],error:h.message};if(!f)return{updated_fields:[],error:`Update silently failed for "${r}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};const g={item_id:r,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:l,new_data:m,actor:"mcp_claude",session_id:Tr()};return a&&(g.batch_id=a),s&&(g.reason=s),await t.from("change_history").insert(g).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),{updated_fields:p,updatedData:m,itemType:o.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),i=!0===e.continue_on_error,n=[],a=[];for(const s of e.updates){const{updated_fields:o,error:d}=await r(s.item_id,s,t,e.reason);if(d){if(!i)return ct(Xe(`Batch stopped at "${s.item_id}": ${d}. ${n.length} item(s) already updated.`));a.push({item_id:s.item_id,error:d})}else n.push({id:s.item_id,updated_fields:o})}return dt(Qe({batch_id:t,updated:n.length,results:!1===e.echo?void 0:n,errors:a}))}if(!e.item_id)return ct(Xe("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:n,updatedData:a,itemType:s,error:o}=await r(e.item_id,{title:e.title,body:e.body,summary:e.summary,domains:e.domains,level:e.level,status:e.status},void 0,e.reason);if(o)return o.includes("not found")?ct(Ke("Item",e.item_id)):o.includes("Unknown domain")?ct(Xe(o)):ct(st(o));if(!1===e.echo)return dt(Qe({id:e.item_id,updated_fields:n}));const d=a??{};return dt(Qe({id:e.item_id,type:s,title:d.title??"",summary:d.summary??"",body:d.body??"",domains:d.tags?.domains??[],level:d.tags?.level??"",updated_fields:n}))}catch(e){return ct(at(e))}}T(Kt,{updateItemHandler:()=>Zt});var Xt,ei,ti=O({"src/tools/update-item.ts"(){Be(),jt(),Dr(),mt()}});function ii(e){const t=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(t){const i=t.toLowerCase();if("1"===i||"true"===i||"all"===i)return!0;if(t.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!re().require_confirmation_for.includes(e)}function ri(e,t=Xt){const i=Date.now()+t,r={...e,exp:i},n=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${n}.${_.createHmac("sha256",ei).update(n).digest("base64url")}`,expires_at:new Date(i).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function ni(e,t){if("string"!=typeof e||!e.includes("."))return{valid:!1,reason:"Token format invalid"};const[i,r]=e.split(".");if(!i||!r)return{valid:!1,reason:"Token format invalid"};const n=_.createHmac("sha256",ei).update(i).digest("base64url"),a=Buffer.from(r,"utf8"),s=Buffer.from(n,"utf8");if(a.length!==s.length||!_.timingSafeEqual(a,s))return{valid:!1,reason:"Token signature invalid"};let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return{valid:!1,reason:"Token payload malformed"}}return"number"!=typeof o.exp||o.exp<Date.now()?{valid:!1,reason:"Token expired"}:o.tool!==t.tool?{valid:!1,reason:"Token issued for a different tool"}:o.project_id!==t.project_id?{valid:!1,reason:"Token issued for a different project"}:o.target!==t.target?{valid:!1,reason:"Token issued for a different target"}:{valid:!0}}function ai(e){if(Array.isArray(e))return e.map(ai);if(null!==e&&"object"==typeof e){const t={};for(const i of Object.keys(e).sort())t[i]=ai(e[i]);return t}return e}function si(e){const t=JSON.stringify(ai(e));return _.createHash("sha256").update(t).digest("base64url").slice(0,16)}var oi,di=O({"src/middleware/confirmation.ts"(){ne(),Xt=6e4,ei=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:_.randomBytes(32).toString("base64url")})()}}),ci={};async function li(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const r=await _t(t,e.project_id,e.item_id);if(!r)return ct(Ke("Item",e.item_id));if(ii(oi)){const t={tool:oi,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const i=ri(t);return dt(Qe({status:"confirmation_required",preview:{id:e.item_id,title:r.title,type:r.type,would_soft_delete:!0},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_delete_item with the same project_id, item_id, and confirmation_token within ${i.expires_in_seconds}s to execute.`}))}const i=ni(e.confirmation_token,t);if(!i.valid)return ct(Xe(`confirmation_token rejected: ${i.reason}`))}const{error:n}=await t.from("items").update({deleted_at:(new Date).toISOString()}).eq("id",e.item_id).eq("project_id",e.project_id);if(n)throw new Error(n.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"deleted",old_data:r.data,new_data:null,actor:"mcp_claude",session_id:Tr()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),dt(Qe({id:e.item_id,title:r.title,type:r.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return ct(at(e))}}T(ci,{deleteItemHandler:()=>li});var mi=O({"src/tools/delete-item.ts"(){Be(),jt(),Dr(),di(),mt(),oi="atoms_delete_item"}}),pi={};async function ui(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{data:r,error:n}=await t.from("items").select("*").eq("id",e.item_id).eq("project_id",e.project_id).maybeSingle();if(n)throw new Error(n.message);if(!r)return ct(Ke("Item",e.item_id));if(!r.deleted_at)return ct(Ye(`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.from("items").update({deleted_at:null}).eq("id",e.item_id).eq("project_id",e.project_id);if(a)throw new Error(a.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"restored",old_data:null,new_data:r.data,actor:"mcp_claude",session_id:Tr()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),dt(Qe({id:e.item_id,title:r.title,type:r.type,restored:!0,message:`Item ${e.item_id} restored successfully.`}))}catch(e){return ct(at(e))}}T(pi,{restoreItemHandler:()=>ui});var _i,fi,hi=O({"src/tools/restore-item.ts"(){Be(),Dr(),mt()}}),gi={};async function yi(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const r=async(r,n,a)=>{const s=await _t(t,e.project_id,r.from_id);if(!s)throw new Error(`Item "${r.from_id}" not found`);const o=await _t(t,e.project_id,r.to_id);if(!o)throw new Error(`Item "${r.to_id}" not found`);const d=_i(r.type);if("add"===r.action){const{data:n}=await t.from("item_relationships").select("from_id").eq("from_id",r.from_id).eq("to_id",r.to_id).eq("type",r.type).eq("project_id",e.project_id).maybeSingle();if(!n){const{error:i}=await t.from("item_relationships").insert({from_id:r.from_id,to_id:r.to_id,type:r.type,project_id:e.project_id});if(i)throw new Error(i.message)}const a=JSON.parse(JSON.stringify(s.data));a.relationships=a.relationships??{};const c=a.relationships[fi(r.type)]??[];c.includes(r.to_id)||(a.relationships[fi(r.type)]=[...c,r.to_id]),await t.from("items").update({data:a,updated_by:i}).eq("id",r.from_id).eq("project_id",e.project_id);const l=JSON.parse(JSON.stringify(o.data));l.relationships=l.relationships??{};const m=l.relationships[fi(d)]??[];m.includes(r.from_id)||(l.relationships[fi(d)]=[...m,r.from_id]),await t.from("items").update({data:l,updated_by:i}).eq("id",r.to_id).eq("project_id",e.project_id)}else{await Promise.all([t.from("item_relationships").delete().eq("from_id",r.from_id).eq("to_id",r.to_id).eq("type",r.type).eq("project_id",e.project_id),t.from("item_relationships").delete().eq("from_id",r.to_id).eq("to_id",r.from_id).eq("type",d).eq("project_id",e.project_id)]);const n=JSON.parse(JSON.stringify(s.data));n.relationships?.[fi(r.type)]&&(n.relationships[fi(r.type)]=n.relationships[fi(r.type)].filter(e=>e!==r.to_id)),await t.from("items").update({data:n,updated_by:i}).eq("id",r.from_id).eq("project_id",e.project_id);const a=JSON.parse(JSON.stringify(o.data));a.relationships?.[fi(d)]&&(a.relationships[fi(d)]=a.relationships[fi(d)].filter(e=>e!==r.from_id)),await t.from("items").update({data:a,updated_by:i}).eq("id",r.to_id).eq("project_id",e.project_id)}const c={item_id:r.from_id,project_id:e.project_id,changed_by:i,event_type:"updated",old_data:null,new_data:{relationship_change:{action:r.action,type:r.type,from:r.from_id,to:r.to_id}},actor:"mcp_claude",session_id:Tr()};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 ct(Xe(`Self-reference in batch: "${t.from_id}"`));const i=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],{data:n}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",i),a=new Set((n??[]).map(e=>e.id)),s=i.filter(e=>!a.has(e));if(s.length>0)return ct(Ke("Items",s.join(", ")));const{data:o}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),d=new Map;for(const e of o??[])"parent"===e.type&&(d.has(e.from_id)||d.set(e.from_id,new Set),d.get(e.from_id).add(e.to_id));for(const t of e.operations){if("parent"!==t.type&&"child"!==t.type)continue;const[e,i]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?d.get(e)?.delete(i):(d.has(e)||d.set(e,new Set),d.get(e).add(i))}const c=0,l=1,m=2,p=new Map,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=[],i=[],r=e=>{p.set(e,l),i.push(e),t.push({node:e,parents:[...d.get(e)??[]],idx:0})};for(r(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){p.set(e.node,m),i.pop(),t.pop();continue}const n=e.parents[e.idx];e.idx++;const a=p.get(n)??c;if(a===l){const e=i.indexOf(n);return[...i.slice(e),n]}a!==m&&r(n)}return null};for(const e of u){const t=_(e);if(t)return ct(Xe(`Batch would create a cycle: ${t.join(" -> ")}. No changes applied.`))}const f=crypto.randomUUID(),h=e.operations.filter(e=>"remove"===e.action),g=e.operations.filter(e=>"add"===e.action);for(const t of[...h,...g])await r(t,f,e.reason);return dt(Qe({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?ct(Xe("Cannot create a relationship between an item and itself")):(await r({action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type},void 0,e.reason),!1===e.echo?dt(Qe({action:e.action,from_id:e.from_id,to_id:e.to_id})):dt(Qe({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}`}))):ct(Xe("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."))}catch(e){return ct(at(e))}}T(gi,{linkItemsHandler:()=>yi});var bi=O({"src/tools/link-items.ts"(){Be(),jt(),Dr(),mt(),_i=e=>"parent"===e?"child":"child"===e?"parent":"verifies"===e?"verified_by":"verified_by"===e?"verifies":"related",fi=e=>"parent"===e?"parents":"child"===e?"children":e}}),wi={};async function vi(e){try{if(!e.items||0===e.items.length)return ct(Xe("items array must contain at least 1 item"));if(e.items.length>100)return ct(Xe(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}if(ii("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:si(e.items)};if(!e.confirmation_token){const i=ri(t),r={};for(const t of e.items)r[t.type]=(r[t.type]??0)+1;return dt(Qe({status:"confirmation_required",preview:{total_items:e.items.length,by_type:r,sample_titles:e.items.slice(0,5).map(e=>e.title)},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_bulk_import with the same project_id, items array, and confirmation_token within ${i.expires_in_seconds}s to execute. Changing items will invalidate the token.`}))}const i=ni(e.confirmation_token,t);if(!i.valid)return ct(Xe(`confirmation_token rejected: ${i.reason}`))}const r=(new Date).toISOString(),n=Tr(),a=[],s=[],{data:o}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),d=o?.domains??[],c=d.length>0?new Set(d.map(ze).filter(e=>e.length>0)):null,l=[];for(let i=0;i<e.items.length;i++){const r=e.items[i],n=(r.domains??[]).map(ze).filter(e=>e.length>0),a=void 0!==r.level?ze(r.level):void 0;if(c&&n.length>0){const e=n.filter(e=>!c.has(e));if(e.length>0){s.push({index:i,title:r.title,error:`Unknown domain${e.length>1?"s":""}: ${e.join(", ")}. Registered: ${d.join(", ")}.`});continue}}try{const s=await vt(t,e.project_id,r.type);l.push({itemId:s,input:r,sanitizedDomains:n,sanitizedLevel:a,index:i})}catch(e){s.push({index:i,title:r.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===l.length)return dt(Qe({created:0,items:[],errors:s}));const m=[],p=new Map;for(const{itemId:t,input:n,sanitizedDomains:a,sanitizedLevel:s}of l){const o={id:t,type:n.type,title:n.title,summary:n.summary,body:n.body,tags:{domains:a,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:n.parent_id?[n.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:r,created_by:i,updated_at:r,updated_by:i}};p.set(t,o),m.push({id:t,project_id:e.project_id,type:n.type,title:n.title,data:o,created_by:i,updated_by:i})}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:i,p_event_source:"mcp"});if(_)for(const{itemId:r,input:o,index:d}of l){const c=m.find(e=>e.id===r);if(!c)continue;const{error:l}=await t.rpc("save_item_with_revision",{p_item_id:c.id,p_project_id:e.project_id,p_type:c.type,p_title:c.title,p_data:c.data,p_user_id:i,p_event_source:"mcp",p_event_session_id:n,p_diff_summary:null});l?s.push({index:d,title:o.title,error:l.message}):a.push({id:r,title:o.title,type:o.type})}else for(const{itemId:e,input:t}of l)a.push({id:e,title:t.title,type:t.type});const f=l.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>a.some(t=>t.id===e)).map(({itemId:t,input:i})=>({from_id:t,to_id:i.parent_id,type:"parent",project_id:e.project_id}));if(f.length>0){await t.from("item_relationships").insert(f).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk relationship sync failed: ${e.message}\n`)});const r=new Map;for(const e of f){const t=r.get(e.to_id)??[];t.push(e.from_id),r.set(e.to_id,t)}const n=Array.from(r.keys()),{data:a,error:s}=await t.from("items").select("id, data").eq("project_id",e.project_id).in("id",n);if(s)process.stderr.write(`[atoms-mcp] Warning: bulk parent JSONB read failed: ${s.message}\n`);else for(const n of a??[]){const a=JSON.parse(JSON.stringify(n.data??{}));a.relationships=a.relationships??{};const s=Array.isArray(a.relationships.children)?a.relationships.children:[],o=r.get(n.id)??[],d=Array.from(new Set([...s,...o]));if(d.length!==s.length){a.relationships.children=d;const{error:r}=await t.from("items").update({data:a,updated_by:i}).eq("id",n.id).eq("project_id",e.project_id);r&&process.stderr.write(`[atoms-mcp] Warning: bulk parent JSONB write failed for ${n.id}: ${r.message}\n`)}}}const h=a.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:p.get(t.id)??null,actor:"mcp_claude",session_id:n}));return 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`)}),dt(Qe({created:a.length,items:a,errors:s.length>0?s:[],project_id:e.project_id}))}catch(e){return ct(at(e))}}T(wi,{bulkImportHandler:()=>vi});var ji=O({"src/tools/bulk-import.ts"(){Be(),jt(),Dr(),di(),mt()}}),xi={};async function Si(e){try{const t=await De(),i=Re(),r=Pe();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const n=await _t(t,e.project_id,e.item_id);if(!n)return ct(Ke("Item",e.item_id));if("test-case"!==n.type)return ct(Xe(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const a=(e.asset??"").trim();let s=null,o=!1;if(a){const{data:r,error:n}=await t.from("assets").select("id").eq("project_id",e.project_id).eq("name",a).is("archived_at",null).maybeSingle();if(n)throw new Error(n.message);if(r)s=r.id;else{const{data:r,error:n}=await t.from("assets").insert({project_id:e.project_id,name:a,created_by:i}).select("id").single();if(n){if("23505"!==n.code)throw new Error(n.message);{const{data:i,error:r}=await t.from("assets").select("id").eq("project_id",e.project_id).eq("name",a).is("archived_at",null).single();if(r)throw new Error(r.message);s=i.id}}else s=r.id,o=!0}}const d=(new Date).toISOString(),{error:c}=await t.from("test_results").insert({item_id:e.item_id,project_id:e.project_id,result:e.result,run_by:r||i,run_at:d,note:e.note??null,asset:a||null});if(c)throw new Error(c.message);await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:d,note:e.note,asset:a||null},actor:"mcp_claude",session_id:Tr()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const l=a?` (asset: ${a})`:"";return dt(Qe({item_id:e.item_id,result:e.result,run_at:d,run_by:r||i,note:e.note??null,asset:a||null,asset_id:s,asset_created:o,message:`Test result '${e.result}' recorded for ${e.item_id}${l}`}))}catch(e){return ct(at(e))}}T(xi,{recordTestResultHandler:()=>Si});var ki=O({"src/tools/record-test-result.ts"(){Be(),jt(),Dr(),mt()}}),Ii={};async function Ei(e){try{const t=await De(),i=Re(),r=Pe();if(!Array.isArray(e.results)||0===e.results.length)return ct(Xe("results must be a non-empty array"));if(e.results.length>100)return ct(Xe(`results must have at most 100 entries (got ${e.results.length})`));try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const n=await _t(t,e.project_id,e.item_id);if(!n)return ct(Ke("Item",e.item_id));if("test-case"!==n.type)return ct(Xe(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const{data:a,error:s}=await t.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:r||i,p_actor_user_id:i,p_results:e.results});if(s)throw new Error(s.message);return t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:i,event_type:"test_result_recorded",old_data:null,new_data:{bulk:!0,count:e.results.length,results:a},actor:"mcp_claude",session_id:Tr()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),dt(Qe({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 ct(at(e))}}T(Ii,{recordTestResultsBulkHandler:()=>Ei});var Oi,Ti,Ai,Hi,Di=O({"src/tools/record-test-results-bulk.ts"(){Be(),jt(),Dr(),mt()}}),Ui={};async function Ci(e){try{const t=Math.min(Math.max(e.depth??5,1),10),i=await De(),r=await _t(i,e.project_id,e.item_id);if(!r)return ct(Ke("Item",e.item_id));const{data:n,error:a}=await i.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);const{data:s,error:o}=await i.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);const d=wt(n??[],s??[]),c=new Map;for(const e of n??[])c.set(e.id,{title:e.title,type:e.type});const l=new Map,m=(e,t,i)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:i})},p=e.relationship_types?new Set(e.relationship_types):null;for(const t of d??[]){const i=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(Ti.includes(i)&&(p&&!p.has(i)||m(t.from_id,t.to_id,i)),Ai.includes(i))){const e=Hi[i]??i;p&&!p.has(e)||m(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(Ai.includes(i)&&(p&&!p.has(i)||m(t.from_id,t.to_id,i)),Ti.includes(i))){const e=Hi[i]??i;p&&!p.has(e)||m(t.to_id,t.from_id,e)}"related"===i&&(p&&!p.has("related")||(m(t.from_id,t.to_id,"related"),m(t.to_id,t.from_id,"related")))}const u=new Set;u.add(e.item_id);const _=[],f=[],h=[],g=l.get(e.item_id)??[];for(const t of g)h.push({id:t.neighbor,depth:1,relType:t.relType,from:e.item_id});for(;h.length>0&&_.length<Oi;){const{id:e,depth:i,relType:r,from:n}=h.shift();if(u.has(e)||i>t)continue;u.add(e);const a=c.get(e);if(a&&(_.push({id:e,title:a.title,type:a.type,relationship:r,depth:i,from:n}),f.push({from:n,to:e,type:r}),i<t)){const t=l.get(e)??[];for(const r of t)u.has(r.neighbor)||h.push({id:r.neighbor,depth:i+1,relType:r.relType,from:e})}}const y=c.get(e.item_id),b=y?{id:e.item_id,title:y.title,type:y.type,relationship:"root",depth:0,from:e.item_id}:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown",relationship:"root",depth:0,from:e.item_id};return dt(Qe({root:e.item_id,direction:e.direction,depth_limit:t,items:[b,..._],edges:f,total_count:_.length+1,..._.length>=Oi?{truncated:!0,truncation_message:`Results capped at ${Oi} items. Use a smaller depth or filter by relationship_types.`}:{}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Ui,{traceHandler:()=>Ci});var qi=O({"src/tools/trace.ts"(){Be(),jt(),mt(),Oi=200,Ti=["parent","verifies"],Ai=["child","verified_by"],Hi={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related"}}}),Ri={};async function Pi(e){try{let t=(await De()).from("assets").select("id, name, archived_at, created_at").eq("project_id",e.project_id).order("name");e.include_archived||(t=t.is("archived_at",null));const{data:i,error:r}=await t;if(r)throw new Error(r.message);return dt(Qe({assets:i||[],total:(i||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Ri,{listAssetsHandler:()=>Pi});var Mi=O({"src/tools/assets.ts"(){Be(),mt()}}),$i={};async function Ni(e){try{const t=await De(),{data:i,error:r}=await t.from("project_variables").select("*").eq("project_id",e.project_id).order("name");if(r)throw new Error(r.message);return dt(Qe({variables:i||[],total:(i||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Wi(e){try{const t=await De(),{data:i,error:r}=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(r)throw new Error(r.message);if(!i)return ct(Ke("Variable",e.variable_name));const{data:n}=await t.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null),a=`{${e.variable_name}}`,s=(n||[]).filter(e=>(e.data?.body||"").includes(a));return dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Li(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}if(!(await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle()).data)return ct(Ke("Variable",e.variable_name));const r={updated_by:i,updated_at:(new Date).toISOString()};void 0!==e.value&&(r.value=e.value),void 0!==e.unit&&(r.unit=e.unit||null),void 0!==e.description&&(r.description=e.description||null);const{data:n,error:a}=await t.from("project_variables").update(r).eq("project_id",e.project_id).eq("name",e.variable_name).select().single();if(a)throw new Error(a.message);return dt(Qe({variable:n}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Vi(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const r=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const n=e.variables.filter(e=>!r.test(e.name));if(n.length>0)return ct(Xe(`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 ct(Xe(`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 ct(Xe(`Variable(s) already exist: ${d.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const c=e.variables.map(t=>({project_id:e.project_id,name:t.name,value:t.value,unit:t.unit??null,description:t.description??null,created_by:i,updated_by:i})),{data:l,error:m}=await t.from("project_variables").insert(c).select();if(m)throw new Error(m.message);return dt(Qe({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 ct(Xe("Provide either (name, value) for single variable or variables[] for batch."));if(!r.test(e.name))return ct(Xe(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const{data:n,error:a}=await t.from("project_variables").insert({project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null,created_by:i,updated_by:i}).select().single();if(a){if(a.message.includes("unique")||a.message.includes("duplicate"))return ct(Xe(`Variable "${e.name}" already exists in this project.`));throw new Error(a.message)}return!1===e.echo?dt(Qe({name:e.name})):dt(Qe({variable:n,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Bi(e){try{const t=await De();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("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 ct(Ke("Variable",e.name));const{data:r}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->>body","ilike",`%{${e.name}}%`),n=(r??[]).length;if(n>0&&!e.force)return ct(Xe(`Variable "${e.name}" is referenced in ${n} item${n>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(ii("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const i=ri(t);return dt(Qe({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:n,would_orphan_references:n>0},confirmation_token:i.token,expires_at:i.expires_at,expires_in_seconds:i.expires_in_seconds,message:`Re-call atoms_delete_variable with the same project_id, name, and confirmation_token within ${i.expires_in_seconds}s to execute.`}))}const i=ni(e.confirmation_token,t);if(!i.valid)return ct(Xe(`confirmation_token rejected: ${i.reason}`))}const{error:a}=await t.from("project_variables").delete().eq("project_id",e.project_id).eq("name",e.name);if(a)throw new Error(a.message);return dt(Qe({deleted:!0,name:e.name,referenced_by_items:n,warning:n>0?`${n} item${n>1?"s":""} still contain {${e.name}} — those references are now unresolved.`:void 0}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T($i,{createVariableHandler:()=>Vi,deleteVariableHandler:()=>Bi,getVariableHandler:()=>Wi,listVariablesHandler:()=>Ni,updateVariableHandler:()=>Li});var Fi=O({"src/tools/variables.ts"(){Be(),di(),mt()}}),Ji={};async function zi(e,t){const{data:i}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:i?.domains??[],levels:i?.levels??[]}}async function Qi(e,t,i,r){const{error:n}=await e.from("metadata").upsert({project_id:t,domains:i,levels:r},{onConflict:"project_id"});if(n)throw new Error(n.message)}async function Gi(e){try{const t=await De(),{domains:i}=await zi(t,e.project_id),{counts:r,orphans:n}=await async function(e,t,i){const{data:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null),n={};for(const e of i)n[e]=0;const a={};for(const e of r??[]){const t=e.data?.tags?.domains??[];for(const e of t)a[e]=(a[e]??0)+1,e in n&&n[e]++}const s=new Set(i),o={};for(const[e,t]of Object.entries(a))s.has(e)||(o[e]=t);return{counts:n,orphans:o}}(t,e.project_id,i),a=i.map(e=>({name:e,registered:!0,item_count:r[e]??0})),s=Object.entries(n).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),o=[...a,...s];return dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Yi(e){try{const t=await De();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{domains:i,levels:r}=await zi(t,e.project_id),n=e.name.trim().toLowerCase();return n?i.includes(n)?ct(Xe(`Domain "${n}" already exists in this project.`)):(await Qi(t,e.project_id,[...i,n],r),dt(Qe({domain:{name:n},message:`Domain "${n}" registered. You can now tag items with domains=["${n}"].`}))):ct(Xe("Domain name cannot be empty."))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Ki(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{domains:r,levels:n}=await zi(t,e.project_id),a=e.name.trim().toLowerCase(),s=e.new_name.trim().toLowerCase();if(!s)return ct(Xe("new_name cannot be empty."));const o=r.includes(a);if(!o){const{data:i}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a])).limit(1);if(!i||0===i.length)return ct(Ke("Domain",a))}if(s!==a&&r.includes(s))return ct(Xe(`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 dt(Qe({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;return m=o?r.map(e=>e===a?s:e):r.includes(s)?r:[...r,s],await Qi(t,e.project_id,m,n),(new Date).toISOString(),await Promise.all((d??[]).map(r=>{const n=(r.data?.tags?.domains??[]).map(e=>e===a?s:e),o={...r.data,tags:{...r.data?.tags??{},domains:n}};return t.from("items").update({data:o,updated_by:i}).eq("id",r.id).eq("project_id",e.project_id)})),dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}async function Zi(e){try{const t=await De(),i=Re();try{await Me(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ct(Ze("Viewer"));throw e}const{domains:r,levels:n}=await zi(t,e.project_id),a=e.name.trim().toLowerCase(),s=r.includes(a),{data:o,error:d}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(d)throw new Error(d.message);const c=(o??[]).length;if(!s&&0===c)return ct(Ke("Domain",a));if(c>0&&!e.force)return ct(Xe(`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(ii("atoms_delete_domain")){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:a};if(!e.confirmation_token){const e=ri(t);return dt(Qe({status:"confirmation_required",preview:{domain_name:a,items_using_count:c,would_strip_from_items:c>0},confirmation_token:e.token,expires_at:e.expires_at,expires_in_seconds:e.expires_in_seconds,message:`Re-call atoms_delete_domain with the same project_id, name, and confirmation_token within ${e.expires_in_seconds}s to execute.`}))}const i=ni(e.confirmation_token,t);if(!i.valid)return ct(Xe(`confirmation_token rejected: ${i.reason}`))}const l=s?r.filter(e=>e!==a):r;return await Qi(t,e.project_id,l,n),(new Date).toISOString(),c>0&&await Promise.all((o??[]).map(r=>{const n={...r.data,tags:{...r.data?.tags??{},domains:(r.data?.tags?.domains??[]).filter(e=>e!==a)}};return t.from("items").update({data:n,updated_by:i}).eq("id",r.id).eq("project_id",e.project_id)})),dt(Qe({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")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(Ji,{createDomainHandler:()=>Yi,deleteDomainHandler:()=>Zi,listDomainsHandler:()=>Gi,updateDomainHandler:()=>Ki});var Xi=O({"src/tools/domains.ts"(){Be(),di(),mt()}}),er={};async function tr(e){try{const t=await De(),{data:i,error:r}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle();if(r)throw new Error(r.message);if(!i)return ct(Ke("Project",e.project_id));const{data:n,error:a}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);const s=n??[],o={requirements:0,test_cases:0,notes:0},d=[],c=[];for(const e of s)if("requirement"===e.type){o.requirements++;const t=e.data?.tags?.domains??[];c.push({id:e.id,domains:t})}else"test-case"===e.type?(o.test_cases++,d.push(e.id)):"note"===e.type&&o.notes++;const l={passed:0,failed:0,blocked:0,not_run:0};if(d.length>0){const{data:i,error:r}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(r)throw new Error(r.message);const n=new Map;for(const e of i??[])n.has(e.item_id)||n.set(e.item_id,e.result);for(const e of d){const t=n.get(e);t&&"not-run"!==t?"passed"===t?l.passed++:"failed"===t?l.failed++:"blocked"===t?l.blocked++:l.not_run++:l.not_run++}}const{data:m,error:p}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(p)throw new Error(p.message);const u=wt(n??[],m??[]),_=new Set;for(const e of u)"verifies"===e.type?_.add(e.to_id):"verified_by"===e.type&&_.add(e.from_id);const f=c.filter(e=>_.has(e.id)).length,h=c.length,g={covered:f,uncovered:h-f,total:h,percent:h>0?Math.round(f/h*1e3)/10:100},y=new Map;for(const e of c){const t=e.domains.length>0?e.domains:["(untagged)"],i=_.has(e.id);for(const e of t){y.has(e)||y.set(e,{covered:0,total:0});const t=y.get(e);t.total++,i&&t.covered++}}const b=Array.from(y.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})),w=new Date;w.setDate(w.getDate()-7);const{count:v,error:j}=await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",w.toISOString());if(j)throw new Error(j.message);return dt(Qe({project_id:e.project_id,project_name:i.name,counts:o,test_status:l,coverage:g,coverage_by_domain:b,recent_changes:v??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(er,{projectSummaryHandler:()=>tr});var ir,rr=O({"src/tools/project-summary.ts"(){Be(),jt(),mt()}}),nr={};async function ar(e){try{const t=await De();let i,r;if(e.query&&e.query.trim().length>0){const n=await bt(t,e.project_id,e.query,{type:e.type,limit:e.limit});i=n.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=n.totalCount}else{const n=await ut(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});i=n.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=n.totalCount}const n=await async function(e,t){const{data:i,error:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(r)throw new Error(r.message);const n=new Set,a=new Set;for(const e of i??[]){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)n.add(t);const i=t.level;i&&a.add(i)}}return{domains:[...n].sort(),levels:[...a].sort()}}(t,e.project_id);return dt(Qe({items:i,filters:{domains:n.domains,levels:n.levels,types:ir},project_id:e.project_id},Ge(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(nr,{browseHandler:()=>ar});var sr,or,dr,cr,lr=O({"src/tools/browse.ts"(){Be(),jt(),mt(),ir=["requirement","test-case","note","table"]}}),mr={};async function pr(e){try{const t=e.direction??"downstream",i=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await De(),n=await _t(r,e.project_id,e.item_id);if(!n)return ct(Ke("Item",e.item_id));const{data:a,error:s}=await r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(s)throw new Error(s.message);const{data:o,error:d}=await r.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(d)throw new Error(d.message);const c=new Map;for(const e of o??[])c.set(e.id,{title:e.title,type:e.type});const l=new Map,m=(e,t,i)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:i})};for(const e of a??[]){const i=e.type;"upstream"!==t&&"both"!==t||(or.includes(i)&&m(e.from_id,e.to_id,i),dr.includes(i)&&m(e.to_id,e.from_id,cr[i]??i)),"downstream"!==t&&"both"!==t||(dr.includes(i)&&m(e.from_id,e.to_id,i),or.includes(i)&&m(e.to_id,e.from_id,cr[i]??i)),"related"===i&&(m(e.from_id,e.to_id,"related"),m(e.to_id,e.from_id,"related"))}const p=new Set;p.add(e.item_id);const 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<sr;){const{id:e,depth:t,path:r}=f.shift();if(p.has(e))continue;if(null!==i&&t>i)continue;p.add(e);const n=c.get(e);if(n&&(u.push({item_id:e,title:ot(n.title),type:n.type,depth:t,relationship_path:r}),t>_&&(_=t),null===i||t<i))for(const i of l.get(e)??[])p.has(i.neighbor)||f.push({id:i.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:i.neighbor,relationship_type:i.relType}]})}let h=0;if(e.include_variable_refs){const{data:t}=await r.from("variable_references").select("variable_id").eq("item_id",e.item_id).eq("project_id",e.project_id),i=[...new Set((t??[]).map(e=>e.variable_id))];if(i.length>0){const{data:t}=await r.from("project_variables").select("id, name").in("id",i),n=new Map((t??[]).map(e=>[e.id,e.name])),{data:a}=await r.from("variable_references").select("variable_id, item_id").in("variable_id",i).eq("project_id",e.project_id).neq("item_id",e.item_id);for(const t of a??[]){const i=t.item_id;if(p.has(i))continue;if(u.length>=sr)break;p.add(i);const r=c.get(i);if(!r)continue;const a=n.get(t.variable_id)??t.variable_id;u.push({item_id:i,title:ot(r.title),type:r.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:i,relationship_type:`variable_ref:${a}`}]}),h++}}}const g={};for(const e of u)g[e.type]=(g[e.type]??0)+1;const y=c.get(e.item_id);return dt(Qe({root:{item_id:e.item_id,title:ot(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>=sr?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):ct(st(e instanceof Error?e.message:String(e)))}}T(mr,{impactAnalysisHandler:()=>pr});var ur=O({"src/tools/impact-analysis.ts"(){Be(),jt(),mt(),sr=200,or=["parent","verifies","traces_to","allocated_from","decomposed_from"],dr=["child","verified_by","allocated_to","decomposes_to","traced_by"],cr={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"}}}),_r={};function fr(e){return e instanceof Error&&e.message.includes("Not authenticated")?ct(et()):null}async function hr(e,t,i){const{data:r,error:n}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(n)return ct(st(n.message));if(!r)return ct(Ke("Project",t));const{data:a,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?ct(st(s.message)):!0!==(a?.feature_flags??{})[i]?ct(Ye(`Feature '${i}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function gr(e){try{const t=await De(),i=await async function(e,t){const{data:i,error:r}=await e.from("baselines").select("id, project_id, name, description, snapshot_at, created_at, created_by, locked_at, locked_by").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1});if(r)throw new Error(`listBaselines: ${r.message}`);return i??[]}(t,e.project_id),r=Math.max(e.offset??0,0),n=Math.min(Math.max(e.limit??50,1),100);return dt(Qe({baselines:i.slice(r,r+n).map(e=>({id:e.id,name:e.name,description:e.description,snapshot_at:e.snapshot_at,created_at:e.created_at,created_by:e.created_by,locked:null!==e.locked_at,locked_at:e.locked_at})),total:i.length,offset:r,limit:n}))}catch(e){return fr(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function yr(e){try{const t=await De(),i=await hr(t,e.project_id,"baselines_enabled");if(i)return i;const{data:r,error:n}=await t.from("baselines").insert({project_id:e.project_id,name:e.name.trim(),description:e.description??null,snapshot_at:(new Date).toISOString()}).select().single();return n?"23505"===n.code?ct(Ye(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):ct(st(n.message)):dt(Qe({id:r.id,name:r.name,description:r.description,snapshot_at:r.snapshot_at,created_at:r.created_at,locked:!1}))}catch(e){return fr(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function br(e){try{const t=await De(),i=await ht(t,e.baseline_id);if(!i)return ct(Ke("Baseline",e.baseline_id));const r=await hr(t,i.project_id,"baselines_enabled");if(r)return r;if(null!==i.locked_at)return ct(Ye("Baseline is already locked",["Locks are one-way; nothing to do"]));const{data:n}=await t.from("projects").select("org_id").eq("id",i.project_id).maybeSingle();if(!n)return ct(Ke("Project",i.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return ct(et());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 ct(Ye("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?ct(st(c.message)):dt(Qe({id:d.id,locked_at:d.locked_at,locked_by:d.locked_by}))}catch(e){return fr(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function wr(e){try{const t=await De(),[i,r]=await Promise.all([ht(t,e.baseline_a_id),ht(t,e.baseline_b_id)]);if(!i||!r)return ct(Ke("Baseline","one of the baseline_ids"));if(i.project_id!==r.project_id)return ct(Ye("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[n,a]=await Promise.all([yt(t,i.project_id,i.snapshot_at),yt(t,r.project_id,r.snapshot_at)]),s=new Map(n.map(e=>[e.id,e])),o=new Map(a.map(e=>[e.id,e])),d=Array.from(new Set([...s.keys(),...o.keys()])).sort(),c=[];let l=0,m=0,p=0;for(const e of d){const t=s.get(e),i=o.get(e);if(!t&&i)l++,c.push({item_id:e,change_type:"added"});else if(t&&!i)m++,c.push({item_id:e,change_type:"removed"});else if(t&&i){const r=[];t.title!==i.title&&r.push("title"),t.type!==i.type&&r.push("type");JSON.stringify(t.data??{})!==JSON.stringify(i.data??{})&&r.push("data"),r.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:r}))}}const 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:i})=>({item_id:e,change_type:t,fields_changed:i}));return dt(Qe({summary:{added:l,removed:m,modified:p,total_compared:d.length},items:f,page_info:{offset:u,limit:_,total:c.length},baselines:{a:{id:i.id,name:i.name,snapshot_at:i.snapshot_at},b:{id:r.id,name:r.name,snapshot_at:r.snapshot_at}}}))}catch(e){return fr(e)??ct(st(e instanceof Error?e.message:String(e)))}}async function vr(e){try{const t=await De(),i=await ht(t,e.baseline_id);if(!i)return ct(Ke("Baseline",e.baseline_id));const r=await hr(t,i.project_id,"baselines_enabled");if(r)return r;const{data:n}=await t.from("projects").select("org_id").eq("id",i.project_id).maybeSingle();if(!n)return ct(Ke("Project",i.project_id));const{data:a}=await t.auth.getUser(),s=a?.user?.id;if(!s)return ct(et());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 ct(Ye("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const d=await yt(t,i.project_id,i.snapshot_at);if(!0!==e.confirm)return dt(Qe({preview:!0,items_to_restore:d.length}));if(0===d.length)return dt(Qe({ok:!0,items_restored:0}));const c=d.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{data:l,error:m}=await t.rpc("bulk_save_items_with_revisions",{p_project_id:i.project_id,p_items:c,p_user_id:s,p_event_source:"restore"});return m?ct(st(m.message)):dt(Qe({ok:!0,items_restored:"number"==typeof l?l:d.length}))}catch(e){return fr(e)??ct(st(e instanceof Error?e.message:String(e)))}}T(_r,{createBaselineHandler:()=>yr,diffBaselinesHandler:()=>wr,listBaselinesHandler:()=>gr,lockBaselineHandler:()=>br,restoreBaselineHandler:()=>vr});var jr,xr,Sr,kr,Ir=O({"src/tools/baselines.ts"(){Be(),mt(),jt()}});function Er(t){z(t.toolName)&&function(t,i){const r=`ui://${i.toolName}/${i.htmlFile}`,n=function(e,t){const i=u(import.meta.url),r=s.dirname(i);return s.resolve(r,"apps","src","apps",e,t)}(i.appName,i.htmlFile),a=[...lt.resourceDomains,...i.extraResourceDomains??[]];c(t,i.toolName,{title:i.title,description:i.description,inputSchema:i.inputSchema,annotations:i.annotations,_meta:{ui:{resourceUri:r}}},i.handler),l(t,`${i.title} UI`,r,{mimeType:m},async()=>{const t=await e.readFile(n,"utf-8");return{contents:[{uri:r,mimeType:m,text:t,_meta:{ui:{csp:{resourceDomains:a}}}}]}})}(jr,t)}function Or(e,t){return async i=>{const r=function(e,t){if(C.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&&q.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&R.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&P.has(t))return{allowed:!1,reason:"block_bulk_import"};const i=V(t);return void 0===i||e.allowed_toolsets.includes(i)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}(re(),e);if(!r.allowed)return ct(Ye(`Tool ${e} is blocked by org policy.`,[ae(r.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=Z();if(!t)return;if("object"!=typeof e||null===e)return;const i=e.project_id;if("string"==typeof i&&i!==t)throw new Y(t,i)}(i)}catch(e){if(e instanceof Y)return ct(it(e.expectedProjectId));throw e}{const e=re(),t=i?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return ct(Ye("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 De(),n=Re()}catch{return t(i)}const s=await async function(e,t){const i=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||D,r=new Date,n=new Date(r.getTime()-U);try{const{count:a,error:s}=await t.from("mcp_rate_limits").select("id",{count:"exact",head:!0}).eq("user_id",e).gte("requested_at",n.toISOString());if(s)throw new Error(s.message);if((a??0)>=i){const{data:i,error:a}=await t.from("mcp_rate_limits").select("requested_at").eq("user_id",e).gte("requested_at",n.toISOString()).order("requested_at",{ascending:!0}).limit(1).maybeSingle();if(a)throw new Error(a.message);const s=(i?new Date(i.requested_at).getTime():r.getTime())+U-r.getTime();return{allowed:!1,retryAfterSeconds:Math.max(1,Math.ceil(s/1e3))}}t.from("mcp_rate_limits").insert({user_id:e,requested_at:r.toISOString()}).then(({error:e})=>{e&&process.stderr.write(`[rate-limiter] insert failed: ${e.message}\n`)});const o=new Date(r.getTime()-2*U);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 ct(rt(s.retryAfterSeconds));if("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN){const e=i?.project_id;if("string"==typeof e)try{const{requireWriteAccess:t}=await Promise.resolve().then(()=>(Be(),He));await t(a,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(mt(),Fe));return ct(e("Viewer (lockdown mode: read access requires editor or admin)"))}}}const o=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let d,c="success";try{const e=await t(i),r=e;if(!0===r?.isError){c="error";const e=r?.content;if(e?.[0]?.text)try{d=JSON.parse(e[0].text).message}catch{}}return e}catch(e){throw c="error",d=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:i,status:c,duration_ms:o(),error_msg:d,project_id:i.project_id,session_id:Sr,client_name:kr};try{!function(e,t,i){const r=H(i.params);e.from("mcp_audit_log").insert({user_id:t,tool_name:i.tool_name,params:r,status:i.status,duration_ms:i.duration_ms,error_msg:i.error_msg??null,project_id:i.project_id??null,session_id:i.session_id??null,client_name:i.client_name??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await De(),n,t)}catch{}}}}function Tr(){return Sr}var Ar,Hr,Dr=O({"src/server.ts"(){W(),L(),K(),te(),ne(),de(),Be(),mt(),pt(),jr=new y({name:"atoms-mcp-server",version:"0.11.1"}),xr=(e,t,i)=>{if(z(e))return jr.registerTool(e,t,i)},Sr=f(),kr=process.env.ATOMS_CLIENT_NAME??"unknown",xr("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(()=>(be(),ce)),i=await e();if(!i)return{content:[{type:"text",text:JSON.stringify({status:"not_authenticated",message:"No ATOMS credentials found. You need to login first.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp login","3. Complete the login in your browser","4. Restart Claude Desktop (quit and reopen)","5. Try your query again"]},null,2)}]};if(!t(i))try{const{getValidToken:e}=await Promise.resolve().then(()=>(Ae(),je)),{email:t}=await e(),{invalidateClient:i}=await Promise.resolve().then(()=>(Be(),He));return i(),{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:t,message:"Token was expired but has been refreshed. You're good to go!"},null,2)}]}}catch{return{content:[{type:"text",text:JSON.stringify({status:"expired",email:i.user_email??"unknown",message:"Your session has expired and could not be refreshed.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp logout","3. Run: npx @atoms-tech/atoms-mcp login","4. Complete the login in your browser","5. Restart Claude Desktop (quit and reopen)"]},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:i.user_email??"unknown",message:"ATOMS MCP is connected and authenticated. All tools are ready."},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({status:"error",message:`Health check failed: ${e instanceof Error?e.message:String(e)}`,next_steps:["1. Open a terminal","2. Run: npx @atoms-tech/atoms-mcp login","3. Restart Claude Desktop"]},null,2)}]}}}),xr("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}},Or("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(kt(),xt));return e()})),xr("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:b.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:b.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:b.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:b.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:b.number().int().min(0).default(0).describe("Pagination offset (default 0)"),baseline_id:b.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:b.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}},Or("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(Ot(),It));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:b.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:b.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}},Or("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(Ht(),Tt));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),query:b.string().min(1).max(1e3).describe("Search text"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),asset:b.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:b.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:b.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}},Or("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(Ct(),Dt));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),query:b.string().min(1).max(1e3).describe("Natural-language concept query"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:b.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(Pt(),qt));return t(e)})),Er({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:b.string().uuid().describe("UUID of the project"),domain:b.string().max(64).optional().describe("Filter by domain tag"),level:b.string().max(32).optional().describe("Filter by level"),baseline_id:b.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:b.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Or("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(Nt(),Mt));return t(e)})}),xr("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_claude) 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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID"),limit:b.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(Vt(),Wt));return t(e)})),Er({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:b.string().uuid().describe("UUID of the project"),root_item_id:b.string().max(20).optional().describe("Root item ID to start from"),depth:b.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:b.boolean().default(!0).describe("Include test case links"),baseline_id:b.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:b.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},extraResourceDomains:["cdn.jsdelivr.net","mermaid.ink"],handler:Or("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(zt(),Bt));return t(e)})}),xr("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\nReturns:\n Created item with generated ID (e.g., \"REQ-058\")\n\nSide effects:\n - Logs to change_history with actor='mcp_claude'\n - Creates relationships if parent_ids provided",inputSchema:{project_id:b.string().uuid().describe("UUID of the target project"),type:b.enum(["requirement","test-case","note"]).describe("Item type"),title:b.string().min(1).max(500).describe("Item title"),body:b.string().max(5e4).optional().describe("Rich text body"),summary:b.string().max(2e3).optional().describe("Brief summary"),domains:b.array(b.string().max(64)).max(20).optional().describe("Domain tags"),level:b.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:b.array(b.string().max(20)).max(50).optional().describe("Parent item IDs to link"),echo:b.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Or("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Yt(),Qt));return t(e)})),xr("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\nReturns:\n Updated item.",inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).optional().describe("Item ID (single form)"),title:b.string().min(1).max(500).optional().describe("New title"),body:b.string().max(5e4).optional().describe("New body"),summary:b.string().max(2e3).optional().describe("New summary"),domains:b.array(b.string().max(64)).max(20).optional().describe("New domain tags"),level:b.string().max(32).optional().describe("New level"),status:b.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status"),echo:b.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:b.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:b.array(b.object({item_id:b.string().min(1).max(20),title:b.string().min(1).max(500).optional(),body:b.string().max(5e4).optional(),summary:b.string().max(2e3).optional(),domains:b.array(b.string().max(64)).max(20).optional(),level:b.string().max(32).optional(),status:b.enum(["passed","failed","blocked","not-run"]).optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:b.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:b.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(ti(),Kt));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:b.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}},Or("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(mi(),ci));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().max(256).describe("ID of the soft-deleted item to restore")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(hi(),pi));return t(e)})),xr("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\nReturns:\n Updated relationship state for both items.",inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),from_id:b.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:b.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:b.enum(["parent","child","related","verifies","verified_by"]).optional().describe("Relationship type"),action:b.enum(["add","remove"]).optional().describe("Add or remove"),echo:b.boolean().optional().describe("false → lean response"),reason:b.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:b.array(b.object({action:b.enum(["add","remove"]),from_id:b.string().min(1).max(20),to_id:b.string().min(1).max(20),type:b.enum(["parent","child","related","verifies","verified_by"])})).optional().describe("Array form: batch relationship ops. Always atomic with DAG cycle detection."),idempotency_key:b.string().max(128).optional().describe("Safe retry key (24h TTL)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(bi(),gi));return t(e)})),Er({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_claude' for each created item\n - Creates parent relationships for items with parent_id",inputSchema:{project_id:b.string().uuid().describe("UUID of the target project"),items:b.array(b.object({type:b.enum(["requirement","test-case","note"]).describe("Item type"),title:b.string().min(1).max(500).describe("Item title"),body:b.string().max(5e4).optional().describe("Rich text body"),summary:b.string().max(2e3).optional().describe("Brief summary"),domains:b.array(b.string().max(64)).max(20).optional().describe("Domain tags"),level:b.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:b.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)"),confirmation_token:b.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:Or("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(ji(),wi));return t(e)})}),xr("atoms_record_test_result",{title:"Record Test Result",description:"Record a pass/fail/blocked result for a test case.\n\nAppends to the test results history. 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 test_results table\n - Inserts into assets table if asset name is new in this project\n - Logs to change_history with actor='mcp_claude'",inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:b.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:b.string().max(1e3).optional().describe("Reason or comment for this result"),asset:b.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}},Or("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(ki(),xi));return t(e)})),xr("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. The whole call is one DB transaction — any entry failure\nrolls 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 - Inserts into test_results (one row per entry)\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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:b.array(b.object({asset:b.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:b.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:b.string().max(500).optional().describe("Run note"),date:b.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}},Or("atoms_record_test_results",async e=>{const{recordTestResultsBulkHandler:t}=await Promise.resolve().then(()=>(Di(),Ii));return t(e)})),Er({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)\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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Starting item ID"),direction:b.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:b.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:b.array(b.enum(["parent","child","related","verifies","verified_by"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Or("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(qi(),Ui));return t(e)})}),xr("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:b.string().uuid().describe("UUID of the project"),include_archived:b.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(Mi(),Ri));return t(e)})),xr("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\nReturns:\n { variables: [{ id, name, value, unit, description }], total }",inputSchema:{project_id:b.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(Fi(),$i));return t(e)})),xr("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\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',inputSchema:{project_id:b.string().uuid().describe("UUID of the project"),variable_name:b.string().min(1).max(64).describe("Variable name")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(Fi(),$i));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),variable_name:b.string().min(1).max(64).describe("Variable name"),value:b.string().max(500).optional().describe("New value"),unit:b.string().max(32).optional().describe("Unit abbreviation"),description:b.string().max(2e3).optional().describe("Description")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(Fi(),$i));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).optional().describe("Variable name (single form)"),value:b.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:b.string().max(32).optional().describe("Unit abbreviation"),description:b.string().max(2e3).optional().describe("Description"),echo:b.boolean().optional().describe("false → lean response (default true)"),variables:b.array(b.object({name:b.string().min(1).max(64).describe("Variable name"),value:b.string().min(1).max(500).describe("Initial value"),unit:b.string().max(32).optional().describe("Unit abbreviation"),description:b.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:b.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Or("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(Fi(),$i));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Variable name to delete"),force:b.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:b.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}},Or("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(Fi(),$i));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(Xi(),Ji));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Or("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(Xi(),Ji));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Current domain name"),new_name:b.string().min(1).max(64).describe("New domain name"),dry_run:b.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Or("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(Xi(),Ji));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(64).describe("Domain name to delete"),force:b.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:b.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}},Or("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(Xi(),Ji));return t(e)})),Er({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:b.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Or("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(rr(),er));return t(e)})}),Er({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:b.string().uuid().describe("UUID of the project"),type:b.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:b.string().max(64).optional().describe("Filter by domain tag"),level:b.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:b.string().max(1e3).optional().describe("Full-text search query"),limit:b.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:b.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Or("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(lr(),nr));return t(e)})}),xr("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:b.string().uuid().describe("UUID of the project"),item_id:b.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:b.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:b.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:b.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(ur(),mr));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),limit:b.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:b.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(Ir(),_r));return t(e)})),xr("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:b.string().uuid().describe("UUID of the project"),name:b.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:b.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Or("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(Ir(),_r));return t(e)})),xr("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:b.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Or("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(Ir(),_r));return t(e)})),xr("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:b.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:b.string().uuid().describe("UUID of the second (newer) baseline"),detail:b.boolean().default(!1).describe("Include per-item field-level diffs (default false)"),limit:b.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:b.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Or("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(Ir(),_r));return t(e)})),xr("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:b.string().uuid().describe("UUID of the baseline to restore from"),confirm:b.boolean().default(!1).describe("Set true to execute; false (default) returns a preview")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Or("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(Ir(),_r));return t(e)}))}}),Ur={};async function Cr(){const e=h(32).toString("base64url"),t=g("sha256").update(e).digest("base64url"),i=`http://localhost:${Ar}${Hr}`,r=new p(`${ye}/auth/mcp-consent`);return r.searchParams.set("redirect_uri",i),r.searchParams.set("code_challenge",t),r.searchParams.set("code_challenge_method","S256"),new Promise((t,i)=>{let n;function a(){clearTimeout(n)}const s=w(async(r,n)=>{const o=new p(r.url??"/",`http://localhost:${Ar}`);if(o.pathname!==Hr)return n.writeHead(404),void n.end("Not found");try{if("access_denied"===o.searchParams.get("error"))return n.writeHead(200,{"Content-Type":"text/html"}),n.end(Rr("Authorization was cancelled.")),a(),s.close(),void i(new Error("Authorization cancelled by user."));const r=o.searchParams.get("code");if(r){const o=await fetch(`${he}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:ge},body:JSON.stringify({auth_code:r,code_verifier:e})}),d=await o.json();if(!o.ok||!d.access_token){const e=d.error_description??d.msg??"Unknown error";return n.writeHead(200,{"Content-Type":"text/html"}),n.end(Rr(`Code exchange failed: ${e}`)),a(),s.close(),void i(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(d.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(he,ge,{global:{headers:{Authorization:`Bearer ${d.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(Rr('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://atoms.tech">atoms.tech</a> first, then run this login command again.')),a(),s.close(),void i(new Error("No ATOMS account found. Sign up at atoms.tech first."))):(await me({access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Date.now()+1e3*(d.expires_in??3600),user_email:c}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(qr(c)),a(),s.close(),void t({email:c}))}const d=o.searchParams.get("access_token"),c=o.searchParams.get("refresh_token"),l=parseInt(o.searchParams.get("expires_in")??"3600",10);d&&c?(await me({access_token:d,refresh_token:c,expires_at:Date.now()+1e3*l}),n.writeHead(200,{"Content-Type":"text/html"}),n.end(qr("authenticated")),a(),s.close(),t({email:"authenticated"})):(n.writeHead(200,{"Content-Type":"text/html"}),n.end("<!DOCTYPE html>\n<html>\n<head><title>ATOMS MCP Login</title></head>\n<body>\n <h1>Completing login...</h1>\n <script>\n const hash = window.location.hash.substring(1);\n const params = new URLSearchParams(hash);\n const data = {\n access_token: params.get('access_token'),\n refresh_token: params.get('refresh_token'),\n expires_in: params.get('expires_in'),\n user_email: ''\n };\n if (data.access_token) {\n // Decode JWT to get email\n try {\n const payload = JSON.parse(atob(data.access_token.split('.')[1]));\n data.user_email = payload.email || '';\n } catch(e) {}\n fetch('/token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data)\n }).then(() => {\n document.body.innerHTML = '<h1>Login successful! You can close this tab.</h1>';\n }).catch(() => {\n document.body.innerHTML = '<h1>Login failed. Please try again.</h1>';\n });\n } else {\n document.body.innerHTML = '<h1>Login failed — no tokens received.</h1>';\n }\n <\/script>\n</body>\n</html>"))}catch(e){n.writeHead(500),n.end("Authentication failed"),a(),s.close(),i(e)}});s.on("request",async(e,r)=>{if("POST"===e.method&&"/token"===e.url){let n="";e.on("data",e=>{n+=e.toString()}),e.on("end",async()=>{try{const e=JSON.parse(n);await me({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0})),a(),s.close(),t({email:e.user_email??"authenticated"})}catch(e){r.writeHead(500),r.end("Failed to store credentials"),a(),s.close(),i(e)}})}}),s.listen(Ar,"127.0.0.1",async()=>{process.stderr.write("\nOpening browser for ATOMS login...\n"),process.stderr.write(`If the browser doesn't open, visit:\n${r.toString()}\n\n`);try{const{default:e}=await import("open");await e(r.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),n=setTimeout(()=>{s.close(),i(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function qr(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 Rr(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>`}T(Ur,{login:()=>Cr});var Pr=O({"src/auth/login.ts"(){be(),ve(),Ar=19275,Hr="/callback"}});Dr(),K(),ne(),Be(),ie();var Mr=process.argv.slice(2)[0];(async function(){switch(Mr){case"login":{const{login:e}=await Promise.resolve().then(()=>(Pr(),Ur));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(()=>(Ae(),je));try{const{email:t,user_id:i}=await e();process.stderr.write(`\n [32m✓[0m Logged in as ${t}\n [90mUser ID: ${i}[0m\n\n`)}catch(e){process.stderr.write("\n [31m✗[0m Not authenticated.\n Run: npx @atoms-tech/atoms-mcp login\n\n"),process.exit(1)}break}case"logout":{const{clearCredentials:e}=await Promise.resolve().then(()=>(be(),ce));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 v0.4.0\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(()=>(Ae(),je)),{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(()=>(Pr(),Ur)),{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`)}}process.stderr.write(`[atoms-mcp] Tool registry: ${function(){const e=J(),t=F(),i=[];i.push(e?"read-only":"read+write"),null===t?i.push("all toolsets"):(i.push(`toolsets=${[...t.allowed].sort().join(",")||"(none — only always-on tools)"}`),t.unknown.length>0&&i.push(`unknown=${t.unknown.join(",")}`));const r=process.env.ATOMS_MCP_PROJECT_ID?.trim();return r&&i.push(`project_scope=${r.slice(0,8)}…`),("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN)&&i.push("lockdown=on"),i.join(" | ")}()}\n`);try{const t=await De(),i=Re(),r=await async function(e,t){const i=process.env.ATOMS_MCP_ORG_ID?.trim();if(i)return i;const{data:r,error:n}=await e.from("org_members").select("org_id, joined_at").eq("user_id",t).order("joined_at",{ascending:!0}).limit(1).maybeSingle();return n?(process.stderr.write(`[atoms-mcp] Could not resolve session org: ${n.message}\n`),null):r?.org_id??null}(t,i),n=await async function(e,t,i){if(!i)return{role:null,is_member:!1,effective:X};const{data:r,error:n}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:i});return n?(process.stderr.write(`[atoms-mcp] mcp_resolve_policy failed (${n.code}): ${n.message}. Falling back to permissive policy.\n`),{role:null,is_member:!1,effective:X}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:X};const t=e,i="string"==typeof t.role?t.role:null,r=!0===t.is_member,n=t.effective??{},a=(e,t)=>Array.isArray(e)?e.filter(e=>"string"==typeof e):t,s=(e,t)=>"boolean"==typeof e?e:t,o=n.project_scope,d=Array.isArray(o)&&o.length>0?o.filter(e=>"string"==typeof e):null;return{role:i,is_member:r,effective:{read_only:s(n.read_only,X.read_only),lockdown:s(n.lockdown,X.lockdown),block_destructive:s(n.block_destructive,X.block_destructive),block_bulk_import:s(n.block_bulk_import,X.block_bulk_import),cross_project_browse:s(n.cross_project_browse,X.cross_project_browse),allowed_toolsets:a(n.allowed_toolsets,X.allowed_toolsets),forbidden_tools:a(n.forbidden_tools,X.forbidden_tools),project_scope:d,require_confirmation_for:a(n.require_confirmation_for,X.require_confirmation_for)}}}(r)}(t,i,r);e={effective:n.effective,role:n.role,org_id:r},ee=e.effective,n.is_member&&r?process.stderr.write(`[atoms-mcp] Org policy loaded: org=${r.slice(0,8)}… role=${n.role??"?"} read_only=${n.effective.read_only} lockdown=${n.effective.lockdown}\n`):process.stderr.write("[atoms-mcp] No org membership detected — running with permissive default policy.\n")}catch(e){process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). Running with permissive default — RLS still enforces row-level access.\n`)}const t=new v;await jr.connect(t),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)});
|