@atoms-tech/atoms-mcp 0.47.0 → 0.58.10

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 CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var e=require("fs/promises"),t=require("os"),r=require("path"),a=require("@supabase/supabase-js"),i=require("http"),n=require("crypto"),s=require("url"),o=require("zod"),c=require("@modelcontextprotocol/ext-apps/server"),l=require("@modelcontextprotocol/sdk/server/mcp.js"),d=require("module"),p=require("@modelcontextprotocol/sdk/server/stdio.js"),u="undefined"!=typeof document?document.currentScript:null;function m(e){return e&&e.__esModule?e:{default:e}}var _,f,h,g,y,w,v,b=m(e),j=m(r),k=m(n),S=Object.defineProperty,A=Object.getOwnPropertyNames,x=(e,t,r)=>function(){if(r)throw r[0];try{return e&&(t=(0,e[A(e)[0]])(e=0)),t}catch(e){throw r=[e],e}},E=(e,t)=>{for(var r in t)S(e,r,{get:t[r],enumerable:!0})};function I(e){return v.get(e)}var R=x({"src/core/tool-catalog.ts"(){_=new Set(["atoms_status","atoms_list_projects"]),f=new Set(["atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_link_items","atoms_bulk_import","atoms_record_test_result","atoms_record_test_results","atoms_create_variable","atoms_update_variable","atoms_delete_variable","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_create_level","atoms_delete_level","atoms_reorder_levels","atoms_create_field","atoms_delete_field","atoms_reorder_fields","atoms_create_baseline","atoms_lock_baseline","atoms_restore_baseline","atoms_create_analysis","atoms_fill_row","atoms_link_mitigation","atoms_propose_rows","atoms_suggest_field","atoms_approve_row"]),h=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_level","atoms_delete_field","atoms_restore_baseline"]),g=new Set(["atoms_bulk_import"]),y={items:["atoms_list_items","atoms_get_item","atoms_search","atoms_semantic_search","atoms_browse","atoms_get_history","atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_bulk_import"],traceability:["atoms_trace","atoms_link_items","atoms_export_mermaid","atoms_impact_analysis"],coverage:["atoms_get_coverage","atoms_verification_status","atoms_record_test_result","atoms_record_test_results","atoms_project_summary","atoms_list_assets"],variables:["atoms_list_variables","atoms_get_variable","atoms_create_variable","atoms_update_variable","atoms_delete_variable"],domains:["atoms_list_domains","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_list_levels","atoms_create_level","atoms_delete_level","atoms_reorder_levels","atoms_list_fields","atoms_create_field","atoms_delete_field","atoms_reorder_fields"],baselines:["atoms_list_baselines","atoms_create_baseline","atoms_lock_baseline","atoms_diff_baselines","atoms_restore_baseline"],analysis:["atoms_create_analysis","atoms_fill_row","atoms_get_analysis","atoms_link_mitigation","atoms_get_gaps","atoms_propose_rows","atoms_suggest_field","atoms_approve_row","atoms_list_scenario_catalogs","atoms_mutate_scenario_catalog"]},w=Object.keys(y),v=new Map;for(const[e,t]of Object.entries(y))for(const r of t)v.set(r,e)}});function O(e,t){if(_.has(t))return{allowed:!0};if(e.lockdown&&!new Set(["atoms_list_items","atoms_get_item","atoms_search","atoms_browse"]).has(t))return{allowed:!1,reason:"lockdown"};if(e.forbidden_tools.includes(t))return{allowed:!1,reason:"forbidden_tool"};if(e.read_only&&f.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&h.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&g.has(t))return{allowed:!1,reason:"block_bulk_import"};const r=I(t);return void 0===r||e.allowed_toolsets.includes(r)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function $(e,t){return O(e,t).allowed}function q(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 z,M,T,H,D=x({"src/core/policy.ts"(){R()}}),C=x({"src/core/types.ts"(){z={read_only:!1,lockdown:!1,block_destructive:!1,block_bulk_import:!1,cross_project_browse:!0,allowed_toolsets:["items","traceability","coverage","variables","domains","baselines","analysis"],forbidden_tools:[],project_scope:null,require_confirmation_for:[]},M={read_only:!0,lockdown:!0,block_destructive:!0,block_bulk_import:!0,cross_project_browse:!1,allowed_toolsets:[],forbidden_tools:[],project_scope:[],require_confirmation_for:[]}}});function P(){return T}var U=x({"src/middleware/session-policy.ts"(){C(),T=z,H=null}});function N(){const e=process.env.ATOMS_MCP_TOOLSETS?.trim();if(!e)return null;const t=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===t.length)return null;const r=new Set,a=[];for(const e of t)w.includes(e)?r.add(e):a.push(e);return{allowed:r,unknown:a}}function L(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function F(e){if(L()&&f.has(e))return!1;if(_.has(e))return!0;const t=N();if(null===t)return $(P(),e);const r=I(e);return!!r&&!!t.allowed.has(r)&&$(P(),e)}var W,V,B=x({"src/middleware/tool-registry.ts"(){R(),D(),U()}}),J={};async function Q(){try{const t=await e.readFile(V,"utf-8"),r=JSON.parse(t);return r.access_token&&r.refresh_token?r:null}catch{return null}}async function G(t){await e.mkdir(W,{recursive:!0,mode:448}),await e.writeFile(V,JSON.stringify(t,null,2),{mode:384})}async function Y(){const e=await Q();return!!e&&e.expires_at>Date.now()+6e4}function K(e){return e.expires_at>Date.now()+6e4}async function Z(){try{await e.unlink(V)}catch{}}function X(){return V}E(J,{clearCredentials:()=>Z,getCredentialsPath:()=>X,hasValidCredentials:()=>Y,isTokenValid:()=>K,readCredentials:()=>Q,writeCredentials:()=>G});var ee,te,re,ae,ie,ne,se,oe=x({"src/auth/token-store.ts"(){W=r.join(t.homedir(),".atoms"),V=r.join(W,"credentials.json")}}),ce={};async function le(){try{await e.mkdir(ee,{recursive:!0,mode:448});const t=await e.open(te,"wx");try{await t.writeFile(`${process.pid} ${Date.now()}`)}finally{await t.close()}return!0}catch(e){if("EEXIST"===e.code)return!1;throw e}}async function de(){try{await e.unlink(te)}catch{}}async function pe(){try{const t=await e.stat(te);return Date.now()-t.mtimeMs>re}catch{return!1}}async function ue(e,t,r=se){const a=r.now()+ae;for(;;){if(await r.tryAcquire())try{try{return await e()}catch{}return await t()}finally{await r.release()}try{return await e()}catch{}if(await r.isStale())await r.release();else{if(r.now()>a)return await t();await r.wait(ie)}}}E(ce,{runExclusiveAuth:()=>ue});var me,_e,fe,he=x({"src/auth/lock.ts"(){ee=r.join(t.homedir(),".atoms"),te=r.join(ee,".auth.lock"),re=7e4,ae=12e4,ie=300,ne=e=>new Promise(t=>setTimeout(t,e)),se={now:Date.now,wait:ne,tryAcquire:le,release:de,isStale:pe}}}),ge={};function ye(e){return e.trim().replace(/\/+$/,"")}E(ge,{ATOMS_APP_URL:()=>fe,ATOMS_SUPABASE_ANON_KEY:()=>_e,ATOMS_SUPABASE_URL:()=>me,resolveUrl:()=>ye});var we=x({"src/config.ts"(){me=ye(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),_e=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",fe=process.env.ATOMS_APP_URL??"https://atoms.tech"}}),ve={};async function be(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=ke(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await Q();if(t&&t.expires_at>Date.now()+6e4){const e=ke(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}return null}async function je(){const e=await be();if(e)return e;const t=await Q();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' to connect your ATOMS account.");return ue(async()=>{const e=await be();if(e)return e;throw new Error("no fresh token yet")},()=>async function(e){process.stderr.write("[atoms-mcp] Refreshing access token...\n");const t=a.createClient(me,_e);let r=await t.auth.refreshSession({refresh_token:e.refresh_token});if(r.error||!r.data.session){const a=await Q();if(a&&a.expires_at>Date.now()+6e4){const e=ke(a.access_token);return{access_token:a.access_token,refresh_token:a.refresh_token,user_id:e.sub,email:e.email??a.user_email??""}}a&&a.refresh_token&&a.refresh_token!==e.refresh_token&&(process.stderr.write("[atoms-mcp] Refresh token was rotated by another session; retrying with the latest...\n"),r=await t.auth.refreshSession({refresh_token:a.refresh_token}))}if(r.error||!r.data.session){const e=r.error?[r.error.status,r.error.message].filter(Boolean).join(" ").trim():"no session returned";throw new Error(`Token refresh failed (${e}). Your saved ATOMS session is no longer valid — re-run 'npx @atoms-tech/atoms-mcp login'.`)}const i=r.data.session;return await G({access_token:i.access_token,refresh_token:i.refresh_token,expires_at:Date.now()+1e3*(i.expires_in??3600),user_email:i.user?.email}),{access_token:i.access_token,refresh_token:i.refresh_token,user_id:i.user?.id??"",email:i.user?.email??""}}(t))}function ke(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,"="),a=JSON.parse(Buffer.from(r,"base64").toString("utf-8"));if(!a.sub)throw new Error("JWT missing 'sub' claim");return a}E(ve,{getValidToken:()=>je,readValidToken:()=>be});var Se,Ae,xe,Ee,Ie,Re,Oe,$e=x({"src/auth/refresh.ts"(){oe(),he(),we()}}),qe=x({"src/core/errors.ts"(){}});function ze(e,t){const r=xe.indexOf(String(e??"")),a=xe.indexOf(String(t??""));return r<0||a<0?Se:Ee[r][a]}function Me(e){return"Moderate"===e||"High"===e||"Very High"===e}var Te,He,De,Ce=x({"src/core/securityScheme.ts"(){Se="-",Ae=["Very Low","Low","Moderate","High","Very High"],xe=["1","2","3","4","5"],Ee=[["Very Low","Very Low","Very Low","Low","Low"],["Very Low","Very Low","Low","Low","Moderate"],["Very Low","Low","Low","Moderate","Moderate"],["Low","Low","Moderate","Moderate","High"],["Low","Moderate","High","High","Very High"]],Ie={"Very Low":"meets the acceptance criteria",Low:"meets the acceptance criteria",Moderate:"acceptable only with a recorded justification",High:"does not meet the acceptance criteria","Very High":"does not meet the acceptance criteria"},Re=[{id:"authentication",label:"Authentication",abbr:"Auth"},{id:"authorization",label:"Authorization",abbr:"AuthZ"},{id:"cryptography",label:"Cryptography",abbr:"Crypto"},{id:"code_data_execution_integrity",label:"Code, data and execution integrity",abbr:"Integrity"},{id:"confidentiality",label:"Confidentiality",abbr:"Confid"},{id:"event_detection_logging",label:"Event detection and logging",abbr:"Detect"},{id:"resiliency_recovery",label:"Resiliency and recovery",abbr:"Resil"},{id:"firmware_software_updates",label:"Firmware and software updates",abbr:"Update"}],Oe={id:"The row id. The prefix comes from the scheme: SEC for the analysis, CYB for its rows.",asset:"The thing worth protecting, the seed of a row.",threat_event:"What the adversary does, one per row.",vulnerability:"The weakness the threat event exploits.",impact:"What the attacker achieves on the device.",harm:"The consequence for the patient, the data or the delivery of care.",s:"Severity and pervasiveness: how bad the consequence is and how widely it reaches, 1 to 5. The anchor for each level is in the glossary.",e:"The ease with which the vulnerability can be exploited, assessed across the device lifecycle. It is not a probability. Score the worst case, or write the reason for a lower score in the E rationale (FDA premarket guidance 2026, V.A.2).",risk:"Derived from S and E through the one fixed matrix of the scheme. Acceptability is judged on the residual risk, not here.",security_control:"One control per risk, stated as a requirement the device shall meet.",mit:"The requirements that carry this control, each with one of the eight FDA control categories on the link.",haz:"The ISO 14971 risk rows this security risk affects. Nothing is derived from the link onto the risk row ratings.",safety_impact:"Whether this security risk creates or worsens a pathway to patient harm. Yes means it is transferred into the ISO 14971 file and linked to the risk rows it affects. No means the consequence stays inside security. The answer needs a written reason either way.",safety_impact_justification:"Why this does or does not reach a patient. Required whichever way the answer goes.",assumptions:"One assumption per line. Non normative: it saves live with no change record.",s_rationale:"The evidence for the S rating.",e_rationale:"The evidence for the E rating. Say here why a score lower than the worst case is justified.",residual_s:"Severity and pervasiveness after the control is in place.",residual_e:"Exploitability after the control is in place.",residual_risk:"The same fixed matrix applied to Residual S and Residual E. Acceptability is judged here: Very Low and Low meet the acceptance criteria, Moderate is acceptable only with a recorded justification, High and Very High do not meet them.",justification:"Why this control and why the residual is accepted. Required when the residual is Moderate or worse, and on any row at S5 or Residual S5 whatever the band.",verified:"The test cases that verify the linked control requirements. A row with links and no test case counts as a control not verified.",chgstatus:"The approval state of the row under change control, with its revision.",authentication:"Proving the identity of a user, an endpoint, or a piece of information (FDA Appendix 1).",authorization:"Deciding what an authenticated identity may do, evaluated on every action.",cryptography:"Protecting data in transit and at rest with validated algorithms and key handling.",code_data_execution_integrity:"Proving that code, data and the running artefact are what the manufacturer released.",confidentiality:"Keeping data readable only by those entitled to read it.",event_detection_logging:"Recording security relevant events so they can be detected and reconstructed afterwards.",resiliency_recovery:"Keeping the device usable under attack or failure, and recovering it afterwards.",firmware_software_updates:"Delivering and verifying updates to the device across its lifecycle.",threat_model_method:"The methodology used to enumerate threats (for example STRIDE), and why it was chosen for this system boundary.",environment_assumptions:"What is assumed about the environment the device operates in, one per line (for example: assume the hospital network is hostile).",attack_surfaces:"The interfaces and entry points considered, one per line.",lifecycle_sources:"The device lifecycle stages considered as a source of threats (FDA premarket guidance V.A.1): supply chain, manufacturing, deployment, interoperation, maintenance and update, decommission.",related_documents:"Where the software bill of materials, the security testing report and the architecture views live.",overall_residual_risk:"The residual risk conclusion of the security risk assessment (AAMI TIR57), one of the five bands, judged by a person against every row's residual risk."}}});function Pe(e){return`${e.join(", ")} cannot be written through atoms_fill_row: the acceptance is recorded by a person in the app; it is never written over MCP.`}function Ue(e){return`${e}. The signed-in person records that the analysis is accepted, with the date and the open gaps by kind copied at that moment. It is not computed from the rows. Row approval is a separate act. ${De}`}function Ne(e){const t=e??{},r="accepted"===t.acceptance_state?"accepted":"draft",a=Array.isArray(t.open_gaps_at_acceptance)?t.open_gaps_at_acceptance.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.kind):[];return{acceptance_state:r,accepted_by:"string"==typeof t.accepted_by?t.accepted_by:null,accepted_at:"string"==typeof t.accepted_at?t.accepted_at:null,acceptance_note:"string"==typeof t.acceptance_note?t.acceptance_note:"",open_gaps_at_acceptance:a}}function Le(e){return"accepted"===e.acceptance_state&&(e.prev_accepted_by=e.accepted_by??null,e.prev_accepted_at=e.accepted_at??null,e.acceptance_state="draft",e.accepted_by=null,e.accepted_at=null,!0)}function Fe(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function We(e){const t=e?.analysis_props,r={...t&&"object"==typeof t?t:{}};return{revoked:Le(r),parentProps:r}}var Ve,Be,Je,Qe,Ge,Ye,Ke,Ze,Xe,et,tt,rt,at,it,nt,st,ot,ct,lt,dt,pt,ut,mt,_t,ft,ht,gt,yt,wt,vt,bt,jt,kt,St,At,xt,Et,It,Rt,Ot,$t,qt,zt,Mt,Tt,Ht,Dt,Ct,Pt,Ut=x({"src/core/acceptance.ts"(){Te=["acceptance_state","accepted_by","accepted_at","acceptance_note","open_gaps_at_acceptance"],He=["prev_accepted_by","prev_accepted_at","accepted_snapshot_id","accepted_snapshot_name"],De="This is a record of a decision, not an electronic signature. The signature of record is applied in the manufacturer's own quality system."}});function Nt(e,t,r){return"hara"===e?"tir57"===t?"security_tir57":"iso14971"===t?"hazard_iso14971":"iso26262"===t?"hara_iso26262":"medical"===r?"hazard_iso14971":"hara_iso26262":"process"===t?"fmea_process":"software"===t?"fmea_software":"use"===t?"fmea_use":"design"===t?"dfmea_rpn":"medical"===r?"fmea_process":"dfmea_rpn"}function Lt(e){return Be[e]}function Ft(e){return Je.some(t=>t.id===e)||function(e){return Re.some(t=>t.id===e)}(e)}function Wt(e){const t=Array.isArray(e)?e.filter(e=>"string"==typeof e):[],r=t.length>=2?t[1].trim():"";return r?{level:r,source:"taxonomy"}:{level:Ge,source:"fallback"}}function Vt(e){const t=(e??"").trim().toLowerCase();return"sub-system"===t?"subsystem":t}function Bt(e,t){const r=Wt(e),a=Wt(t);return Vt(r.level)===Vt(a.level)?null:`Warning: this changes the system level (the ladder's second rung, L1) from "${r.level}" to "${a.level}". HARA and risk-analysis gap classification (the no_parent / bridge gap) is judged against the system level, so gap results for this project's hazard analyses may change. Re-check atoms_get_gaps on affected analyses.`}function Jt(e){return"hazard_iso14971"===e?dt:"security_tir57"===e?_t:[]}function Qt(e){return"security_tir57"===e?Ae:pt}function Gt(e){return String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e)}function Yt(e){const t=e??{};return{intended_use:String(t.intended_use??"").trim(),foreseeable_misuse:Gt(t.foreseeable_misuse),safety_characteristics:Gt(t.safety_characteristics)}}function Kt(e,t=pt){const r=e??{},a=String(r.overall_residual_risk??"").trim(),i=String(r.software_safety_class??"").trim();return{residual_risk:t.includes(a)?a:"",residual_rationale:String(r.overall_residual_rationale??"").trim(),safety_class:ut.includes(i)?i:"",safety_rationale:String(r.software_safety_rationale??"").trim()}}function Zt(e){return""!==Yt(e).intended_use}function Xt(e,t){const r=Jt(e);if(0===r.length)return`An analysis parent of scheme ${e} carries no fillable field: ${t.join(", ")} cannot be written on it. Only the ISO 14971 risk analysis carries a scope and an overall residual risk.`;const a=r.filter(e=>!e.endsWith("_rationale"));return`Unknown field(s) for the analysis parent: ${t.join(", ")}. Allowed: ${a.join(", ")} (+ _rationale for the last two)`}function er(e,t,r){return`Invalid ${e} value ${JSON.stringify(t)}. Allowed: ${r.join(", ")}`}function tr(e){return"risk_analysis"===e||"hazard_analysis"===e?["iso14971"]:"security_risk"===e?["tir57"]:Ve[wt[e]]}function rr(e){return Object.entries(Rt[e]).map(([e,t])=>({key:e,label:t}))}function ar(e){return Object.entries(function(e){return"hara_iso26262"===e?St:"dfmea_rpn"===e?Et:"hazard_iso14971"===e?xt:"security_tir57"===e?Oe:It}(e)).map(([e,t])=>({key:e,text:t}))}function ir(e){return"hazard_iso14971"===e?it:"security_tir57"===e?Ie:null}function nr(e,t){const r=ir(e);return r?r[t]??null:null}function sr(e){return(e??"").trim().toLowerCase()}function or(e,t){const r=sr(e);if(!r)return null;for(const e of t)if(sr(e)===r)return e;return null}function cr(e){const t=e?.severity||"",r=e?.exposure||"",a=e?.controllability||"";return t&&r&&a?"S0"===t||"E0"===r||"C0"===a?"QM":Xe[`${t}-${r}-${a}`]||Ke:Ke}function lr(e){const t=parseInt(e?.severity||"",10),r=parseInt(e?.occurrence||"",10),a=parseInt(e?.detection||"",10);return Number.isNaN(t)||Number.isNaN(r)||Number.isNaN(a)?Ke:String(t*r*a)}function dr(e,t,r){const a=String(e??""),i=String(t??""),n=String(r??"");if(tt.indexOf(a)<0||tt.indexOf(i)<0||tt.indexOf(n)<0)return Ke;const s=rt[`${i}-${n}`];return s&&at[`${s}-${a}`]||Ke}function pr(e){return dr(e?.severity,e?.p1,e?.p2)}function ur(e){return dr(e?.residual_s,e?.residual_p1,e?.residual_p2)}function mr(e){return ze(e?.severity,e?.exploitability)}function _r(e){return ze(e?.residual_s,e?.residual_e)}function fr(e,t){return"hara_iso26262"===e?cr(t):"hazard_iso14971"===e?pr(t):"security_tir57"===e?mr(t):"fmea_software"===e?function(e){return lr({...e??{},occurrence:nt})}(t):lr(t)}function hr(e,t,r){if(r)return!1;if("hara_iso26262"===e){const e=cr(t);return"C"===e||"D"===e}if("hazard_iso14971"===e)return"High"===pr(t);if("security_tir57"===e){const e=mr(t);return"High"===e||"Very High"===e}const a=parseInt(fr(e,t),10);return!Number.isNaN(a)&&a>=200}function gr(e,t,r){if(!e?.approved||!e.approved_at)return!1;const a=Date.parse(e.approved_at);return!Number.isNaN(a)&&[...e.source_req?[e.source_req]:[],...t].some(e=>{const t=r(e),i=t?Date.parse(t):NaN;return!Number.isNaN(i)&&i>a})}function yr(e,t){const r=function(e){return"hara_iso26262"===e?"asil":"hazard_iso14971"===e||"security_tir57"===e?"risk":"rpn"}(e);return`Field${t.length>1?"s":""} ${t.join(", ")} cannot be written: ${r} is derived from the ratings and the approval keys are recorded by atoms_approve_row. Write the ratings instead and read ${r} back as computed_level.`}function wr(e){return"fmea_software"===e?{field:"occurrence",value:nt}:null}function vr(e){const t=wr(e);return t?`Field ${t.field} is fixed at ${t.value} in a Software FMEA (IEC 62304: software failure probability is assumed 100 percent), so the RPN follows severity and detection. Omit it.`:""}function br(e){return zt[e]}function jr(e){return"security_tir57"===e?Re:function(e){return"hazard_iso14971"===e||"fmea_process"===e||"fmea_software"===e||"fmea_use"===e}(e)?Je:[]}function kr(e){return jr(e).map((e,t)=>({...e,precedence:t+1}))}function Sr(e){return"security_tir57"===e?`control_type is required for a security control link (FDA Appendix 1). Choose one of: ${Re.map(e=>`${e.id} (${e.label})`).join(", ")}.`:`control_type is required for a risk control link (ISO 14971 clause 7). Choose one of: ${Je.map(e=>`${e.id} (${e.label})`).join(", ")}.`}function Ar(e){if(null==e||""===e)return null;if("number"==typeof e)return Number.isInteger(e)?e:null;if("string"!=typeof e||!/^\s*\d+\s*$/.test(e))return null;const t=parseInt(e,10);return Number.isNaN(t)?null:t}function xr(e){const t=parseInt(e,10);return!Number.isNaN(t)&&t>=100}function Er(e){return"hara_iso26262"===e?Ht:"hazard_iso14971"===e?Dt:"security_tir57"===e?Pt:Ct}function Ir(e){return!0===e.approved&&(e.approved=!1,e.approved_at=null,e.approved_by=null,e.approved_note="",!0)}function Rr(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function Or(e,t,r=sr){const a=new Set(t.map(r).filter(e=>e.length>0));return e.filter(e=>a.has(r(e)))}function $r(e){const t=e.length>1;return`Function-flagged tag${t?"s":""} used as domain${t?"s":""}: ${e.join(", ")}. A function is not a domain tag: seed a HARA row with it instead (atoms_create_analysis source_functions, or atoms_fill_row source_function), or unflag it (atoms_update_domain with is_function=false, or Taxonomy Management).`}var qr,zr,Mr,Tr=x({"src/core/analysis.ts"(){Ce(),Ce(),Ut(),Ve={hara:["iso26262","iso14971","tir57"],dfmea:["design","process","software","use"]},Be={hara_iso26262:"ISO 26262",hazard_iso14971:"ISO 14971",dfmea_rpn:"AIAG-VDA FMEA Handbook",fmea_process:"AIAG-VDA FMEA Handbook",fmea_software:void 0,fmea_use:void 0,security_tir57:"AAMI TIR57"},Je=[{id:"inherent",label:"Inherent design",abbr:"ID"},{id:"protective",label:"Protective measure",abbr:"PM"},{id:"information",label:"Information for safety",abbr:"IFS"}],Qe="safety",Ge="L1",Ye=8,Ke="-",Ze=["prevention","detection","mitigation"],Xe={"S1-E1-C1":"QM","S1-E1-C2":"QM","S1-E1-C3":"QM","S1-E2-C1":"QM","S1-E2-C2":"QM","S1-E2-C3":"QM","S1-E3-C1":"QM","S1-E3-C2":"QM","S1-E3-C3":"A","S1-E4-C1":"QM","S1-E4-C2":"A","S1-E4-C3":"B","S2-E1-C1":"QM","S2-E1-C2":"QM","S2-E1-C3":"QM","S2-E2-C1":"QM","S2-E2-C2":"QM","S2-E2-C3":"A","S2-E3-C1":"QM","S2-E3-C2":"A","S2-E3-C3":"B","S2-E4-C1":"A","S2-E4-C2":"B","S2-E4-C3":"C","S3-E1-C1":"QM","S3-E1-C2":"QM","S3-E1-C3":"A","S3-E2-C1":"QM","S3-E2-C2":"A","S3-E2-C3":"B","S3-E3-C1":"A","S3-E3-C2":"B","S3-E3-C3":"C","S3-E4-C1":"B","S3-E4-C2":"C","S3-E4-C3":"D"},rt={"1-1":"1","1-2":"1","1-3":"1","1-4":"2","1-5":"3","2-1":"1","2-2":"1","2-3":"2","2-4":"3","2-5":"4","3-1":"1","3-2":"2","3-3":"3","3-4":"4","3-5":"5","4-1":"2","4-2":"3","4-3":"4","4-4":"5","4-5":"5","5-1":"3","5-2":"4","5-3":"5","5-4":"5","5-5":"5"},at={"1-1":"Low","1-2":"Low","1-3":"Low","1-4":"Low","1-5":"Medium","2-1":"Low","2-2":"Low","2-3":"Low","2-4":"Medium","2-5":"Medium","3-1":"Low","3-2":"Low","3-3":"Medium","3-4":"Medium","3-5":"High","4-1":"Low","4-2":"Medium","4-3":"Medium","4-4":"High","4-5":"High","5-1":"Medium","5-2":"Medium","5-3":"High","5-4":"High","5-5":"High"},it={Low:"Acceptable",Medium:"Acceptable with justification",High:"Not acceptable"},nt="10",st={hara_iso26262:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea_rpn:{severity:et=["1","2","3","4","5","6","7","8","9","10"],occurrence:et,detection:et},hazard_iso14971:{severity:tt=["1","2","3","4","5"],p1:tt,p2:tt,residual_s:tt,residual_p1:tt,residual_p2:tt},fmea_process:{severity:et,occurrence:et,detection:et},fmea_software:{severity:et,detection:et},fmea_use:{severity:et,occurrence:et,detection:et},security_tir57:{severity:[...xe],exploitability:[...xe],residual_s:[...xe],residual_e:[...xe]}},ot={hara_iso26262:["failure_mode","operating_scenario","hazard","assumptions","severity","exposure","controllability","safe_state","ftti","rationale","source_function","safety_goal","s_rationale","e_rationale","c_rationale"],dfmea_rpn:["failure_mode","cause","severity","occurrence","detection","rationale"],hazard_iso14971:["failure_mode","operating_scenario","hazard","assumptions","severity","p1","p2","rationale","source_function","safety_goal","s_rationale","p1_rationale","p2_rationale","residual_s","residual_p1","residual_p2","benefit_note"],fmea_process:["process_step","failure_mode","cause","severity","occurrence","current_controls","detection","rationale"],fmea_software:["failure_mode","cause","severity","detection","rationale"],fmea_use:["failure_mode","cause","severity","occurrence","detection","rationale"],security_tir57:["failure_mode","operating_scenario","hazard","assumptions","severity","exploitability","rationale","source_function","safety_goal","s_rationale","e_rationale","residual_s","residual_e","justification","safety_impact","safety_impact_justification"]},ct=["intended_use","foreseeable_misuse","safety_characteristics"],lt=["overall_residual_risk","overall_residual_rationale","software_safety_class","software_safety_rationale"],dt=[...ct,...lt],pt=["Low","Medium","High"],ut=["A","B","C"],mt=["threat_model_method","threat_model_rationale","environment_assumptions","attack_surfaces","related_documents","overall_residual_risk","overall_residual_rationale"],_t=[...mt,"lifecycle_sources"],ft={hara:"safety-goal",dfmea:"failure-mode"},ht={hara_iso26262:"SG",dfmea_rpn:"FM",hazard_iso14971:"RSK",fmea_process:"PF",fmea_software:"FM",fmea_use:"FM",security_tir57:"CYB"},gt={hara_iso26262:"HARA",dfmea_rpn:"DFMEA",hazard_iso14971:"RA",fmea_process:"PFMEA",fmea_software:"SFMEA",fmea_use:"UFMEA",security_tir57:"SEC"},yt=["HA"],Array.from(new Set([...Object.values(gt),...Object.values(ht),...yt])).sort(),wt={hara:"hara",dfmea:"dfmea",risk_analysis:"hara",fmea:"dfmea",hazard_analysis:"hara",security_risk:"hara"},vt=["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"],bt={hara:"iso26262",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"design",fmea:"process",security_risk:"tir57"},jt={hara:"iso14971",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"process",fmea:"process",security_risk:"tir57"},kt={fmea_failure_mode:"Failure mode: the way the design, the process step or the software fails to do what it should, for example a valve that sticks open or a step skipped.",fmea_effect:"Effect: what the failure mode does to the customer, the patient or the next step of the process. Severity rates the effect.",fmea_cause:"Cause: the mechanism or condition behind the failure mode, what has to be true for it to happen. Occurrence rates the cause.",fmea_action:"Action: the requirement that answers the failure mode. The link records how it answers it, and a row at RPN 100 or above with no action is a gap."},St={...kt,s:"Severity: how badly people could be hurt if the hazardous event happens. S0 no injuries, S1 light, S2 severe but survivable, S3 life-threatening or fatal (ISO 26262-3).",e:"Exposure: how often the operational scenario occurs. E0 incredible, E1 very low, E2 low, E3 medium, E4 high probability (ISO 26262-3).",c:"Controllability: how likely the driver or others can avoid the harm. C0 controllable in general, C1 simply, C2 normally, C3 difficult or uncontrollable (ISO 26262-3).",asil:"Automotive Safety Integrity Level: computed from S, E and C per ISO 26262-3 Table 4. QM means no safety requirement is needed; D is the most demanding.",safe_state:"The condition the system moves to when the function fails, for example handing braking back to the driver.",ftti:"Fault tolerant time interval: the longest time a fault may stay undetected before the hazardous event can occur.",safety_goal:"The top-level safety requirement derived from a hazardous event. One goal per HARA row; it is met by safety requirements that mitigate it.",safety_req:"A requirement of type Safety that mitigates a safety goal. At L1 it is a functional or technical safety requirement and traces to a system requirement.",verified_by:"The test case that proves this safety goal on its operating design domain (ODD).",hazardous_event:"What happens to the vehicle and the people when the failure occurs in this scenario. One per row.",hazard:"The potential harm, for example unintended braking.",assumptions:"The conditions you assume for the rating, one per line, for example light traffic or a speed limit.",fn:"The system function this row analyses, from the project's function tags.",failure_mode:"How the function fails: no function, loss, partial, degradation or misinterpretation.",scenario:"The driving situation in which the failure is analysed. One per row.",dfmea_s:"Severity: how serious the effect of the failure is for the customer, 1 (no effect) to 10 (safety or regulatory failure without warning).",o:"Occurrence: how likely the cause is, 1 (remote) to 10 (very high).",d:"Detection: how likely current controls detect the cause before it reaches the customer, 1 (certain) to 10 (impossible).",rpn:"Risk priority number: S times O times D. Rows at 100 or above are gaps.",accept_analysis:Ue("The confirmation review of the HARA (ISO 26262)")},At={s:"Severity: a measure of the possible consequences of a hazard. 1 Negligible, 2 Minor, 3 Serious, 4 Critical, 5 Catastrophic (ISO 14971).",p1:"P1: the probability of a hazardous situation occurring. 1 Improbable, 2 Remote, 3 Occasional, 4 Probable, 5 Frequent (the example scale of ISO 14971:2007 Annex D, kept in ISO/TR 24971).",p2:"P2: the probability that the hazardous situation leads to harm, given that it occurs. 1 to 5 on the same scale (ISO 14971:2007 Annex D, ISO/TR 24971).",p0:"P0: the overall probability of harm, looked up from P1 and P2 on the 5 by 5 probability table.",risk:"Risk: the combination of the probability of harm and its severity, looked up from P0 and S. Low is acceptable, Medium is acceptable with a justification, High is not acceptable (ISO 14971).",risk_analysis:"Risk analysis: the systematic use of available information to identify hazards and to estimate the risk for each hazardous situation (ISO 14971:2019 definition 3.19 and clause 5). It is the name the standard gives this document.",hazard:"Hazard: a potential source of harm, for example an uncontrolled flow of the drug.",hazardous_situation:"Hazardous situation: the circumstance in which people are exposed to the hazard.",sequence:"Sequence of events: what has to happen for the hazard to become a hazardous situation. One sequence per row.",harm:"Harm: injury or damage to the health of people, or damage to property or the environment.",assumptions:"The conditions you assume for the estimate, one per line, for example the care setting or the patient group.",fn:"The device function this row analyses, from the project's function tags.",risk_control:"Risk control: the measure that reduces the risk. Applied in order: inherent safety by design, then protective measures, then information for safety (ISO 14971 clause 7).",control_req:"A requirement of type Risk control that implements a risk control measure. It carries the control type and traces to a system requirement.",verified_by:"Verification of effectiveness: the test that shows the risk control works, not only that it was implemented (ISO 14971 clause 7.2).",residual:"Residual risk: the risk remaining after the risk control measures are applied, estimated with the same two tables.",benefit:"Benefit-risk analysis: the argument that the medical benefit outweighs a residual risk that is still not acceptable (ISO 14971 clause 7.4).",dfmea_s:"Severity: how serious the effect of the failure is, 1 (no effect) to 10 (harm without warning).",o:"Occurrence: how likely the cause is, 1 (remote) to 10 (very high).",o_sw:"IEC 62304: software failure probability is assumed 100 percent; rate by severity.",d:"Detection: how likely current controls detect the cause before it reaches the patient, 1 (certain) to 10 (impossible).",rpn:"Risk priority number: S times O times D. Rows at 100 or above are gaps.",process_step:"The step of the clinical or manufacturing process this row analyses.",controls:"Current controls: what already stands between this cause and the effect.",intended_use:"Intended use: what the device is for, for which patient, by which user and in which environment. ISO 14971:2019 5.2 asks for it before any hazard is identified.",foreseeable_misuse:"Reasonably foreseeable misuse: use in a way the manufacturer did not intend but can expect, one case per line (ISO 14971:2019 5.2).",safety_characteristics:"Characteristics related to safety: the qualitative and quantitative characteristics that could affect safety, one per line (ISO 14971:2019 5.3).",overall_residual_risk:"Overall residual risk: the risk that remains from the device as a whole, once every individual risk is controlled. Judged by a person against the criteria in the risk management plan (ISO 14971:2019 clause 8).",software_safety_class:"Software safety class: A no injury or damage to health is possible, B non-serious injury is possible, C death or serious injury is possible (IEC 62304 4.3)."},xt={...kt,...At,accept_analysis:Ue("The ISO 14971 clause 8 overall residual risk conclusion")},Et={...kt,dfmea_s:St.dfmea_s,o:St.o,d:St.d,rpn:St.rpn,accept_analysis:Ue("The AIAG-VDA FMEA sign-off")},It={...kt,dfmea_s:At.dfmea_s,o:At.o,o_sw:At.o_sw,d:At.d,rpn:At.rpn,process_step:At.process_step,controls:At.controls,fn:At.fn,risk_control:At.risk_control,control_req:At.control_req,verified_by:At.verified_by,accept_analysis:Ue("The FMEA sign-off")},Rt={hara_iso26262:{source_function:"Function",failure_mode:"Failure Mode",operating_scenario:"Operational Scenario",effect:"Hazardous Event",hazard:"Hazard",assumptions:"Assumptions",s_rationale:"S evidence",e_rationale:"E evidence",c_rationale:"C evidence",safe_state:"Safe state",ftti:"FTTI",severity:"S",exposure:"E",controllability:"C",safety_goal:"Safety goal",asil:"ASIL"},dfmea_rpn:{source_req:"Source",failure_mode:"Failure Mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",detection:"D",rpn:"RPN"},hazard_iso14971:{source_function:"Function",failure_mode:"Hazard",operating_scenario:"Sequence of events",effect:"Hazardous situation",hazard:"Harm",assumptions:"Assumptions",s_rationale:"S rationale",p1_rationale:"P1 rationale",p2_rationale:"P2 rationale",residual_s:"Residual S",residual_p1:"Residual P1",residual_p2:"Residual P2",residual_level:"Residual risk",benefit_note:"Benefit-risk note",severity:"S",p1:"P1",p2:"P2",safety_goal:"Risk control statement",risk:"Risk"},fmea_process:{source_req:"Source",process_step:"Process step",failure_mode:"Failure mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",current_controls:"Current controls",detection:"D",rpn:"RPN"},fmea_software:{source_req:"Source",failure_mode:"Failure Mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",detection:"D",rpn:"RPN"},fmea_use:{source_req:"Source",failure_mode:"Failure Mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",detection:"D",rpn:"RPN"},security_tir57:{source_function:"Asset",failure_mode:"Threat event",operating_scenario:"Vulnerability",effect:"Impact",hazard:"Harm",assumptions:"Assumptions",s_rationale:"S rationale",e_rationale:"E rationale",residual_s:"Residual S",residual_e:"Residual E",residual_level:"Residual risk",severity:"S",exploitability:"E",risk:"Risk",safety_goal:"Security control statement",safety_impact:"Safety impact",safety_impact_justification:"Safety impact justification",justification:"Justification"}},Ot=["asil","rpn","risk","p0"],$t=["approved","approved_at","approved_by","approved_note","field_source","link_roles","mitigation_types"],qt=[...Ot,...$t],zt={hara_iso26262:{parent:"HARA",row:"Safety goal",row_statement:"Safety goal",mitigating_requirement:"Safety requirement",lane:"Safety lane",level:"ASIL"},dfmea_rpn:{parent:"DFMEA",row:"Failure mode",row_statement:"Action",mitigating_requirement:"Requirement",lane:"Safety lane",level:"RPN"},hazard_iso14971:{parent:"Risk analysis",row:"Risk",row_statement:"Risk control statement",mitigating_requirement:"Risk control",lane:"Risk lane",level:"Risk"},fmea_process:{parent:"PFMEA",row:"Process failure",row_statement:"Action",mitigating_requirement:"Risk control",lane:"Risk lane",level:"RPN"},fmea_software:{parent:"Software FMEA",row:"Failure mode",row_statement:"Action",mitigating_requirement:"Risk control",lane:"Risk lane",level:"RPN"},fmea_use:{parent:"Use FMEA",row:"Failure mode",row_statement:"Action",mitigating_requirement:"Risk control",lane:"Risk lane",level:"RPN"},security_tir57:{parent:"Security risk analysis",row:"Security risk",row_statement:"Security control statement",mitigating_requirement:"Security control",lane:"Security lane",level:"Risk"}},Mt=(e,t,r)=>1===e?t:r,Ht=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft safety requirement",label:e=>`${e} ${Mt(e,"safety goal","safety goals")} unmitigated`,matches:e=>e.level!==Ke&&"QM"!==e.level&&!e.linked},{kind:"no_test",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Mt(e,"safety goal","safety goals")} without a test on its ODD`,matches:e=>e.level!==Ke&&"QM"!==e.level&&e.linked&&!e.verified},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} ${Mt(e,"safety requirement","safety requirements")} without a system parent`},{kind:"catalog_draft",scope:"analysis",fix:"open_analysis",fixLabel:"Review the scenario catalogs",label:()=>"Scenario catalog not accepted",matchesAnalysis:e=>e.catalogsDraft},Tt={kind:"not_accepted",scope:"analysis",fix:"open_analysis",fixLabel:"Accept analysis",label:()=>"Analysis not accepted",matchesAnalysis:e=>e.hasRows&&!e.accepted}],Dt=[{kind:"no_control",scope:"row",fix:"link_requirement",fixLabel:"Draft risk control requirement",label:e=>`${e} ${Mt(e,"risk","risks")} above Low with no control`,matches:e=>e.level!==Ke&&"Low"!==e.level&&!e.linked},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Mt(e,"control","controls")} not verified for effectiveness`,matches:e=>e.level!==Ke&&"Low"!==e.level&&e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual ${Mt(e,"risk","risks")} not assessed`,matches:e=>e.level!==Ke&&"Low"!==e.level&&e.linked&&e.residualLevel===Ke},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} risk ${Mt(e,"control","controls")} without a system parent`},{kind:"no_scope",scope:"analysis",fix:"open_analysis",fixLabel:"Open the scope",label:()=>"Scope not stated",matchesAnalysis:e=>e.hasRows&&!e.scopeStated},{kind:"no_overall",scope:"analysis",fix:"open_analysis",fixLabel:"Judge the overall residual risk",label:()=>"Overall residual risk not judged",matchesAnalysis:e=>e.hasRows&&e.everyRowSettled&&!e.overallJudged},Tt],Ct=[{kind:"rpn",scope:"row",fix:"link_requirement",fixLabel:"Link a requirement",label:e=>`${e} at RPN 100 or above with no mitigating requirement`,matches:e=>xr(e.level)&&!e.linked},{kind:"severity",scope:"row",fix:"link_requirement",fixLabel:"Link a requirement",label:e=>`${e} at severity 9 or above below RPN 100 with no mitigating requirement`,matches:e=>!xr(e.level)&&null!==e.severity&&e.severity>=9&&!e.linked},Tt],Pt=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft security control",label:e=>`${e} security ${Mt(e,"risk","risks")} above Low with no control`,matches:e=>Me(e.level)&&!e.linked},{kind:"unassessed",scope:"row",fix:"open_row",fixLabel:"Rate S and E",label:e=>`${e} not assessed`,matches:e=>e.level===Ke},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Mt(e,"control","controls")} not verified`,matches:e=>e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual not assessed`,matches:e=>e.linked&&e.residualLevel===Ke},{kind:"no_justification",scope:"row",fix:"open_row",fixLabel:"Write the justification",label:e=>`${e} residual without justification`,matches:e=>{const t=String(e.props?.severity??""),r=String(e.props?.residual_s??""),a="5"===t||"5"===r;return(Me(e.residualLevel)||a)&&!String(e.props?.justification??"").trim()}},{kind:"safety_no_hazard",scope:"row",fix:"open_row",fixLabel:"Link a safety hazard",label:e=>`${e} safety impact Yes with no safety hazard`,matches:e=>"Yes"===e.props?.safety_impact&&!e.affectsLinked},{kind:"safety_no_reason",scope:"row",fix:"open_row",fixLabel:"Write the reason",label:e=>`${e} safety impact without a reason`,matches:e=>("Yes"===e.props?.safety_impact||"No"===e.props?.safety_impact)&&!String(e.props?.safety_impact_justification??"").trim()},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} security ${Mt(e,"control","controls")} without a system parent`},{kind:"no_scope",scope:"analysis",fix:"open_analysis",fixLabel:"Open the threat model",label:()=>"Threat model not stated",matchesAnalysis:e=>e.hasRows&&!e.scopeStated}]}});function Hr(e){if(e instanceof zr)return e.names;if(e&&"object"==typeof e&&e.code===qr){const t=e.names;if(Array.isArray(t))return t.filter(e=>"string"==typeof e)}return null}function Dr(e,t){return t?`Domain "${e}" already exists as a function, and a function is not a domain tag. To tag items with it, unflag it first: atoms_update_domain with name "${e}" and is_function=false.`:`Domain "${e}" already exists in this project.`}function Cr(e){return`Domain "${e}" is already flagged as a function. Nothing changed.`}function Pr(e){return`"${e}" is already a domain, not a function. Nothing changed.`}function Ur(e,t,r){const a=`${t} item${1!==t?"s":""}`;return r?`Dry run: flagging "${e}" as a function would move it out of the Domains group. The ${a} that carry it would keep the tag, and no new item could take it as a domain until it is unflagged (is_function=false). Call again with dry_run=false to apply.`:`Domain "${e}" is now a function. It moved out of the Domains group: the ${a} that carry it keep the tag, and no new item can take it as a domain until you unflag it (is_function=false). Use it through atoms_create_analysis source_functions or atoms_fill_row source_function.`}function Nr(e,t,r){const a=t>0?` ${t} analysis row${1!==t?"s":""} still name${1===t?"s":""} it as their function: they keep the name as text, but it no longer lists under Functions in the sidebar. Flag it again (is_function=true) to restore that.`:"";return r?`Dry run: unflagging "${e}" would turn it back into a domain, so items can be tagged with domains=["${e}"] again.${a} Call again with dry_run=false to apply.`:`"${e}" is a domain again: items can be tagged with domains=["${e}"].${a}`}var Lr,Fr,Wr,Vr,Br,Jr,Qr,Gr,Yr=x({"src/core/domains.ts"(){Tr(),qr="domain_not_function",zr=class extends Error{code=qr;names;unregistered;constructor(e,t=[]){super(`${qr}: ${e.join(", ")}`),this.name="DomainNotFunctionError",this.names=[...e],this.unregistered=[...t]}},Mr="domain_rename_onto_function"}}),Kr={};function Zr(e,t=Fr){if("string"!=typeof e)return"";const r=e.replace(Br,"").replace(Jr,"");return r.length<=t?r:r.slice(0,t)+"..."}function Xr(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function ea(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function ta(e,t,r){return{total_count:e,limit:t,offset:r,has_more:r+t<e}}function ra(e,t){return{status:"error",message:e,next_steps:t}}function aa(e,t){return ra(`${e} '${Zr(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function ia(e){return"account"===e?ra("Account suspended.",["Your ATOMS account is suspended, so ATOMS tools are unavailable","Contact ATOMS support or your organization admin to restore access"]):ra("Organization suspended.",["This project's organization is suspended, so its data is unavailable","Contact your organization admin or ATOMS support to have it reactivated","Projects in your other organizations are unaffected"])}function na(e){const t=/\b(account|organization) suspended\b/i.exec(e);return t?t[1].toLowerCase():null}function sa(e){return ra(`${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 oa(e,t=Wr){return ra(`Validation error: ${Zr(e,t)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function ca(){return ra("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 la(){return ra("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 da(e){return ra("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 pa(e){return ra("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 ua(e){return ra(`Parse error: ${Zr(e,Wr)}`,["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 ma(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function _a(){return ra("Stale write rejected: this item changed after it was read.",["Call atoms_get_item again and use the returned metadata.updated_at value","Review the current item before retrying so you do not overwrite newer work","Retry atoms_update_item or atoms_link_items with the fresh expected timestamp"])}function fa(){return ra("Save paused because this item is already being written.",["Wait a few seconds, read the item again, and retry once","Do not repeatedly retry the same stale payload"])}function ha(){return ra("Item saves are temporarily paused by an ATOMS operator.",["Keep your local draft and wait for the operator to re-enable saves","Do not repeatedly retry while the safety brake is active"])}function ga(){return ra("Item save rejected because this item is in Trash.",["Restore the item before changing it","Do not retry the same save while the item remains in Trash"])}function ya(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e),r=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";if(/not authenticated/i.test(t))return ca();const a=function(e){const t=Hr(e);if(null===t)return null;const r=e.unregistered;return function(e,t=[]){const r=e.map(e=>`"${e}"`).join(", "),a=1===e.length,i=e=>e.trim().toLowerCase(),n=e=>`atoms_update_domain (name: "${i(e)}", is_function: true)`,s=e.filter(e=>null!==or(e,t)),o=e.filter(e=>null===or(e,t)),c=e=>1===e.length?"it":"them",l=o.map(n).join(" and "),d=`${s.map(e=>`atoms_create_domain (name: "${i(e)}")`).join(" and ")}, then flag ${c(s)} with ${s.map(n).join(" and ")}`,p=[],u=[];o.length>0&&(p.push(`Flag ${c(o)} first with ${l}, then use ${c(o)}.`),u.push(`Flag ${1===o.length?"the domain":"the domains"} explicitly: ${l}`)),s.length>0&&(p.push(`Register ${c(s)} first with ${d}, then use ${c(s)}.`),u.push(`Register ${1===s.length?"the tag":"the tags"} (items carry ${c(s)} but the taxonomy does not list ${c(s)}) and flag ${c(s)}: ${d}`));const m={code:qr,domains:[...e]};return s.length>0&&(m.unregistered=[...s]),{status:"error",message:`${r} ${a?"is a domain":"are domains"}, not ${a?"a function":"functions"}, so ${a?"it":"they"} cannot be used as ${a?"a function":"functions"} yet. ${p.join(" ")} Flagging moves a tag out of the Domains group: items that already carry it keep the tag, and new items cannot take it as a domain until you unflag it (is_function: false).`,next_steps:[...u,"Or choose a function name that is not already a domain"],details:m}}(t,Array.isArray(r)?r.filter(e=>"string"==typeof e):[])}(e);if(null!==a)return a;if(function(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const r=e;t="string"==typeof r.message?r.message:"string"==typeof r.code?r.code:String(e)}else null!=e&&(t=String(e));return/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst301/i.test(t)}(e))return la();if(/rate.?limit|too many requests|429/i.test(t))return pa();if(ma(t))return _a();if(/soft_deleted_item_write/i.test(t))return ga();if(/save_temporarily_unavailable/i.test(t))return ha();if("55P03"===r||"57014"===r||/item_save_busy|statement timeout|request timeout|upstream request timeout/i.test(t))return fa();const i=na(t);return i?ia(i):"42501"===r&&/org_project_field_admin_required/i.test(t)?sa("Org admin"):"42501"===r&&/project_field/i.test(t)?sa("Project admin or owner"):"P0002"===r&&/project_field/i.test(t)?ra("Project field not found.",["Refresh the field list and retry with an existing field name"]):["22023","23505","23514"].includes(r)&&/project_field/i.test(t)?oa(t.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?ua(t):va(t)}function wa(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??""),r=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return["40001","PT409","55P03","57014"].includes(r)||/stale_item_write|soft_deleted_item_write|save_temporarily_unavailable|item_save_busy|statement timeout|request timeout|upstream request timeout|fetch failed|network error|connection (?:closed|reset|refused)/i.test(t)}function va(e){return/row.level security|permission denied for/i.test(e)?ra("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"]):ra(`Database error: ${Zr(e,Wr)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function ba(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"&lt;/user_content&gt;")}</user_content>`}function ja(e){return"string"!=typeof e?e:e.replace(/<\s*\/?\s*user_content\s*>/gi,"")}function ka(e){return Qr.has(e)}function Sa(e,t,r=!1){return"string"==typeof e?r||null!=t&&Qr.has(t)?ba(e):e:Array.isArray(e)?e.map(e=>Sa(e,t,r)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Sa(t,e,r||Gr.has(e))])):e}function Aa(e){if(JSON.stringify(e,null,2).length>Lr&&"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(Sa(r),null,2)}],structuredContent:r}}return{content:[{type:"text",text:JSON.stringify(Sa(e),null,2)}],structuredContent:e}}function xa(e){return{content:[{type:"text",text:JSON.stringify(Sa(e),null,2)}],structuredContent:e,isError:!0}}E(Kr,{CHARACTER_LIMIT:()=>Lr,USER_CONTENT_KEYS:()=>Qr,VALIDATION_MESSAGE_LONG:()=>Vr,accessDeniedError:()=>sa,authError:()=>ca,classifyError:()=>ya,dbError:()=>va,errorResponse:()=>ra,formatErrorResult:()=>xa,formatToolResult:()=>Aa,isAutoWrappedKey:()=>ka,isItemSaveStopError:()=>wa,isStaleWriteErrorMessage:()=>ma,jwtExpiredError:()=>la,notFoundError:()=>aa,paginationMeta:()=>ta,parseError:()=>ua,rateLimitError:()=>pa,sanitizeForEcho:()=>Zr,sanitizeTagOrLevel:()=>Xr,saveBusyError:()=>fa,saveUnavailableError:()=>ha,scopeError:()=>da,softDeletedItemError:()=>ga,staleWriteError:()=>_a,stripUserContentMarkers:()=>ja,success:()=>ea,suspendedError:()=>ia,suspensionKind:()=>na,validationError:()=>oa,wrapMcpUserContentFields:()=>Sa,wrapUserContent:()=>ba});var Ea,Ia,Ra,Oa=x({"src/tools/_base.ts"(){qe(),Yr(),Lr=25e3,Fr=50,Wr=200,Vr=600,Br=new RegExp("[\\u0000-\\u001F\\u007F]","g"),Jr=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g"),Qr=new Set(["body","description","domain","domains","error","level","levels","message","name","note","summary","title","value","effect","failure_mode","cause","operating_scenario","safe_state","ftti","rationale","hazard","assumptions","source_function"]),Gr=new Set(["fields","diff"])}});async function $a(e,t){const r=Ia.get(t),a=Date.now();if(r&&a-r.at<Ea)return r.status;const{data:i,error:n}=await e.from("users").select("platform_status").eq("id",t).maybeSingle();if(n)throw n;const s=i?.platform_status??"pending";return Ia.set(t,{status:s,at:a}),s}function qa(e){return JSON.stringify(Sa(e),null,2)}var za,Ma,Ta,Ha,Da,Ca=x({"src/middleware/status-gate.ts"(){Oa(),Ea=3e4,Ia=new Map,Ra="ATOMS MCP is connected. org_suspended lists the suspended organizations visible to you (every suspended organization for a platform admin); their projects are unavailable until a platform admin reactivates them."}}),Pa={};async function Ua(){if(za)try{const e=await Q();e&&e.expires_at>Da&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),Na())}catch{}if(za&&Ha>Date.now()+6e4)return za;za&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:r}=await je(),i=e.split(".");if(3===i.length)try{const e=JSON.parse(Buffer.from(i[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());Ha=1e3*(e.exp??0)}catch{Ha=Date.now()+36e5}try{const e=await Q();Da=e?.expires_at??0}catch{Da=0}const n=a.createClient(me,_e,{global:{headers:{Authorization:`Bearer ${e}`}}});return Ma=t,Ta=r,za=n}function Na(){za=null,Ma=null,Ta=null,Ha=0,Da=0,Ia.clear()}function La(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 Fa(e){try{return await e()}catch(t){if(!La(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),Na(),await e()}}function Wa(){if(!Ma)throw new Error("Not authenticated. Call getClient() first.");return Ma}function Va(){return Ta??""}async function Ba(e,t){const r=Wa(),{data:a,error:i}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(i||!a)throw new Error(`Project '${t}' not found`);const{data:n,error:s}=await e.from("org_members").select("role").eq("user_id",r).eq("org_id",a.org_id).maybeSingle();if(s||!n){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"===n.role)throw new Error("VIEWER_ROLE");return n.role}async function Ja(e,t){const r=Wa(),{data:a,error:i}=await e.from("projects").select("org_id, created_by").eq("id",t).maybeSingle();if(i||!a)throw new Error(`Project '${t}' not found`);const{data:n,error:s}=await e.from("org_members").select("role").eq("user_id",r).eq("org_id",a.org_id).maybeSingle();if(s||!n)throw new Error("Not a member of this project's organization");if("admin"===n.role)return"admin";if(a.created_by===r)return"owner";throw new Error("PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED")}E(Pa,{getClient:()=>Ua,getUserEmail:()=>Va,getUserId:()=>Wa,invalidateClient:()=>Na,isJwtExpiredError:()=>La,requireProjectFieldDefinitionAccess:()=>Ja,requireWriteAccess:()=>Ba,withJwtRetry:()=>Fa});var Qa,Ga,Ya=x({"src/db/client.ts"(){$e(),oe(),we(),Ca(),za=null,Ma=null,Ta=null,Ha=0,Da=0}}),Ka={};async function Za(){const e=n.randomBytes(32).toString("base64url"),t=n.createHash("sha256").update(e).digest("base64url"),r=`http://localhost:${Qa}${Ga}`,a=new s.URL(`${fe}/auth/mcp-consent`);return a.searchParams.set("redirect_uri",r),a.searchParams.set("code_challenge",t),a.searchParams.set("code_challenge_method","S256"),new Promise((t,r)=>{let n;function o(){clearTimeout(n)}const c=i.createServer(async(a,i)=>{const n=new s.URL(a.url??"/",`http://localhost:${Qa}`);if(n.pathname!==Ga)return i.writeHead(404),void i.end("Not found");try{if("access_denied"===n.searchParams.get("error"))return i.writeHead(200,{"Content-Type":"text/html"}),i.end(ei("Authorization was cancelled.")),o(),c.close(),void r(new Error("Authorization cancelled by user."));const a=n.searchParams.get("code");if(a){const n=await fetch(`${me}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:_e},body:JSON.stringify({auth_code:a,code_verifier:e})}),s=await n.json();if(!n.ok||!s.access_token){const e=s.error_description??s.msg??"Unknown error";return i.writeHead(200,{"Content-Type":"text/html"}),i.end(ei(`Code exchange failed: ${e}`)),o(),c.close(),void r(new Error(`Code exchange failed: ${e}`))}let l="authenticated";try{l=JSON.parse(Buffer.from(s.access_token.split(".")[1],"base64").toString()).email??l}catch{}const{createClient:d}=await import("@supabase/supabase-js"),p=d(me,_e,{global:{headers:{Authorization:`Bearer ${s.access_token}`}}}),{data:u,error:m}=await p.from("org_members").select("org_id").limit(1);return m||!u||0===u.length?(i.writeHead(200,{"Content-Type":"text/html"}),i.end(ei('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://atoms.tech">atoms.tech</a> first, then run this login command again.')),o(),c.close(),void r(new Error("No ATOMS account found. Sign up at atoms.tech first."))):s.refresh_token?(await G({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:Date.now()+1e3*(s.expires_in??3600),user_email:l}),i.writeHead(200,{"Content-Type":"text/html"}),i.end(Xa(l)),o(),c.close(),void t({email:l})):(i.writeHead(200,{"Content-Type":"text/html"}),i.end(ei("Sign-in succeeded but no refresh token was issued, so the session would expire within the hour. This usually points to a Supabase Auth setting (refresh-token rotation or session policy). Please contact ATOMS support.")),o(),c.close(),void r(new Error("No refresh token issued by Supabase — cannot persist a durable session.")))}const s=n.searchParams.get("access_token"),l=n.searchParams.get("refresh_token"),d=parseInt(n.searchParams.get("expires_in")??"3600",10);s&&l?(await G({access_token:s,refresh_token:l,expires_at:Date.now()+1e3*d}),i.writeHead(200,{"Content-Type":"text/html"}),i.end(Xa("authenticated")),o(),c.close(),t({email:"authenticated"})):(i.writeHead(200,{"Content-Type":"text/html"}),i.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){i.writeHead(500),i.end("Authentication failed"),o(),c.close(),r(e)}});c.on("request",async(e,a)=>{if("POST"===e.method&&"/token"===e.url){let i="";e.on("data",e=>{i+=e.toString()}),e.on("end",async()=>{try{const e=JSON.parse(i);await G({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),a.writeHead(200,{"Content-Type":"application/json"}),a.end(JSON.stringify({ok:!0})),o(),c.close(),t({email:e.user_email??"authenticated"})}catch(e){a.writeHead(500),a.end("Failed to store credentials"),o(),c.close(),r(e)}})}}),c.listen(Qa,"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${a.toString()}\n\n`);try{const{default:e}=await import("open");await e(a.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),n=setTimeout(()=>{c.close(),r(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function Xa(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 ei(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Failed</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #450a0a;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 { font-size: 22px; font-weight: 600; margin-bottom: 16px; color: #ef4444; }\n .reason { font-size: 14px; color: #a3a3a3; line-height: 1.6; }\n .reason a { color: #7c3aed; text-decoration: underline; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#ef4444" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1>Authorization Failed</h1>\n <p class="reason">${e}</p>\n </div>\n</body>\n</html>`}E(Ka,{login:()=>Za});var ti,ri,ai,ii,ni=x({"src/auth/login.ts"(){oe(),we(),Qa=19275,Ga="/callback"}});function si(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of ai)if(t.test(e.trim()))return"[redacted]";return e.length>ii?e.slice(0,ii)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>si(e,t+1));if(null!==e&&"object"==typeof e){const r={};for(const[a,i]of Object.entries(e)){const e=a.toLowerCase();ti.has(e)?r[a]="[redacted]":ri.has(e)?r[a]="string"==typeof i?"[content]":si(i,t+1):r[a]=si(i,t+1)}return r}return e}function oi(e){return si(e)}var ci,li,di,pi,ui,mi=x({"src/middleware/audit.ts"(){ti=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),ri=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),ai=[/^[^\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_-]+$/],ii=200}}),_i=x({"src/middleware/rate-limiter.ts"(){ci=60,li=6e4}});function fi(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?di.test(e)?e:(pi||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),pi=!0),null):null}var hi,gi=x({"src/middleware/project-scope.ts"(){di=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pi=!1,ui=class extends Error{expectedProjectId;receivedProjectId;constructor(e,t){super("Tool call rejected: project_id is outside the configured ATOMS_MCP_PROJECT_ID scope."),this.name="ProjectScopeError",this.expectedProjectId=e,this.receivedProjectId=t}}}});function yi(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?hi:t:hi}var wi,vi,bi,ji,ki=x({"src/core/client-identity.ts"(){hi="claude_desktop"}}),Si=x({"src/core/timestamps.ts"(){wi=o.z.string().datetime({offset:!0})}});function Ai(e){return 32===e||9===e||13===e||10===e}function xi(e){if("string"!=typeof e)return NaN;const t=vi.exec(function(e){let t=0,r=e.length;for(;t<r&&Ai(e.charCodeAt(t));)t++;for(;r>t&&Ai(e.charCodeAt(r-1));)r--;return e.slice(t,r)}(e));if(!t)return NaN;const[,r,a,i,n="0",s="0",o="0",c="",l="Z"]=t,d=Number(r),p=Number(a),u=Number(i),m=Date.UTC(d,p-1,u,Number(n),Number(s),Number(o));if(new Date(m).getUTCDate()!==u)return NaN;let _=0;if("Z"!==l.toUpperCase()){const e="-"===l[0]?-1:1,t=l.slice(1).replace(":","");_=e*(60*Number(t.slice(0,2))+(t.length>2?Number(t.slice(2,4)):0))}return 1e3*(m-6e4*_)+Number(`${c}000000`.slice(0,6))}function Ei(e,t){const r=xi(e),a=xi(t),i=!Number.isNaN(r),n=!Number.isNaN(a);return i&&n?r===a?0:r>a?-1:1:i?-1:n?1:0}function Ii(e){return"passed"===e||"failed"===e||"blocked"===e}function Ri(e){const t=e.data?.status,r=e.data?.runs;if("test-case"===e.type&&Array.isArray(r)){const e=function(e){if(!e||0===e.length)return;const t=function(e,t){let r;for(const a of e??[])t&&!t(a)||(void 0===r||Ei(a.date,r.date)<0)&&(r=a);return r}(e,e=>Ii(e.result))?.result;return Ii(t)?t:"not-run"}(r);if(void 0!==e)return e}return"string"==typeof t?t:void 0}function Oi(e){return`${e} has runs: ${bi}. Record a run: atoms_record_test_result(s).`}var $i,qi,zi=x({"src/core/run-order.ts"(){vi=/^([1-9]\d{3})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?:[T ]([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d+))?)? ?(Z|[+-](?:0\d|1[0-5])(?::?[0-5]\d)?)?)?$/i,bi="its status comes from its runs and cannot be set",ji="status (passed|failed|blocked|not-run): only for a test case with no runs. A test case that has runs takes its status from its newest run, so this tool refuses status for it; record a run with atoms_record_test_result or atoms_record_test_results instead"}});function Mi(e,t){return"requirement"!==t?`req_type applies only to requirements (type='requirement'), not '${t}'.`:qi.includes(e)?`req_type '${e}' names an analysis row, which is created by atoms_create_analysis, not atoms_create_item / atoms_update_item. Use atoms_create_analysis (variant iso26262 | iso14971 | design | process | software | use).`:$i.includes(e)?null:`Unknown req_type '${e}'. Allowed: ${$i.join(", ")}.`}var Ti,Hi,Di=x({"src/core/req-type.ts"(){$i=["functional","interface","performance","safety"],qi=["safety-goal","failure-mode"]}});function Ci(e){return"requirement"===e.type&&"string"==typeof e.data?.req_type&&qi.includes(e.data.req_type)}function Pi(e,t){const r=new Map;for(const t of e)r.set(t.id,t);const a=new Map,i=(e,t)=>{if(e===t)return;const i=r.get(e),n=r.get(t);if(!i||!n||!Ci(i))return;if("requirement"!==n.type||Ci(n))return;let s=a.get(e);s||a.set(e,s=new Set),s.add(t)};for(const e of t)"mitigated_by"===e.type?i(e.from_id,e.to_id):"mitigates"===e.type&&i(e.to_id,e.from_id);const n=new Map;for(const[e,t]of a)n.set(e,[...t].sort((e,t)=>e.localeCompare(t)));return n}function Ui(e,t){const r=e.filter(e=>(t?.get(e.id)?.length??0)>0).map(e=>e.id);return{count:r.length,ids:r}}function Ni(e,t,r){return e.filter(e=>!t.has(e)&&(r.get(e)?.length??0)>0).length}var Li,Fi=x({"src/core/coverage-mitigation.ts"(){Di(),Ti="covered and coverage_percent count a requirement's own linked test cases (its verified_by, or a test case's verifies), whatever their result. A hazard, failure mode or risk row that has no test case of its own but at least one live mitigating requirement is listed in uncovered, as always, and the app reads it as covered through its mitigation: covered_via_mitigation is { count, ids } for those rows, and each such row in uncovered_items carries mitigated_by, the ids of its live mitigating requirements. It does not change covered or coverage_percent.",Hi="coverage.covered and coverage.percent count a requirement's own linked test cases. coverage.via_mitigation counts the requirements with no test case of their own that are hazard, failure mode or risk rows with at least one live mitigating requirement, which the app reads as covered through its mitigation; it is not part of covered or percent."}});var Wi=x({"src/apps/register.ts"(){Li={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function Vi(e){return e.replace(/[\\%_*]/g,e=>`\\${e}`)}function Bi(e){return`"${`*${Vi(e)}*`.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Ji(e){return Vi(e)}function Qi(e){return`*"${Vi(e)}"*`}var Gi=x({"src/core/postgrest.ts"(){}});async function Yi(e,t,r){let a=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0});r.type&&(a=a.eq("type",r.type)),r.domain&&(a=a.filter("data->tags->>domains","ilike",Qi(r.domain))),r.level&&(a=a.filter("data->tags->>level","ilike",Ji(r.level))),a=a.range(r.offset,r.offset+r.limit-1);const{data:i,error:n,count:s}=await a;if(n)throw new Error(n.message);return{items:i??[],totalCount:s??0}}async function Ki(e,t,r){const{data:a,error:i}=await e.from("items").select("*").eq("id",r).eq("project_id",t).is("deleted_at",null).maybeSingle();if(i)throw new Error(i.message);return a}async function Zi(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:a}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",t.baseline_id).maybeSingle();if(a)throw new Error(`resolveSnapshotAt: ${a.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 Xi(e,t){const{data:r,error:a}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, deleted_at, release_version, release_status").eq("id",t).maybeSingle();if(a)throw new Error(`getBaselineById: ${a.message}`);return r&&null===r.deleted_at?r:null}function en(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 tn(e,t,r){const{data:a,error:i}=await e.rpc("project_state_at",{p_project_id:t,p_snapshot_at:r});if(i)throw new Error(`projectStateAt: ${i.message}`);return a??[]}async function rn(e,t,r,a){const i=r.trim();if(!i)return{items:[],totalCount:0};let n=null;if(a.asset&&a.asset.trim()){const{data:r,error:i}=await e.from("test_results").select("item_id").eq("project_id",t).eq("asset",a.asset.trim());if(i)throw new Error(i.message);const s=new Set;for(const e of r??[])s.add(e.item_id);if(n=Array.from(s),0===n.length)return{items:[],totalCount:0}}let s=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${Bi(i)},data->>body.ilike.${Bi(i)},data->>summary.ilike.${Bi(i)}`).limit(a.limit);a.type&&(s=s.eq("type",a.type)),a.domain&&(s=s.filter("data->tags->>domains","ilike",Qi(a.domain))),a.level&&(s=s.filter("data->tags->>level","ilike",Ji(a.level))),n&&(s=s.in("id",n));const{data:o,error:c,count:l}=await s;if(c)throw new Error(c.message);return{items:o??[],totalCount:l??0}}function an(e,t){const r=new Set(e.map(e=>e.id)),a=new Set,i=[],n=(e,t,n)=>{if(e===t)return;if(!r.has(e)||!r.has(t))return;const s=`${e}|${t}|${n}`;a.has(s)||(a.add(s),i.push({from_id:e,to_id:t,type:n}))};for(const e of t)n(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"))n(t.id,e,"parent");for(const e of r("children"))n(t.id,e,"child");for(const e of r("related"))n(t.id,e,"related");for(const e of r("verifies"))n(t.id,e,"verifies");for(const e of r("verified_by"))n(t.id,e,"verified_by");for(const e of r("mitigated_by"))n(t.id,e,"mitigated_by");for(const e of r("mitigates"))n(t.id,e,"mitigates")}return i}async function nn(e,t,r){const a="requirement"===r?"REQ":"test-case"===r?"TC":"note"===r?"NOTE":"TABLE",{data:i,error:n}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:a});if(n)throw new Error(`ID generation failed: ${n.message}`);return i}var sn=x({"src/db/queries.ts"(){Gi(),Tr(),Fi()}}),on={};async function cn(){try{const e=await Fa(async()=>{const e=await Ua();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=fi(),r=H,a=P().project_scope,i=a?new Set(a):null;return Aa(ea(e.filter(e=>!r||e.org_id===r).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 xa(ya(e))}}E(on,{listProjectsHandler:()=>cn});var ln=x({"src/tools/list-projects.ts"(){Ya(),sn(),gi(),U(),Oa()}}),dn={};async function pn(e){try{const t=await Ua();let r,a,i=null;try{i=await Zi(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return xa(va(e.message))}if(i){const n=(await tn(t,e.project_id,i)).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.some(t=>sr(t)===sr(e.domain)))return!1}return!e.level||Vt(r?.tags?.level)===Vt(e.level)});a=n.length,r=n.slice(e.offset,e.offset+e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const i=await Yi(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});r=i.items,a=i.totalCount}return Aa(ea(r.map(e=>({id:e.id,title:e.title,type:e.type,status:Ri(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),ta(a,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(dn,{listItemsHandler:()=>pn});var un,mn=x({"src/tools/list-items.ts"(){Ya(),sn(),Oa(),Tr(),zi()}}),_n={};function fn(e,t){if(!t)return e;const r={...e};for(const e of un){const a=t[e];null!=a&&(r[e]=a)}return r}async function hn(e){try{const r=await Ua();let a=null;try{a=await Zi(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return xa(ra(e.message,["Pass baseline_id OR as_of, not both"]))}const i=a?await async function(e,t,r,a){const{data:i,error:n}=await e.rpc("item_state_at",{p_item_id:r,p_project_id:t,p_snapshot_at:a});if(n)throw new Error(`itemStateAt: ${n.message}`);return(i??[])[0]??null}(r,e.project_id,e.item_id,a).then(e=>e?en(e):null):await Ki(r,e.project_id,e.item_id);if(!i)return xa(aa("Item",e.item_id));const n={parents:[],children:[],related:[],verified_by:[],verifies:[],mitigated_by:[],mitigates:[]};if(a){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 t=await async function(e,t,r){const{data:a,error:i}=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(i)throw new Error(i.message);return a??[]}(r,e.project_id,e.item_id),a={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",mitigated_by:"mitigated_by",mitigates:"mitigates"},s={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"},o=(e,t)=>{if(!(e in n))return;const r=n[e];r.includes(t)||r.push(t)},c=new Set([e.item_id]);for(const e of t)c.add(e.from_id),c.add(e.to_id);const l=i.data?.relationships??{};for(const e of Object.keys(n)){const t=l[e];if(Array.isArray(t))for(const e of t)"string"==typeof e&&c.add(e)}let d=new Set([e.item_id]);const p=Array.from(c);if(p.length>0){const{data:t,error:a}=await r.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",p);if(a)throw new Error(a.message);d=new Set((t??[]).map(e=>e.id)),d.add(e.item_id)}const u=e=>d.has(e);for(const r of t)if(r.from_id===e.item_id){if(!u(r.to_id))continue;o(a[r.type]??r.type,r.to_id)}else{if(!u(r.from_id))continue;o(s[r.type]??r.type,r.from_id)}for(const t of Object.keys(n)){const r=l[t];if(Array.isArray(r))for(const a of r)"string"==typeof a&&a!==e.item_id&&u(a)&&o(t,a)}}let s=[];if("test-case"===i.type)if(a)s=(i.data?.runs??[]).map(e=>({base:{result:e.result??"not-run",run_by:e.by??e.run_by??null,run_at:e.date??e.run_at??"",note:e.note??null,..."string"==typeof e.asset?{asset:e.asset}:{}},canonical:e})).filter(e=>"string"==typeof e.base.run_at&&e.base.run_at.length>0).sort((e,t)=>Ei(String(e.base.run_at),String(t.base.run_at))).slice(0,20).map(e=>fn(e.base,e.canonical));else{const{data:t,error:a}=await r.from("test_results").select("result, run_by, run_at, note, asset").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);if(!a&&t){const e=new Map;for(const t of i.data?.runs??[])"string"==typeof t?.date&&e.set(t.date,t);s=t.map(t=>fn(t,e.get(String(t.run_at))))}}return Aa(ea({id:i.id,type:i.type,req_type:i.data?.req_type,title:i.title,summary:i.data?.summary,body:i.data?.body,domains:i.data?.tags?.domains??[],level:i.data?.tags?.level,tags:i.data?.tags??{domains:[]},ownership:i.data?.ownership??{primary:null,additional:[]},relationships:n,links:i.data?.links??[],fields:(t=i.data?.fields,!t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>"string"==typeof e[1]))),status:Ri(i),..."test-case"===i.type?{latest_result:s[0]?.result??"not-run",test_results:s}:{},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")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}var t}E(_n,{getItemHandler:()=>hn});var gn=x({"src/tools/get-item.ts"(){Ya(),zi(),sn(),Oa(),un=["point","release_id","build","environment","tooling","step_results"]}}),yn={};async function wn(e){try{const t=await Ua();let r,a,i=null;try{i=await Zi(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return xa(va(e.message))}if(i){const n=await tn(t,e.project_id,i),s=e.query.trim().toLowerCase(),o=0===s.length?[]:n.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))});a=o.length,r=o.slice(0,e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else{const i=await rn(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});r=i.items,a=i.totalCount}return Aa(ea(r.map(e=>({id:e.id,title:e.title,type:e.type,status:Ri(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ta(a,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(yn,{searchHandler:()=>wn});var vn=x({"src/tools/search.ts"(){Ya(),sn(),Oa(),zi()}}),bn={};async function jn(e){try{const t=await Ua(),{access_token:r}=await je(),{items:a,totalCount:i}=await async function(e,t,r,a){const{ATOMS_SUPABASE_URL:i,ATOMS_SUPABASE_ANON_KEY:n}=await Promise.resolve().then(()=>(we(),ge)),s=await fetch(`${i}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.accessToken}`,apikey:n},body:JSON.stringify({input:r})});if(!s.ok)throw new Error(`Embed function failed: ${s.status}`);const{embedding:o}=await s.json(),{data:c,error:l}=await e.rpc("semantic_search",{query_embedding:o,p_project_id:t,match_threshold:.3,match_count:a.limit,p_type:a.type||null});if(l)throw new Error(l.message);return{items:c??[],totalCount:(c??[]).length,method:"semantic"}}(t,e.project_id,e.query,{type:e.type,limit:e.limit,accessToken:r});return Aa(ea(a.map(e=>({id:e.id,title:e.title,type:e.type,status:Ri(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),ta(i,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(bn,{semanticSearchHandler:()=>jn});var kn,Sn=x({"src/tools/semantic-search.ts"(){Ya(),$e(),sn(),Oa(),zi()}});function An(e,t){return t>0?Math.round(e/t*1e3)/10:kn}function xn(e,t){const r={passed:0,failed:0,blocked:0,not_run:0};if(0===e.length)return r;const a=new Map;for(const e of t)a.has(e.item_id)||a.set(e.item_id,e.result);for(const t of e){const e=a.get(t);"passed"===e?r.passed++:"failed"===e?r.failed++:"blocked"===e?r.blocked++:r.not_run++}return r}var En=x({"src/core/project-summary.ts"(){kn=100}}),In={};async function Rn(e){try{if(e.baseline_id&&e.as_of)return xa(oa("baseline_id and as_of are mutually exclusive"));const t=await Ua();let r;if(e.baseline_id){const a=await Xi(t,e.baseline_id);if(!a)return xa(oa(`Baseline ${e.baseline_id} not found`));if(a.project_id!==e.project_id)return xa(oa("Baseline does not belong to this project"));r=a.snapshot_at}else e.as_of&&(r=e.as_of);const{covered:a,uncovered:i,total:n,mitigators:s}=await async function(e,t,r){let a,i,n;if(r.snapshotAt){const s=(await tn(e,t,r.snapshotAt)).map(en);a=s.filter(e=>"requirement"===e.type),i=s.map(e=>({id:e.id,type:e.type,data:e.data})),n=[]}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);a=r??[];const{data:o,error:c}=await e.from("items").select("id, type, data").eq("project_id",t).is("deleted_at",null);if(c)throw new Error(c.message);i=o??[];const{data:l,error:d}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t);if(d)throw new Error(d.message);n=l??[]}const s=a.filter(e=>!(r.domain&&!(e.data?.tags?.domains??[]).some(e=>sr(e)===sr(r.domain))||r.level&&Vt(e.data?.tags?.level)!==Vt(r.level))),o=an(i,n),c=new Set;for(const e of o)"verifies"===e.type?c.add(e.to_id):"verified_by"===e.type&&c.add(e.from_id);const l=s.filter(e=>c.has(e.id)),d=s.filter(e=>!c.has(e.id)),p=Pi(i,o);return{covered:l,uncovered:d,total:s.length,mitigators:p}}(t,e.project_id,{domain:e.domain,level:e.level,snapshotAt:r}),o=i.map(e=>{const t=function(e,t){if(Ci(e))return[...t?.get(e.id)??[]]}(e,s);return{id:e.id,title:e.title,type:e.type,status:Ri(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,...t?{mitigated_by:t}:{}}});return Aa(ea({covered:a.length,uncovered:i.length,total:n,coverage_percent:An(a.length,n),covered_via_mitigation:Ui(i,s),uncovered_items:o}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(In,{getCoverageHandler:()=>Rn});var On,$n=x({"src/tools/get-coverage.ts"(){Ya(),sn(),Oa(),zi(),En(),Fi()}}),qn={};async function zn(e){try{const t=await Ua();let r;if(e.release_id){const a=await Xi(t,e.release_id);if(!a)return xa(oa(`Release ${e.release_id} not found`));if(a.project_id!==e.project_id)return xa(oa("Release does not belong to this project"));if(null===a.release_version)return xa(ra(`Baseline "${a.name}" is not a formal Release.`,["Promote the baseline to a Release first (Snapshots view in the app)","Use atoms_list_baselines to see which baselines carry a release_version"]));r=a}else{const{data:a,error:i}=await t.from("baselines").select("id, release_version, release_status").eq("project_id",e.project_id).eq("release_status","released").is("deleted_at",null).maybeSingle();if(i)return xa(va(i.message));if(!a)return xa(On);r=a}const{data:a,error:i}=await t.rpc("verification_readiness",{p_project_id:e.project_id,p_release_id:r.id});if(i)return xa(ya(i));const{data:n,error:s}=await t.from("verification_status").select("requirement_id, state, stale, points_total, points_run").eq("project_id",e.project_id).eq("release_id",r.id);if(s)return xa(va(s.message));const o=(n??[]).slice().sort((e,t)=>e.requirement_id<t.requirement_id?-1:e.requirement_id>t.requirement_id?1:0),c={release:{id:r.id,version:r.release_version,status:r.release_status},readiness:a??{},requirements:o,...0===o.length?{hint:"projection empty; an admin may need to run rebuild_verification_from_runs for this project"}:{}};if(e.include_gaps){const{data:a,error:i}=await t.rpc("verification_notrun_points",{p_project_id:e.project_id,p_release_id:r.id});if(i)return xa(ya(i));c.gaps=a??[]}return Aa(ea(c))}catch(e){return xa(ya(e))}}E(qn,{verificationStatusHandler:()=>zn});var Mn=x({"src/tools/verification-status.ts"(){Ya(),sn(),Oa(),On=ra("This project has no current formal Release.",["Promote a locked baseline to a Release first (Snapshots view in the app)","Or pass release_id explicitly to query a specific (e.g. superseded) Release","Use atoms_list_baselines to see which baselines carry a release_version"])}});function Tn(e){if(!e||"object"!=typeof e)return{};const t=e,r=t.data,a=r&&"object"==typeof r?{...r}:{};return"title"in t&&(a.title=t.title),"type"in t&&(a.type=t.type),a}var Hn=x({"src/core/history.ts"(){}}),Dn={};async function Cn(e){try{const t=await Ua(),r=await async function(e,t,r,a){const{data:i,error:n}=await e.from("item_revisions").select("id, revision_number, fields_snapshot, valid_from, changed_by, event_source, event_session_id").eq("item_id",r).eq("project_id",t).order("revision_number",{ascending:!1}).limit(a);if(n)throw new Error(n.message);return i??[]}(t,e.project_id,e.item_id,e.limit);if(r.length>0){const t=function(e){return e.map((t,r)=>{const a=e[r+1]??null,i=1===t.revision_number||null===a,n="system"===t.event_source?"system_normalization":1===t.revision_number?"created":"updated",s=i?["(created)"]:function(e,t){const r=new Set([...Object.keys(e),...Object.keys(t)]),a=[];for(const i of r)JSON.stringify(e[i])!==JSON.stringify(t[i])&&a.push(i);return a}(Tn(a?.fields_snapshot),Tn(t.fields_snapshot));return{id:t.id,event_type:n,changed_by:t.changed_by??null,changed_at:t.valid_from,actor:"mcp"===t.event_source?"mcp_claude":"user",session_id:t.event_session_id??null,fields_changed:s}})}(r);return Aa(ea(t,ta(t.length,e.limit,0)))}const a=await async function(e,t,r,a){const{data:i,error:n}=await e.from("change_history").select("*").eq("item_id",r).eq("project_id",t).order("changed_at",{ascending:!1}).limit(a);if(n)throw new Error(n.message);return i??[]}(t,e.project_id,e.item_id,e.limit),i=a.map(e=>{const t=[],r=e.old_data,a=e.new_data;if(r&&a){const e=new Set([...Object.keys(r),...Object.keys(a)]);for(const i of e)JSON.stringify(r[i])!==JSON.stringify(a[i])&&t.push(i)}else a?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 Aa(ea(i,ta(i.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(Dn,{getHistoryHandler:()=>Cn});var Pn=x({"src/tools/get-history.ts"(){Ya(),sn(),Hn(),Oa()}});function Un(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function Nn(e){const t=Fn(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:`["${t}"]`}function Ln(e){const t=Un(e.from_id),r=Un(e.to_id);return"child"===e.type?`${t} --\x3e ${r}`:"verified_by"===e.type?`${t} -.-> ${r}`:"related"===e.type?`${t} -.- ${r}`:null}function Fn(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var Wn=x({"src/core/mermaid.ts"(){}}),Vn={};async function Bn(e){try{if(e.baseline_id&&e.as_of)return xa(oa("baseline_id and as_of are mutually exclusive"));const t=await Ua();let r,a,i;if(e.baseline_id){const a=await Xi(t,e.baseline_id);if(!a)return xa(oa(`Baseline ${e.baseline_id} not found`));if(a.project_id!==e.project_id)return xa(oa("Baseline does not belong to this project"));r=a.snapshot_at}else e.as_of&&(r=e.as_of);if(r){a=(await tn(t,e.project_id,r)).map(en).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),i=an(a,[])}else{const{data:r,error:n}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(n)throw new Error(n.message);a=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);i=an(a,s??[])}return Aa(ea(function(e){const t=e.items,r=e.relationships??[],a=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${Fn(e.emptyLabel??"No items in project")}]`,node_count:0,edge_count:0};const i=new Map(t.map(e=>[e.id,e])),n=function(e,t,r,a){if(r)return[r];const i=new Set(t.filter(e=>"child"===e.type).map(e=>e.to_id));return e.filter(e=>!i.has(e.id)).filter(e=>a||"test-case"!==e.type).map(e=>e.id)}(t,r,e.rootItemId,e.includeTests),s=n.map(e=>({id:e,depth:0})),o=new Set,c=new Set,l=[],d=[];for(;s.length>0;){const{id:t,depth:n}=s.shift();if(o.has(t)||n>a)continue;const p=i.get(t);if(p&&(e.includeTests||"test-case"!==p.type)){o.add(t),l.push(` ${Un(t)}${Nn(p)}`);for(const l of r){if(l.from_id!==t)continue;const r=i.get(l.to_id);if(!r)continue;if(!e.includeTests&&"test-case"===r.type)continue;if(n+1>a)continue;const p=Ln(l);if(!p)continue;const u=`${l.from_id}:${l.type}:${l.to_id}`;c.has(u)||(c.add(u),d.push(` ${p}`),o.has(l.to_id)||s.push({id:l.to_id,depth:n+1}))}}}return{mermaid:["graph TD",...l,...d].join("\n"),node_count:o.size,edge_count:c.size}}({items:a,relationships:i,rootItemId:e.root_item_id,depth:e.depth,includeTests:e.include_tests,emptyLabel:"No items in project"})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(Vn,{exportMermaidHandler:()=>Bn});var Jn,Qn,Gn=x({"src/tools/export-mermaid.ts"(){Ya(),sn(),Oa(),Wn()}});function Yn(e){const t=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(t){const r=t.toLowerCase();if("1"===r||"true"===r||"all"===r)return!0;if(t.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!P().require_confirmation_for.includes(e)}function Kn(e,t=Jn){const r=Date.now()+t,a={...e,exp:r},i=Buffer.from(JSON.stringify(a)).toString("base64url");return{token:`${i}.${k.default.createHmac("sha256",Qn).update(i).digest("base64url")}`,expires_at:new Date(r).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function Zn(e,t){if("string"!=typeof e||!e.includes("."))return{valid:!1,reason:"Token format invalid"};const[r,a]=e.split(".");if(!r||!a)return{valid:!1,reason:"Token format invalid"};const i=k.default.createHmac("sha256",Qn).update(r).digest("base64url"),n=Buffer.from(a,"utf8"),s=Buffer.from(i,"utf8");if(n.length!==s.length||!k.default.timingSafeEqual(n,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 Xn(e){if(Array.isArray(e))return e.map(Xn);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e).sort())t[r]=Xn(e[r]);return t}return e}function es(e){const t=JSON.stringify(Xn(e));return k.default.createHash("sha256").update(t).digest("base64url").slice(0,16)}var ts=x({"src/middleware/confirmation.ts"(){U(),Jn=6e4,Qn=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:k.default.randomBytes(32).toString("base64url")})()}}),rs={};function as(e){const t=Xr(e??"");return"sub-system"===t?"subsystem":t}async function is(e,t){const{data:r}=await e.from("metadata").select("levels").eq("project_id",t).maybeSingle();return{levels:r?.levels??[]}}async function ns(e,t,r){const a=Xr(r??""),i=as(a);if(!a)return!1;if(!$(P(),"atoms_create_level"))return!1;try{const{levels:r}=await is(e,t);if(r.some(e=>as(e)===i))return!1;const{error:n}=await e.rpc("mutate_project_levels",{p_project_id:t,p_action:"add",p_values:[a]});return!n}catch{return!1}}async function ss(e){try{const t=await Ua(),{levels:r}=await is(t,e.project_id),{data:a}=await t.from("items").select("data").eq("project_id",e.project_id).is("deleted_at",null),i={};for(const e of a??[]){const t=e.data?.tags,r=as(t?.level);r&&(i[r]=(i[r]??0)+1)}return Aa(ea({levels:r.map((e,t)=>({name:e,prefix:`L${t}`,item_count:i[as(e)]??0})),total:r.length,note:"L# is the level's position in this list (0-based). Names are user-defined."}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function os(e){try{const t=await Ua();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const{levels:r}=await is(t,e.project_id),a=Xr(e.name),i=as(a);if(!a)return xa(oa("Level name cannot be empty."));if(r.some(e=>as(e)===i))return xa(oa(`Level "${a}" already exists in this project.`));const{data:n,error:s}=await t.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"add",p_values:[a]});if(s)throw new Error(s.message);const o=(n?.levels??[...r,a]).indexOf(a),c=`L${o>=0?o:r.length}`;return Aa(ea({level:{name:a,prefix:c},message:`Level "${a}" registered as ${c}. Tag items with level="${a}".`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function cs(e){try{const t=await Ua();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const r=as(ja(e.name));if(!r)return xa(oa("Level name cannot be empty."));const{levels:a}=await is(t,e.project_id),i=a.filter(e=>as(e)===r),{data:n,error:s}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null);if(s)throw new Error(s.message);const o=(n??[]).filter(e=>as(e.data?.tags?.level)===r).length;if(0===i.length&&0===o)return xa(aa("Level",e.name));const c=i[0]??e.name;if(o>0)return xa(oa(`Level "${c}" is used by ${o} item${o>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`));if(Yn("atoms_delete_level")){const t={tool:"atoms_delete_level",project_id:e.project_id,target:r};if(!e.confirmation_token){const e=Kn(t);return Aa(ea({status:"confirmation_required",preview:{level_name:c,items_using_count:0},confirmation_token:e.token,expires_at:e.expires_at,expires_in_seconds:e.expires_in_seconds,message:`Re-call atoms_delete_level with the same project_id, name, and confirmation_token within ${e.expires_in_seconds}s to execute.`}))}const a=Zn(e.confirmation_token,t);if(!a.valid)return xa(oa(`confirmation_token rejected: ${a.reason}`))}const{data:l,error:d}=await t.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"remove",p_values:i});if(d)throw new Error(d.message);const p=l?.levels??[],u=Bt(a,p);return Aa(ea({level:{name:c},remaining_levels:p,message:`Level "${c}" deleted. Every later level's L# shifts down by one.`+(u?" "+u:"")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function ls(e){try{const t=await Ua();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const r=Array.isArray(e.names)?e.names.map(e=>ja(String(e??"")).trim()).filter(e=>e.length>0):[];if(0===r.length)return xa(oa("names must be a non-empty array of the project's existing levels, in the order you want them."));const{levels:a}=await is(t,e.project_id),i=new Map;for(const e of a)i.set(as(e),e);const n=[],s=new Set,o=`names must list every existing level exactly once. Levels: ${a.length>0?a.join(", "):"(none)"}`;for(const e of r){const t=as(e),r=i.get(t);if(!r||s.has(t))return xa(oa(o));s.add(t),n.push(r)}if(n.length!==a.length)return xa(oa(o));const{data:c,error:l}=await t.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"reorder",p_values:n});if(l)throw new Error(l.message);const d=c?.levels??n,p=Bt(a,d);return Aa(ea({levels:d.map((e,t)=>({name:e,prefix:`L${t}`})),message:"Levels reordered. L# now follows this order everywhere it renders (Strata, sidebar, exports)."+(p?" "+p:"")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(rs,{createLevelHandler:()=>os,deleteLevelHandler:()=>cs,ensureLevelRegistered:()=>ns,listLevelsHandler:()=>ss,reorderLevelsHandler:()=>ls});var ds,ps,us=x({"src/tools/levels.ts"(){Ya(),ts(),Oa(),Tr(),D(),U()}}),ms=x({"src/core/project-field-counts.ts"(){}});function _s(e){if(!Array.isArray(e))return;const t=new Set(e.filter(e=>"string"==typeof e&&ps.has(e)));return 0!==t.size?ds.filter(e=>t.has(e)):void 0}var fs,hs,gs=x({"src/core/field-scope.ts"(){ds=["requirement","test-case","note","table"],ps=new Set(ds)}}),ys={};async function ws(e,t){const{data:r,error:a}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(a)throw a;return vs(r?.fields)}function vs(e){if(!Array.isArray(e))return[];const t=[],r=new Set;for(const a of e){if(!a||"object"!=typeof a)continue;const e=a,i="string"==typeof e.name?e.name.trim():"";if(!i)continue;const n=i.toLowerCase();if(r.has(n))continue;r.add(n);const s=void 0===e.type?"text":"string"==typeof e.type&&hs.has(e.type)?e.type:"text",o=Array.isArray(e.options)?Os(e.options):[],c=_s(e.appliesTo??e.applies_to);t.push({name:i,type:s,..."select"===s?{options:o}:{},...c?{appliesTo:c}:{}})}return t}function bs(e,t){const r=e.name.trim();if(!r)return"Field name cannot be empty.";if(r.length>60)return"Field name must be 60 characters or fewer.";if(!hs.has(e.type))return"Field type is not supported.";const a=t.find(e=>e.name.toLowerCase()===r.toLowerCase());if(a)return`Field "${a.name}" already exists.`;if("select"===e.type){const t=Os(e.options??[]);if(0===t.length)return"Select fields need at least one option.";if(t.length>100)return"Select fields support at most 100 options.";if(t.some(e=>e.length>120))return"Select options must be 120 characters or fewer."}return null}function js(e,t){const r=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!r.has(e.toLowerCase()))}function ks(e,t){const r=new Map(e.map(e=>[e.name.toLowerCase(),e.name])),a={};for(const[e,i]of Object.entries(t))a[r.get(e.toLowerCase())??e]=i;return a}function Ss(e,t,r){if("string"!=typeof r||!e||"object"!=typeof e||Array.isArray(e))return!1;const a=t.toLowerCase();return Object.entries(e).some(([e,t])=>e.toLowerCase()===a&&t===r)}function As(e,t,r=new Set,a){const i=js(e,t);if(i.length>0)return{error:`Unknown field${i.length>1?"s":""}: ${i.join(", ")}. Defined: ${e.length>0?e.map(e=>e.name).join(", "):"(none)"}. Define fields first with atoms_create_field.`};const n={},s=new Map(e.map(e=>[e.name.toLowerCase(),e]));for(const[e,i]of Object.entries(t)){const t=s.get(e.toLowerCase());if(!t)continue;if(Ss(a,e,i)){i.trim()&&(n[t.name]=i);continue}const o=xs(t,i,r);if(o.error)return{error:o.error};o.value&&(n[t.name]=o.value)}return{fields:n}}function xs(e,t,r){const a=t.trim();if(!a)return{value:""};if(a.length>1e4)return{error:`${e.name} is too long.`};switch(e.type){case"text":case"long":return{value:a};case"bool":{const t=a.toLowerCase();return"yes"===t?{value:"yes"}:"no"===t?{value:"no"}:{error:`${e.name} must be yes or no.`}}case"date":return function(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;const t=new Date(`${e}T00:00:00.000Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}(a)?{value:a}:{error:`${e.name} must be an ISO date.`};case"person":return Rs(a)&&r.has(a)?{value:a}:{error:`${e.name} must be an active project member ID.`};case"select":return(e.options??[]).includes(a)?{value:a}:{error:`${e.name} must be one of: ${(e.options??[]).join(", ")}.`};case"number":return Number.isFinite(Number(a))?{value:a}:{error:`${e.name} must be numeric.`};case"link":{const t=function(e){if(!e)return{label:"",url:""};try{const t=JSON.parse(e);if(t&&"object"==typeof t&&"string"==typeof t.url){const e=t.label;return{label:"string"==typeof e?e:"",url:t.url}}}catch{}return{label:"",url:e}}(a);return function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(t.url)?{value:Es(t.label,t.url)}:{error:`${e.name} must be an http(s) URL.`}}}}function Es(e,t){const r=t.trim();return r?JSON.stringify({label:e.trim(),url:r}):""}async function Is(e,t,r,a,i){const n=new Map(r.map(e=>[e.name.toLowerCase(),e])),s=new Map;for(const[e,t]of Object.entries(a)){if(Ss(i,e,t))continue;const r=n.get(e.toLowerCase());"person"===r?.type&&t.trim()&&s.set(t.trim(),r)}const o=new Set;for(const[r,a]of s){if(!Rs(r))return{error:`${a.name} must be an active project member ID.`};const{data:i,error:n}=await e.rpc("is_active_project_member_for_field",{p_project_id:t,p_person_user_id:r,p_actor_user_id:Wa()});if(n)return{error:n.message};!0===i&&o.add(r)}return As(r,a,o,i)}function Rs(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function Os(e){const t=[],r=new Set;for(const a of e){if("string"!=typeof a)continue;const e=a.trim();if(!e)continue;const i=e.toLowerCase();r.has(i)||(r.add(i),t.push(e))}return t}async function $s(e){try{const t=await Ua(),r=await ws(t,e.project_id),a=await async function(e,t,r,a=500){const i=Object.fromEntries(r.map(e=>[e.name,0])),n=new Map(r.map(e=>[e.name.toLowerCase(),e.name]));let s=0;for(;;){const{data:r,error:o}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null).order("id",{ascending:!0}).range(s,s+a-1);if(o)throw o;const c=r??[];for(const e of c){const t=e.data?.fields;if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,r]of Object.entries(t)){const t=n.get(e.toLowerCase());t&&"string"==typeof r&&r.length>0&&(i[t]+=1)}}if(c.length<a)return i;s+=c.length}}(t,e.project_id,r);return Aa(ea({fields:r.map(e=>({name:e.name,type:e.type,options:e.options??[],...e.appliesTo?{appliesTo:e.appliesTo}:{},item_count:a[e.name]??0})),total:r.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(ya(e))}}async function qs(e){try{const t=await Ua();try{await Ja(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return xa(sa("Project admin or owner"));throw e}const{data:r}=await t.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),a=vs(r?.fields),i=_s(e.appliesTo),n={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:Os(e.options??[])}:{},...i?{appliesTo:i}:{}},s=bs(n,a);if(s)return xa(oa(s));const o=function(e,t){return"organization"!==e?null:t&&0!==t.length?t.length>=ds.length?null:'An organization-scoped field cannot be restricted to specific item types (appliesTo is a project-scoped-field feature only; the org field library has no per-type scope column). Omit appliesTo, list all item types, or use scope="project".':null}(e.scope,i);if(o)return xa(oa(o));const{data:c,error:l}="organization"===e.scope?await t.rpc("create_org_project_field_definition",{p_project_id:e.project_id,p_field:n,p_actor_user_id:Wa()}):await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"create",p_field:n,p_field_name:null,p_actor_user_id:Wa()});if(l)throw l;return Aa(ea({field:c?.field??n,..."organization"===e.scope?{created_projects:c?.created_projects??[],skipped_projects:c?.skipped_projects??[]}:{},message:`Field "${n.name}" defined. Set values with atoms_update_item fields={"${n.name}": "<value>"}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(ya(e))}}async function zs(e){try{const t=await Ua();try{await Ja(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return xa(sa("Project admin or owner"));throw e}const r=e.name.trim(),{data:a,error:i}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"delete",p_field:null,p_field_name:r,p_actor_user_id:Wa()});if(i)throw i;return Aa(ea({deleted:a?.deleted??r}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(ya(e))}}async function Ms(e){try{const t=await Ua();try{await Ja(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return xa(sa("Project admin or owner"));throw e}const r=Array.isArray(e.names)?e.names.map(e=>String(e??"").trim()).filter(e=>e.length>0):[];if(0===r.length)return xa(oa("names must be a non-empty array of existing field names, in the order you want them"));const a=await ws(t,e.project_id),i=a.map(e=>e.name.toLowerCase()).sort(),n=r.map(e=>e.toLowerCase()).sort();if(i.length!==n.length||i.some((e,t)=>e!==n[t]))return xa(oa(`names must list every existing field exactly once. Defined: ${a.length>0?a.map(e=>e.name).join(", "):"(none)"}`));const{data:s,error:o}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"reorder",p_field:r,p_field_name:null,p_actor_user_id:Wa()});if(o)throw o;return Aa(ea({fields:vs(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(ya(e))}}E(ys,{PROJECT_FIELD_TYPES:()=>fs,canonicalizeFieldKeys:()=>ks,createFieldHandler:()=>qs,deleteFieldHandler:()=>zs,findUnknownFieldNames:()=>js,getProjectFields:()=>ws,isStoredFieldValue:()=>Ss,listFieldsHandler:()=>$s,normalizeProjectFields:()=>vs,reorderFieldsHandler:()=>Ms,validateAndCanonicalizeFieldValues:()=>As,validateProjectFieldDefinition:()=>bs,validateProjectFieldValuesForWrite:()=>Is});var Ts=x({"src/tools/fields.ts"(){Ya(),Oa(),ms(),gs(),fs=["text","long","bool","date","person","select","number","link"],hs=new Set(fs)}}),Hs={};async function Ds(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}e.title=ja(e.title),void 0!==e.body&&(e.body=ja(e.body)),void 0!==e.summary&&(e.summary=ja(e.summary)),void 0!==e.level&&(e.level=ja(e.level)),e.domains&&(e.domains=e.domains.map(e=>ja(e)));const a=(e.domains??[]).map(Xr).filter(e=>e.length>0),i=void 0!==e.level?Xr(e.level):void 0;if(a.length>0){const{data:r,error:i}=await t.from("metadata").select("domains, function_tags").eq("project_id",e.project_id).maybeSingle();if(i)throw new Error(`metadata read failed: ${i.message}`);const n=r?.domains??[],s=Or(a,Rr(r?.function_tags),Xr);if(s.length>0)return xa(oa($r(s),Vr));if(n.length>0){const e=new Set(n.map(Xr).filter(e=>e.length>0)),t=a.filter(t=>!e.has(t));if(t.length>0)return xa(oa(`Unknown domain${t.length>1?"s":""}: ${t.join(", ")}. Registered: ${n.join(", ")}. Add new domains via Taxonomy Management in the ATOMS web app first.`))}}let n;if(e.fields&&Object.keys(e.fields).length>0){const{getProjectFields:r,validateProjectFieldValuesForWrite:a}=await Promise.resolve().then(()=>(Ts(),ys)),i=await r(t,e.project_id),s=await a(t,e.project_id,i,e.fields);if(s.error)return xa(oa(s.error));n=s.fields}if(void 0!==e.req_type){const t=Mi(e.req_type,e.type);if(t)return xa(oa(t))}const s=await nn(t,e.project_id,e.type),o=(new Date).toISOString(),c={id:s,type:e.type,title:e.title,summary:e.summary,body:e.body,...e.req_type?{req_type:e.req_type}:{},tags:{domains:a,level:i??""},ownership:{primary:null,additional:[]},relationships:{parents:e.parent_ids??[],children:[],related:[],verifies:[],verified_by:[]},links:[],...n?{fields:n}:{},metadata:{created_at:o,created_by:r,updated_at:o,updated_by:r}},{error:l}=await t.rpc("save_item_with_revision",{p_item_id:s,p_project_id:e.project_id,p_type:e.type,p_title:e.title,p_data:c,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null});if(l)throw new Error(l.message);if(i&&await ns(t,e.project_id,i),e.parent_ids&&e.parent_ids.length>0)for(const a of e.parent_ids){const{error:i}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:s,p_to_id:a,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"});i&&process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${a}: ${i.message}\n`)}return await t.from("change_history").insert({item_id:s,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:c,actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===e.echo?Aa(ea({id:s,type:e.type})):Aa(ea({id:s,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",...e.req_type?{req_type:e.req_type}:{},domains:a,level:i??"",project_id:e.project_id}))}catch(e){return xa(ya(e))}}E(Hs,{createItemHandler:()=>Ds});var Cs=x({"src/tools/create-item.ts"(){Ya(),sn(),Nl(),Oa(),us(),Tr(),Di()}});function Ps(e,t){const r=function(e){return`SG-${e}`}(t);return{id:e,outcome:"captured_as_change",change:{id:r,sg_number:t,status:"open"},message:`Captured as change ${r}, awaiting approval. This requirement stays at its approved revision until a human approver approves the change; no MCP tool can approve, dismiss, or apply it.`}}function Us(e){return{id:e,outcome:"under_review",message:"This requirement is under change control. Your edit was submitted; if it changed the requirement's meaning it is now a change awaiting a human approver, otherwise it wrote through live. Reload the item to confirm. No MCP tool can approve, dismiss, or apply a change."}}var Ns=x({"src/core/change-control.ts"(){}}),Ls={};async function Fs(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=async(a,i,n,s)=>{const o=await Ki(t,e.project_id,a);if(!o)return{updated_fields:[],error:`Item "${a}" not found`};const c="approved"===o.approval_state;if(void 0!==i.status&&function(e){const t=e.data?.runs;return"test-case"===e.type&&Array.isArray(t)&&t.length>0}(o))return{updated_fields:[],error:Oi(a)};void 0!==i.title&&(i.title=ja(i.title)),void 0!==i.body&&(i.body=ja(i.body)),void 0!==i.summary&&(i.summary=ja(i.summary)),void 0!==i.level&&(i.level=ja(i.level)),void 0!==i.domains&&(i.domains=i.domains.map(e=>ja(e)));const l=void 0!==i.domains?i.domains.map(Xr).filter(e=>e.length>0):void 0,d=void 0!==i.level?Xr(i.level):void 0;if(void 0!==l&&l.length>0){const{data:r,error:a}=await t.from("metadata").select("domains, function_tags").eq("project_id",e.project_id).maybeSingle();if(a)throw new Error(`metadata read failed: ${a.message}`);const i=r?.domains??[],n=Or(l,Rr(r?.function_tags),Xr);if(n.length>0)return{updated_fields:[],error:$r(n)};if(i.length>0){const e=new Set(i.map(Xr).filter(e=>e.length>0)),t=l.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const p={...o.data},u={...o.data},m=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==i.title&&_(o.data.title,i.title)&&(u.title=i.title,m.push("title")),void 0!==i.body&&_(o.data.body,i.body)&&(u.body=i.body,m.push("body")),void 0!==i.summary&&_(o.data.summary,i.summary)&&(u.summary=i.summary,m.push("summary")),void 0!==l&&_(o.data.tags?.domains??[],l)&&(u.tags={...u.tags,domains:l},m.push("domains")),void 0!==d&&_(o.data.tags?.level,d)&&(u.tags={...u.tags,level:d},m.push("level")),void 0!==i.status&&_(o.data.status,i.status)&&(u.status=i.status,m.push("status")),void 0!==i.req_type){const e=Mi(i.req_type,o.type);if(e)return{updated_fields:[],error:e};_(o.data.req_type,i.req_type)&&(u.req_type=i.req_type,m.push("req_type"))}if(void 0!==i.steps&&_(o.data.steps,i.steps)&&(u.steps=i.steps,m.push("steps")),void 0!==i.params&&_(o.data.params,i.params)&&(u.params=i.params,m.push("params")),void 0!==i.fields&&Object.keys(i.fields).length>0){const{getProjectFields:r,validateProjectFieldValuesForWrite:a,canonicalizeFieldKeys:n}=await Promise.resolve().then(()=>(Ts(),ys)),s=await r(t,e.project_id),c=await a(t,e.project_id,s,i.fields,o.data.fields);if(c.error)return{updated_fields:[],error:c.error};const l=n(s,o.data.fields??{});for(const[e,t]of Object.entries({...n(s,i.fields),...c.fields??{}}))""===t?delete l[e]:l[e]=t;_(o.data.fields??{},l)&&(u.fields=l,m.push("fields"))}if(0===m.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};u.metadata={...u.metadata,updated_at:(new Date).toISOString(),updated_by:r};const f=i.title??o.title,{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:a,p_project_id:e.project_id,p_type:o.type,p_title:f,p_data:u,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:i.expected_updated_at??o.updated_at});if(g)return{updated_fields:[],error:g};if(!h)return{updated_fields:[],error:`Update silently failed for "${a}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};m.includes("level")&&d&&await ns(t,e.project_id,d);const y={item_id:a,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:p,new_data:u,actor:Pl(),session_id:Cl()};if(n&&(y.batch_id=n),s&&(y.reason=s),await t.from("change_history").insert(y).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),c&&function(e){return e.some(e=>"title"===e||"body"===e||"type"===e)}(m)){const r=await async function(e,t,r){const{data:a,error:i}=await e.from("item_suggestions").select("sg_number").eq("project_id",t).eq("item_id",r).eq("status","open").maybeSingle();return i||!a?null:"number"==typeof a.sg_number?a.sg_number:null}(t,e.project_id,a);return null!==r?{updated_fields:m,updatedData:u,itemType:o.type,capturedSg:r}:{updated_fields:m,updatedData:u,itemType:o.type,capturedUnknown:!0}}return{updated_fields:m,updatedData:u,itemType:o.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),r=!0===e.continue_on_error,i=[],n=[];for(const s of e.updates){const{updated_fields:o,capturedSg:c,capturedUnknown:l,error:d}=await a(s.item_id,s,t,e.reason);if(d){if(wa(d))return xa(ya(d));if(!r){const e=d instanceof Error?d.message:String("object"==typeof d&&d&&"message"in d?d.message??"":d);return xa(oa(`Batch stopped at "${s.item_id}": ${e}. ${i.length} item(s) already updated.`,e.includes("Function-flagged tag")?Vr:void 0))}n.push({item_id:s.item_id,error:String(d)})}else void 0!==c?i.push(Ps(s.item_id,c)):l?i.push(Us(s.item_id)):i.push({id:s.item_id,updated_fields:o})}return Aa(ea({batch_id:t,updated:i.length,results:!1===e.echo?void 0:i,errors:n}))}if(!e.item_id)return xa(oa("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:i,updatedData:n,itemType:s,capturedSg:o,capturedUnknown:c,error:l}=await a(e.item_id,{title:e.title,body:e.body,summary:e.summary,domains:e.domains,level:e.level,status:e.status,req_type:e.req_type,fields:e.fields,steps:e.steps,params:e.params,expected_updated_at:e.expected_updated_at},void 0,e.reason);if(l){const t=l instanceof Error?l.message:String("object"==typeof l&&l&&"message"in l?l.message??"":l);return t.includes("not found")?xa(aa("Item",e.item_id)):t.includes("Unknown domain")||t.includes("Unknown field")||t.includes("Function-flagged tag")||t.includes("req_type")||function(e){return e.includes(bi)}(t)?xa(oa(t,t.includes("Function-flagged tag")?Vr:void 0)):ma(t)||wa(l)?xa(ya(l)):xa(va(t))}if(void 0!==o)return Aa(ea(Ps(e.item_id,o)));if(c)return Aa(ea(Us(e.item_id)));if(!1===e.echo)return Aa(ea({id:e.item_id,updated_fields:i}));const d=n??{};return Aa(ea({id:e.item_id,type:s,title:d.title??"",summary:d.summary??"",body:d.body??"",domains:d.tags?.domains??[],level:d.tags?.level??"",...d.req_type?{req_type:d.req_type}:{},updated_fields:i}))}catch(e){return xa(ya(e))}}E(Ls,{updateItemHandler:()=>Fs});var Ws,Vs=x({"src/tools/update-item.ts"(){Ya(),sn(),Nl(),Di(),zi(),Oa(),us(),Ns(),Tr()}}),Bs={};async function Js(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=await async function(e,t,r){const{data:a,error:i}=await e.from("items").select("*").eq("id",r).eq("project_id",t).maybeSingle();if(i)throw new Error(i.message);return a}(t,e.project_id,e.item_id);if(!a)return xa(aa("Item",e.item_id));if(a.deleted_at)return xa(oa(`Item ${e.item_id} is already deleted`));if(Yn(Ws)){const t={tool:Ws,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const r=Kn(t);return Aa(ea({status:"confirmation_required",preview:{id:e.item_id,title:a.title,type:a.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=Zn(e.confirmation_token,t);if(!r.valid)return xa(oa(`confirmation_token rejected: ${r.reason}`))}const{error:i}=await t.rpc("soft_delete_item_with_revision",{p_item_id:e.item_id,p_project_id:e.project_id,p_user_id:r,p_expected_updated_at:a.updated_at,p_event_source:"mcp",p_actor:Pl(),p_session_id:Cl()});if(i)throw new Error(i.message);const n=Fe(a.data);if(n){const a=await Ki(t,e.project_id,n);if(a){const{revoked:i,parentProps:n}=We(a.data);if(i){const i={...a.data,analysis_props:n},{error:s}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:i,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});s&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${a.id}': ${s.message}\n`)}}}return Aa(ea({id:e.item_id,title:a.title,type:a.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return xa(ya(e))}}E(Bs,{deleteItemHandler:()=>Js});var Qs=x({"src/tools/delete-item.ts"(){Ya(),sn(),Nl(),Ut(),ts(),Oa(),Ws="atoms_delete_item"}}),Gs={};async function Ys(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const{data:a,error:i}=await t.from("items").select("*").eq("id",e.item_id).eq("project_id",e.project_id).maybeSingle();if(i)throw new Error(i.message);if(!a)return xa(aa("Item",e.item_id));if(!a.deleted_at)return xa(ra(`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:n}=await t.rpc("save_item_with_revision",{p_item_id:e.item_id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:a.data,p_user_id:r,p_event_source:"restore",p_event_session_id:Cl()??null,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:a.updated_at});if(n)throw new Error(n.message);const{error:s}=await t.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:e.project_id,p_item_id:e.item_id});if(s)throw new Error(`Relationship repair failed: ${s.message}`);const o=Fe(a.data);if(o){const a=await Ki(t,e.project_id,o);if(a){const{revoked:i,parentProps:n}=We(a.data);if(i){const i={...a.data,analysis_props:n},{error:s}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:i,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});s&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${a.id}': ${s.message}\n`)}}}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:a.data,actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Aa(ea({id:e.item_id,title:a.title,type:a.type,restored:!0,message:`Item ${e.item_id} restored successfully.`}))}catch(e){return xa(ya(e))}}E(Gs,{restoreItemHandler:()=>Ys});var Ks,Zs,Xs=x({"src/tools/restore-item.ts"(){Ya(),sn(),Nl(),Ut(),Oa()}}),eo={};function to(e,t,r){const[a,i]="affects"===r?[e,t]:[t,e];return a.startsWith(Ks)&&i.startsWith(Zs)?null:`affects/affected_by links a security risk analysis row (${Ks}n) to an ISO 14971 risk row (${Zs}n) only: "${e}" -> "${t}" is not that pair.`}async function ro(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=async(a,i,n)=>{const s=await Ki(t,e.project_id,a.from_id);if(!s)throw new Error(`Item "${a.from_id}" not found`);const o=await Ki(t,e.project_id,a.to_id);if(!o)throw new Error(`Item "${a.to_id}" not found`);const{error:c}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:a.from_id,p_to_id:a.to_id,p_type:a.type,p_action:a.action,p_user_id:r,p_event_source:"mcp",p_expected_from_updated_at:a.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:a.expected_to_updated_at??o.updated_at});if(c)throw new Error(c.message);if("affects"===a.type||"affected_by"===a.type)for(const a of[s,o]){const i=Fe(a.data);if(!i)continue;const n=await Ki(t,e.project_id,i);if(!n)continue;const{revoked:s,parentProps:o}=We(n.data);if(!s)continue;const c={...n.data,analysis_props:o},{error:l}=await t.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:e.project_id,p_type:n.type,p_title:n.title,p_data:c,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at});l&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${n.id}': ${l.message}\n`)}const l={item_id:a.from_id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:null,new_data:{relationship_change:{action:a.action,type:a.type,from:a.from_id,to:a.to_id}},actor:Pl(),session_id:Cl()};i&&(l.batch_id=i),n&&(l.reason=n),await t.from("change_history").insert(l).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 xa(oa(`Self-reference in batch: "${t.from_id}"`));if("affects"===t.type||"affected_by"===t.type){const e=to(t.from_id,t.to_id,t.type);if(e)return xa(oa(e))}}const r=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],{data:i}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",r),n=new Set((i??[]).map(e=>e.id)),s=r.filter(e=>!n.has(e));if(s.length>0)return xa(aa("Items",s.join(", ")));const{data:o}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),c=new Map;for(const e of o??[])"parent"===e.type&&(c.has(e.from_id)||c.set(e.from_id,new Set),c.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?c.get(e)?.delete(r):(c.has(e)||c.set(e,new Set),c.get(e).add(r))}const l=0,d=1,p=2,u=new Map,m=new Set;for(const[e,t]of c){m.add(e);for(const e of t)m.add(e)}const _=e=>{if((u.get(e)??l)!==l)return null;const t=[],r=[],a=e=>{u.set(e,d),r.push(e),t.push({node:e,parents:[...c.get(e)??[]],idx:0})};for(a(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){u.set(e.node,p),r.pop(),t.pop();continue}const i=e.parents[e.idx];e.idx++;const n=u.get(i)??l;if(n===d){const e=r.indexOf(i);return[...r.slice(e),i]}n!==p&&a(i)}return null};for(const e of m){const t=_(e);if(t)return xa(oa(`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),y=[...h,...g],w=[],v=e=>`${e.action} ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`;for(const t of y){try{await a(t,f,e.reason)}catch(e){const r=ya(e);return xa({...r,message:`${r.message}\n\nThis batch is not atomic: its operations are applied one at a time. ${w.length} of ${y.length} operation(s) committed before this one failed and were NOT rolled back (batch ${f}). Committed: ${w.length?w.map(v).join("; "):"none"}. Failed: ${v(t)}.`,next_steps:[`Do not re-send the whole batch: the ${w.length} committed operation(s) would be applied again.`,"Reconcile from the committed list, then retry only the failed and any remaining operations.",...r.next_steps??[]]})}w.push(t)}return Aa(ea({batch_id:f,processed:e.operations.length,operations:!1===e.echo?void 0:e.operations}))}if(!(e.from_id&&e.to_id&&e.type&&e.action))return xa(oa("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."));if(e.from_id===e.to_id)return xa(oa("Cannot create a relationship between an item and itself"));if("affects"===e.type||"affected_by"===e.type){const t=to(e.from_id,e.to_id,e.type);if(t)return xa(oa(t))}return await a({action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type,expected_from_updated_at:e.expected_from_updated_at,expected_to_updated_at:e.expected_to_updated_at},void 0,e.reason),!1===e.echo?Aa(ea({action:e.action,from_id:e.from_id,to_id:e.to_id})):Aa(ea({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}`}))}catch(e){return xa(ya(e))}}E(eo,{linkItemsHandler:()=>ro});var ao=x({"src/tools/link-items.ts"(){Ya(),sn(),Nl(),Tr(),Ut(),Oa(),Ks=`${ht.security_tir57}-`,Zs=`${ht.hazard_iso14971}-`}}),io=x({"src/core/bulk-parent-links.ts"(){}}),no={};function so(e){return new Set(["22023","23503","23505","23514"]).has(e.code??"")}async function oo(e){try{if(!e.items||0===e.items.length)return xa(oa("items array must contain at least 1 item"));if(e.items.length>100)return xa(oa(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=await async function(e,t,r){const{data:a,error:i}=await e.from("metadata").select("domains, function_tags").eq("project_id",t).maybeSingle();if(i)throw new Error(`metadata read failed: ${i.message}`);const n=a?.domains??[],s=Rr(a?.function_tags),o=n.length>0?new Set(n.map(Xr).filter(e=>e.length>0)):null,c=es(n.map(Xr).filter(e=>e.length>0).sort()),l=[],d=new Set,p={};for(let e=0;e<r.length;e++){const t=r[e];p[t.type]=(p[t.type]??0)+1;const a=(t.domains??[]).map(Xr).filter(e=>e.length>0);if(0===a.length)continue;const i=Or(a,s,Xr);if(i.length>0){d.add(e),l.push({index:e,title:t.title,error:$r(i)});continue}if(!o)continue;const c=a.filter(e=>!o.has(e));c.length>0&&(d.add(e),l.push({index:e,title:t.title,error:`Unknown domain${c.length>1?"s":""}: ${c.join(", ")}. Registered: ${n.join(", ")}.`}))}return{registeredDomains:n,registeredDomainHash:c,invalidDomainIndexes:d,errors:l,typeBreakdown:p}}(t,e.project_id,e.items);if(Yn("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:es({items:e.items,registered_domain_hash:a.registeredDomainHash})};if(!e.confirmation_token){const r=Kn(t);return Aa(ea({status:"confirmation_required",preview:{total_items:e.items.length,by_type:a.typeBreakdown,sample_titles:e.items.slice(0,5).map(e=>e.title),would_fail:a.errors.length>0,errors:a.errors,registered_domain_hash:a.registeredDomainHash},confirmation_token:r.token,expires_at:r.expires_at,expires_in_seconds:r.expires_in_seconds,message:`Re-call atoms_bulk_import with the same project_id, items array, and confirmation_token within ${r.expires_in_seconds}s to execute. Changing items or project domains will invalidate the token.`}))}const r=Zn(e.confirmation_token,t);if(!r.valid)return xa(oa(`confirmation_token rejected: ${r.reason}`))}const i=(new Date).toISOString(),n=Cl(),s=[],o=[...a.errors],c=[],l=new Map,d=async r=>{let a=l.get(r);if(!a){const i=await nn(t,e.project_id,r),n=/^([A-Z]+)-(\d+)$/.exec(i);if(!n)throw new Error(`Unexpected item id format from next_item_id: ${i}`);a={prefix:n[1],next:Number(n[2])},l.set(r,a)}const i=`${a.prefix}-${String(a.next).padStart(3,"0")}`;return a.next+=1,i};for(let t=0;t<e.items.length;t++){const r=e.items[t];if(a.invalidDomainIndexes.has(t))continue;const i=(r.domains??[]).map(Xr).filter(e=>e.length>0),n=void 0!==r.level?Xr(r.level):void 0;try{const e=await d(r.type);c.push({itemId:e,input:r,sanitizedDomains:i,sanitizedLevel:n,index:t})}catch(e){o.push({index:t,title:r.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===c.length)return Aa(ea({created:0,items:[],errors:o}));const p=[],u=new Map;for(const{itemId:t,input:a,sanitizedDomains:n,sanitizedLevel:s}of c){const o={id:t,type:a.type,title:a.title,summary:a.summary,body:a.body,tags:{domains:n,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:a.parent_id?[a.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:i,created_by:r,updated_at:i,updated_by:r}};u.set(t,o),p.push({id:t,project_id:e.project_id,type:a.type,title:a.title,data:o,created_by:r,updated_by:r})}const m=p.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:m,p_user_id:r,p_event_source:"mcp"});if(_&&so(_))for(const{itemId:a,input:i,index:l}of c){const c=p.find(e=>e.id===a);if(!c)continue;const{error:d}=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:r,p_event_source:"mcp",p_event_session_id:n,p_diff_summary:null});d?o.push({index:l,title:i.title,error:d.message}):s.push({id:a,title:i.title,type:i.type})}else{if(_)throw _;for(const{itemId:e,input:t}of c)s.push({id:e,title:t.title,type:t.type})}const f=c.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:t,input:r})=>({from_id:t,to_id:r.parent_id,type:"parent",project_id:e.project_id}));await async function(e){for(const t of e.links){const{error:r}=await e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:t.from,p_to_id:t.to,p_type:"parent",p_action:"add",p_user_id:e.userId,p_event_source:"mcp"});r&&e.warn(`bulk parent link sync failed for ${t.to}: ${r.message??"unknown error"}`)}}({client:t,projectId:e.project_id,links:f.map(e=>({from:e.from_id,to:e.to_id})),userId:r,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const h=s.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:u.get(t.id)??null,actor:Pl(),session_id:n}));h.length>0&&await t.from("change_history").insert(h).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const g=new Set(s.map(e=>e.id)),y=new Set(c.filter(({itemId:e,sanitizedLevel:t})=>t&&g.has(e)).map(({sanitizedLevel:e})=>e));for(const r of y)await ns(t,e.project_id,r);return Aa(ea({created:s.length,items:s,errors:o.length>0?o:[],project_id:e.project_id}))}catch(e){return xa(ya(e))}}E(no,{bulkImportHandler:()=>oo,canRetryBulkImportPerItem:()=>so});var co=x({"src/tools/bulk-import.ts"(){Ya(),sn(),Nl(),ts(),Oa(),io(),us(),Tr()}}),lo={};async function po(e){try{const t=await Ua(),r=Wa(),a=Va();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const i=await Ki(t,e.project_id,e.item_id);if(!i)return xa(aa("Item",e.item_id));if("test-case"!==i.type)return xa(oa(`Item '${e.item_id}' is a ${i.type}, not a test-case`));const n=(e.asset??"").trim(),{data:s,error:o}=await t.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:a||r,p_actor_user_id:r,p_results:[{result:e.result,note:e.note,asset:n||void 0,point:e.point,release_id:e.release_id,build:e.build,environment:e.environment,tooling:e.tooling,steps_rev:e.steps_rev,step_results:e.step_results}]});if(o)throw new Error(o.message);const c=Array.isArray(s)?s[0]:s?.[0],l="string"==typeof c?.run_at?c.run_at:null;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:l,note:e.note,asset:n||null},actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const d=n?` (asset: ${n})`:"";return Aa(ea({item_id:e.item_id,result:e.result,run_at:l,run_by:a||r,note:e.note??null,asset:n||null,asset_id:c?.asset_id??null,asset_created:c?.asset_created??!1,message:`Test result '${e.result}' recorded for ${e.item_id}${d}`}))}catch(e){return xa(ya(e))}}E(lo,{recordTestResultHandler:()=>po});var uo=x({"src/tools/record-test-result.ts"(){Ya(),sn(),Nl(),Oa()}}),mo={};async function _o(e){try{const r=await Ua(),a=Wa(),i=Va();if(!Array.isArray(e.results)||0===e.results.length)return xa(oa("results must be a non-empty array"));if(e.results.length>100)return xa(oa(`results must have at most 100 entries (got ${e.results.length})`));try{await Ba(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const n=await Ki(r,e.project_id,e.item_id);if(!n)return xa(aa("Item",e.item_id));if("test-case"!==n.type)return xa(oa(`Item '${e.item_id}' is a ${n.type}, not a test-case`));const{data:s,error:o}=await r.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:i||a,p_actor_user_id:a,p_results:e.results});if(o)throw new Error(o.message);r.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:a,event_type:"test_result_recorded",old_data:null,new_data:{bulk:!0,count:e.results.length,results:s},actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const c=function(e){const t=[];return e.forEach((e,r)=>{e&&void 0!==e.date&&null!==e.date&&t.push(r)}),t}(e.results);return Aa(ea({item_id:e.item_id,count:e.results.length,results:s,message:`Recorded ${e.results.length} test results for ${e.item_id}`,...c.length>0?{warning:(t=c,`date was ignored on ${t.length} ${1===t.length?"entry":"entries"} (results[${t.join(", ")}]): every run is stamped with server time when it is recorded, never a caller-supplied date. A batch is stored newest-first, the last entry submitted being the newest run. Read each stored time from results[].run_at.`),ignored_date_entries:c}:{}}))}catch(e){return xa(ya(e))}var t}E(mo,{recordTestResultsBulkHandler:()=>_o});var fo,ho,go,yo,wo=x({"src/tools/record-test-results-bulk.ts"(){Ya(),sn(),Nl(),Oa(),zi()}});function vo(e){return Math.min(Math.max(e??5,1),10)}var bo=x({"src/core/trace-graph.ts"(){fo=200,ho=new Set(["parent","verifies","mitigated_by"]),go=new Set(["child","verified_by","mitigates"]),yo={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"}}}),jo={};async function ko(e){try{const t=vo(e.depth),r=await Ua(),a=await Ki(r,e.project_id,e.item_id);if(!a)return xa(aa("Item",e.item_id));const{data:i,error:n}=await r.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(n)throw new Error(n.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 c=an(i??[],s??[]);return Aa(ea(function(e){const t=vo(e.depth),r=e.relationshipTypes?.length?new Set(e.relationshipTypes):null,a=new Map(e.items.map(e=>[e.id,e]));a.has(e.rootItemId)||a.set(e.rootItemId,e.rootItem);const i=new Map,n=(e,t,r)=>{i.has(e)||i.set(e,[]),i.get(e).push({neighbor:t,relType:r})};for(const t of e.relationships){const a=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(!ho.has(a)||r&&!r.has(a)||n(t.from_id,t.to_id,a),go.has(a))){const e=yo[a]??a;r&&!r.has(e)||n(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!go.has(a)||r&&!r.has(a)||n(t.from_id,t.to_id,a),ho.has(a))){const e=yo[a]??a;r&&!r.has(e)||n(t.to_id,t.from_id,e)}"related"!==a||r&&!r.has("related")||(n(t.from_id,t.to_id,"related"),n(t.to_id,t.from_id,"related"))}const s=new Set([e.rootItemId]),o=[],c=[],l=[];for(const t of i.get(e.rootItemId)??[])l.push({id:t.neighbor,depth:1,relType:t.relType,from:e.rootItemId});for(;l.length>0&&o.length<fo;){const{id:e,depth:r,relType:n,from:d}=l.shift();if(s.has(e)||r>t)continue;s.add(e);const p=a.get(e);if(p&&(o.push({id:e,title:p.title,type:p.type,relationship:n,depth:r,from:d}),c.push({from:d,to:e,type:n}),r<t))for(const t of i.get(e)??[])s.has(t.neighbor)||l.push({id:t.neighbor,depth:r+1,relType:t.relType,from:e})}const d={id:e.rootItemId,title:e.rootItem.title,type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId};return{root:e.rootItemId,project_id:e.projectId,direction:e.direction,depth_limit:t,items:[d,...o],edges:c,total_count:o.length+1,...o.length>=fo?{truncated:!0,truncation_message:`Results capped at ${fo} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:a.title??e.item_id,type:a.type??"unknown"},items:i??[],relationships:c??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(jo,{traceHandler:()=>ko});var So=x({"src/tools/trace.ts"(){Ya(),sn(),bo(),Oa()}}),Ao={};async function xo(e){try{let t=(await Ua()).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:a}=await t;if(a)throw new Error(a.message);return Aa(ea({assets:r||[],total:(r||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(Ao,{listAssetsHandler:()=>xo});var Eo=x({"src/tools/assets.ts"(){Ya(),Oa()}}),Io={};async function Ro(e,t,r,a){if(r&&a)throw new Error("baseline_id and as_of are mutually exclusive");if(a)return a;if(!r)return null;const{data:i,error:n}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",r).maybeSingle();if(n)throw new Error(n.message);if(!i||i.project_id!==t||i.deleted_at)throw new Error("Baseline not found for this project");return i.snapshot_at}async function Oo(e,t,r){if(r){const{data:a,error:i}=await e.rpc("variables_at",{p_project_id:t,p_snapshot_at:r});if(i)throw new Error(i.message);return a??[]}const{data:a,error:i}=await e.from("project_variables").select("*").eq("project_id",t).order("name");if(i)throw new Error(i.message);return a??[]}async function $o(e,t,r,a){const{data:i,error:n}=await e.rpc("save_variable_with_revision",{p_project_id:t.project_id,p_name:t.name,p_value:t.value,p_unit:t.unit??null,p_description:t.description??null,p_is_signal:t.is_signal??!1,p_range_min:t.range_min??null,p_range_max:t.range_max??null,p_rate_ms:t.rate_ms??null,p_user_id:r,p_event_source:a,p_variable_id:t.id??null});if(n)throw new Error(n.message);return i}async function qo(e){try{const t=await Ua(),r=await Ro(t,e.project_id,e.baseline_id,e.as_of),a=await Oo(t,e.project_id,r),i=e.limit??50,n=e.offset??0;return Aa(ea({variables:a.slice(n,n+i),total:a.length},ta(a.length,i,n)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function zo(e){try{const t=await Ua(),r=await Ro(t,e.project_id,e.baseline_id,e.as_of),a=(await Oo(t,e.project_id,r)).find(t=>t.name===e.variable_name)??null;if(!a)return xa(aa("Variable",e.variable_name));const{data:i}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),n=`{${e.variable_name}}`,s=(i||[]).filter(e=>(e.data?.body||"").includes(n));return Aa(ea({variable:a,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")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function Mo(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(!a.data)return xa(aa("Variable",e.variable_name));const i={updated_by:r,updated_at:(new Date).toISOString()};return 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),Aa(ea({variable:await $o(t,{...a.data,...i,project_id:e.project_id,name:e.variable_name,value:i.value??a.data.value,unit:i.unit??a.data.unit,description:i.description??a.data.description},r,"mcp")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function To(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const i=e.variables.filter(e=>!a.test(e.name));if(i.length>0)return xa(oa(`Invalid variable name(s): ${i.map(e=>e.name).join(", ")}. Use letters, digits, underscores; must start with letter or underscore.`));const n=e.variables.map(e=>e.name),s=n.map(e=>e.toLowerCase()),o=n.filter((e,t)=>s.indexOf(s[t])!==t);if(o.length>0)return xa(oa(`Duplicate names in batch (case-insensitive): ${[...new Set(o)].join(", ")}`));const{data:c}=await t.from("project_variables").select("name").eq("project_id",e.project_id),l=new Set((c??[]).map(e=>e.name.toLowerCase())),d=n.filter(e=>l.has(e.toLowerCase()));if(d.length>0)return xa(oa(`Variable(s) already exist (case-insensitive): ${d.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const p=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})),u=await async function(e,t,r,a){const{data:i,error:n}=await e.rpc("bulk_save_variables_with_revisions",{p_project_id:t,p_variables:r,p_user_id:a,p_event_source:"mcp"});if(n)throw new Error(n.message);return i??[]}(t,e.project_id,p,r);return Aa(ea({batch_id:crypto.randomUUID(),created:(u??[]).length,variables:!1===e.echo?(u??[]).map(e=>({name:e.name})):u??[],message:`${(u??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`}))}if(!e.name||!e.value)return xa(oa("Provide either (name, value) for single variable or variables[] for batch."));if(!a.test(e.name))return xa(oa(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const{data:i}=await t.from("project_variables").select("name").eq("project_id",e.project_id),n=(i??[]).find(t=>t.name.toLowerCase()===e.name.toLowerCase());if(n)return xa(oa(`Variable "${n.name}" already exists in this project (names are unique regardless of case).`));const s=await $o(t,{project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null},r,"mcp");return!1===e.echo?Aa(ea({name:e.name})):Aa(ea({variable:s,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function Ho(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const{data:a}=await t.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!a)return xa(aa("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 xa(oa(`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(Yn("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const r=Kn(t);return Aa(ea({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=Zn(e.confirmation_token,t);if(!r.valid)return xa(oa(`confirmation_token rejected: ${r.reason}`))}const s=await async function(e,t,r,a){const{data:i,error:n}=await e.rpc("delete_variable_with_revision",{p_project_id:t,p_variable_id:r,p_user_id:a,p_event_source:"mcp"});if(n)throw new Error(n.message);return Boolean(i)}(t,e.project_id,a.id,r);return s?Aa(ea({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})):xa(aa("Variable",e.name))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(Io,{createVariableHandler:()=>To,deleteVariableHandler:()=>Ho,getVariableHandler:()=>zo,listVariablesHandler:()=>qo,updateVariableHandler:()=>Mo});var Do,Co=x({"src/tools/variables.ts"(){Ya(),ts(),Oa()}}),Po={};async function Uo(e,t,r,a,i){let n=0;for(;;){const{data:s,error:o}=await e.rpc("apply_domain_change",{p_project_id:t,p_old_domain:r,p_new_domain:a,p_user_id:i,p_event_source:"mcp",p_limit:Do});if(o)throw new Error(n>0?`${o.message} (${n} items were already updated and the registry is unchanged: call again to finish)`:o.message);const c="number"==typeof s?s:0;if(n+=c,c<Do)return n}}async function No(e,t){const{data:r,error:a}=await e.from("metadata").select("domains, levels, function_tags").eq("project_id",t).maybeSingle();if(a)throw new Error(`metadata read failed: ${a.message}`);return{domains:r?.domains??[],levels:r?.levels??[],functionTags:Array.isArray(r?.function_tags)?r.function_tags.filter(e=>"string"==typeof e):[]}}async function Lo(e){try{const t=await Ua(),{domains:r,functionTags:a}=await No(t,e.project_id),i=Or(r,a),n=new Set(i.map(sr)),s=new Set(a.map(sr)),o=r.filter(e=>!n.has(sr(e))),{counts:c,orphans:l}=await async function(e,t,r){const{data:a}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null),i={};for(const e of r)i[e]=0;const n={};for(const e of a??[]){const t=e.data?.tags?.domains??[];for(const e of t)n[e]=(n[e]??0)+1,e in i&&i[e]++}const s=new Set(r),o={};for(const[e,t]of Object.entries(n))s.has(e)||(o[e]=t);return{counts:i,orphans:o}}(t,e.project_id,o),d=o.map(e=>({name:e,registered:!0,item_count:c[e]??0})),p=Object.entries(l).filter(([e])=>!s.has(sr(e))).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),u=[...d,...p];return Aa(ea({domains:u,total:u.length,registered_count:d.length,unregistered_count:p.length,excluded_function_tags:i,note:p.length>0?`${p.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")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function Fo(e){try{const r=await Ua();try{await Ba(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=ja(e.name).trim().toLowerCase();if(!a)return xa(oa("Domain name cannot be empty."));const i=await No(r,e.project_id);if(null!==or(a,i.functionTags))return xa(oa(Dr(a,!0),Vr));const n=or(a,i.domains);if(null!==n)return xa(oa(Dr(n,!1),Vr));const{data:s,error:o}=await r.rpc("append_project_domain",{p_project_id:e.project_id,p_domain:a});if(o)throw new Error(o.message);if(s&&!1===s.added){const{functionTags:t}=await No(r,e.project_id);return xa(oa(Dr(a,null!==or(a,t)),Vr))}return Aa(ea({domain:{name:a},message:(t=a,`Domain "${t}" registered. You can now tag items with domains=["${t}"].`)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}var t}async function Wo(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=void 0!==e.new_name;if(a===(void 0!==e.is_function))return xa(oa(function(e){return e?"Pass either new_name (rename the domain) or is_function (flag it as a function, or unflag it back to a domain), not both. Make the two changes in separate calls.":"Pass new_name to rename the domain, or is_function to flag it as a function (true) or unflag it back to a domain (false)."}(a),Vr));if(void 0===e.new_name)return await async function(e,t,r,a,i){const n=ja(r).trim();if(!n)return xa(oa("name cannot be empty."));const{domains:s,functionTags:o}=await No(e,t),c=or(n,s),l=or(n,o);if(a){if(null!==l)return Aa(ea({domain:{name:l},is_function:!0,changed:!1,message:Cr(l)}));if(null===c){const{data:r}=await e.from("items").select("id").eq("project_id",t).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([n.toLowerCase()])).limit(1);return r&&0!==r.length?xa(oa(function(e){return`Tag "${e}" is carried by items but is not registered in this project's taxonomy, so it cannot be flagged as a function. Register it first with atoms_create_domain.`}(n.toLowerCase()),Vr)):xa(aa("Domain",n.toLowerCase()))}const r=await async function(e,t,r){const{data:a,error:i}=await e.from("items").select("id").eq("project_id",t).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([r]));if(i)throw new Error(i.message);return(a??[]).length}(e,t,c);if(i)return Aa(ea({dry_run:!0,domain:{name:c},is_function:!0,items_carrying_tag:r,message:Ur(c,r,!0)}));const{data:a,error:s}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"flag_function",p_values:[c]});if(s)throw new Error(s.message);return Array.isArray(a?.function_tags)&&null!==or(c,a.function_tags)?Aa(ea({domain:{name:c},is_function:!0,changed:!0,items_carrying_tag:r,message:Ur(c,r,!1)})):xa(aa("Domain",c.toLowerCase()))}if(null===l)return null!==c?Aa(ea({domain:{name:c},is_function:!1,changed:!1,message:Pr(c)})):xa(aa("Domain",n.toLowerCase()));const d=await async function(e,t,r){const{count:a,error:i}=await e.from("items").select("id",{count:"exact",head:!0}).eq("project_id",t).is("deleted_at",null).filter("data->analysis_props->>source_function","ilike",Ji(r));if(i)throw new Error(i.message);return"number"==typeof a?a:0}(e,t,l);if(i)return Aa(ea({dry_run:!0,domain:{name:l},is_function:!1,analysis_rows_using_function:d,message:Nr(l,d,!0)}));const{error:p}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"unflag_function",p_values:[l]});if(p)throw new Error(p.message);return Aa(ea({domain:{name:l},is_function:!1,changed:!0,analysis_rows_using_function:d,message:Nr(l,d,!1)}))}(t,e.project_id,e.name,!0===e.is_function,!0===e.dry_run);const{domains:i,functionTags:n}=await No(t,e.project_id),s=ja(e.name).trim().toLowerCase(),o=ja(e.new_name).trim().toLowerCase();if(!o)return xa(oa("new_name cannot be empty."));const c=i.includes(s);if(!c){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([s])).limit(1);if(!r||0===r.length)return xa(aa("Domain",s))}const l=function(e,t,r,a){if(null!==or(t,[e]))return null;const i=or(t,a);if(null!==i)return{kind:"function",name:i};const n=or(t,r);return null!==n?{kind:"domain",name:n}:null}(s,o,i,n);if("function"===l?.kind)return xa(function(e,t,r){const a=`atoms_update_domain (name: "${r.trim().toLowerCase()}", is_function: false)`;return{status:"error",message:`Cannot rename "${e}" to "${t}": "${r}" is a function, and a tag is a domain or a function, never both, so a domain cannot take a function's name. Choose another name, or unflag the function first with ${a}.`,next_steps:["Choose a new_name that is not already a domain or a function",`Or unflag the function first: ${a}`],details:{code:Mr,functions:[r]}}}(s,o,l.name));if("domain"===l?.kind&&c)return xa(oa(`Domain "${l.name}" already exists. Choose a different name.`));const d="domain"===l?.kind&&!c,p=d&&l?l.name:o,{data:u,error:m}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([s]));if(m)throw new Error(m.message);const _=(u??[]).length;if(e.dry_run)return Aa(ea({dry_run:!0,rename:{from:s,to:p},items_affected:_,message:d?`Dry run: "${s}" is not registered and "${p}" is, so the ${_} item${1!==_?"s":""} carrying "${s}" would be merged into the registered domain "${p}" (the registry is not changed). Call again with dry_run=false to apply.`:`Dry run: renaming "${s}" → "${o}" would update ${_} item${1!==_?"s":""}. Call again with dry_run=false to apply.`}));const f=await Uo(t,e.project_id,s,p,r);if(d)return Aa(ea({domain:{name:p},renamed_from:s,items_updated:f,message:`Domain "${s}" merged into the registered domain "${p}". ${f} item${1!==f?"s":""} updated.`}));const{error:h}=await t.rpc("mutate_project_domains",{p_project_id:e.project_id,p_action:"rename",p_values:[s,o]});if(h)throw new Error(h.message);return Aa(ea({domain:{name:o},renamed_from:s,items_updated:f,message:`Domain renamed "${s}" → "${o}". ${f} item${1!==f?"s":""} updated.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function Vo(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const{domains:a}=await No(t,e.project_id),i=ja(e.name).trim().toLowerCase(),n=a.includes(i),{data:s,error:o}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([i]));if(o)throw new Error(o.message);const c=(s??[]).length;if(!n&&0===c)return xa(aa("Domain",i));if(c>0&&!e.force)return xa(oa(function(e,t){return`Domain "${e}" is used by ${t} item${t>1?"s":""}. Use force=true to delete and strip the domain from all items, or re-tag them first.`}(i,c)));if(Yn("atoms_delete_domain")){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:i};if(!e.confirmation_token){const e=Kn(t);return Aa(ea({status:"confirmation_required",preview:{domain_name:i,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=Zn(e.confirmation_token,t);if(!r.valid)return xa(oa(`confirmation_token rejected: ${r.reason}`))}const l=c>0?await Uo(t,e.project_id,i,null,r):0,{error:d}=await t.rpc("mutate_project_domains",{p_project_id:e.project_id,p_action:"remove",p_values:[i]});if(d)throw new Error(d.message);return Aa(ea({deleted:!0,name:i,items_updated:l,message:c>0?`Domain "${i}" deleted and stripped from ${l} item${1!==l?"s":""}.`:`Domain "${i}" deleted.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(Po,{DOMAIN_CHANGE_BATCH:()=>Do,createDomainHandler:()=>Fo,deleteDomainHandler:()=>Vo,listDomainsHandler:()=>Lo,updateDomainHandler:()=>Wo});var Bo=x({"src/tools/domains.ts"(){Ya(),ts(),Oa(),Tr(),Gi(),Yr(),Do=200}}),Jo={};async function Qo(e){try{const t=await Ua(),{data:r,error:a}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle(),i=r?.name??null,n=a?.message??null,{data:s,error:o}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(o)throw new Error(o.message);const c=s??[];if(!i&&0===c.length){if(n)throw new Error(n);return xa(aa("Project",e.project_id))}const l={requirements:0,test_cases:0,notes:0},d=[],p=[];for(const e of c)if("requirement"===e.type){l.requirements++;const t=e.data?.tags?.domains??[];p.push({id:e.id,domains:t})}else"test-case"===e.type?(l.test_cases++,d.push(e.id)):"note"===e.type&&l.notes++;let u=xn([],[]);if(d.length>0){const{data:r,error:a}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(a)throw new Error(a.message);u=xn(d,r??[])}const{data:m,error:_}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(_)throw new Error(_.message);const f=an(s??[],m??[]),h=new Set;for(const e of f)"verifies"===e.type?h.add(e.to_id):"verified_by"===e.type&&h.add(e.from_id);const g=p.filter(e=>h.has(e.id)).length,y=p.length,w={covered:g,uncovered:y-g,total:y,percent:An(g,y),via_mitigation:Ni(p.map(e=>e.id),h,Pi(c,f))},v=new Map;for(const e of p){const t=e.domains.length>0?e.domains:["(untagged)"],r=h.has(e.id);for(const e of t){v.has(e)||v.set(e,{covered:0,total:0});const t=v.get(e);t.total++,r&&t.covered++}}const b=Array.from(v.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:An(t.covered,t.total)})),j=new Date;j.setDate(j.getDate()-7);const{count:k,error:S}=await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",j.toISOString());if(S)throw new Error(S.message);return Aa(ea({project_id:e.project_id,project_name:i??`Project ${e.project_id.slice(0,8)}`,counts:l,test_status:u,coverage:w,coverage_by_domain:b,recent_changes:k??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(Jo,{projectSummaryHandler:()=>Qo});var Go,Yo=x({"src/tools/project-summary.ts"(){Ya(),sn(),En(),Fi(),Oa()}}),Ko={};async function Zo(e){try{const t=await Ua();let r,a;if(e.query&&e.query.trim().length>0){const i=await rn(t,e.project_id,e.query,{type:e.type,domain:e.domain,level:e.level,limit:e.limit});r=i.items.map(e=>({id:e.id,title:e.title,type:e.type,status:Ri(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),a=i.totalCount}else{const i=await Yi(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});r=i.items.map(e=>({id:e.id,title:e.title,type:e.type,status:Ri(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),a=i.totalCount}const i=await async function(e,t){const{data:r,error:a}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(a)throw new Error(a.message);const i=new Set,n=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)i.add(t);const r=t.level;r&&n.add(r)}}return{domains:[...i].sort(),levels:[...n].sort()}}(t,e.project_id);return Aa(ea({items:r,filters:{domains:i.domains,levels:i.levels,types:Go},project_id:e.project_id},ta(a,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(Ko,{browseHandler:()=>Zo});var Xo,ec,tc,rc,ac=x({"src/tools/browse.ts"(){Ya(),sn(),Oa(),zi(),Go=["requirement","test-case","note","table"]}}),ic={};async function nc(e){try{const t=e.direction??"downstream",r=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,a=await Ua(),i=await Ki(a,e.project_id,e.item_id);if(!i)return xa(aa("Item",e.item_id));const{data:n,error:s}=await a.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:c}=await a.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(c)throw new Error(c.message);const l=new Map;for(const e of o??[])l.set(e.id,{title:e.title,type:e.type});const d=new Map,p=(e,t,r)=>{d.has(e)||d.set(e,[]),d.get(e).push({neighbor:t,relType:r})};for(const e of n??[]){const r=e.type;"upstream"!==t&&"both"!==t||(ec.includes(r)&&p(e.from_id,e.to_id,r),tc.includes(r)&&p(e.to_id,e.from_id,rc[r]??r)),"downstream"!==t&&"both"!==t||(tc.includes(r)&&p(e.from_id,e.to_id,r),ec.includes(r)&&p(e.to_id,e.from_id,rc[r]??r)),"related"===r&&(p(e.from_id,e.to_id,"related"),p(e.to_id,e.from_id,"related"))}const u=new Set;u.add(e.item_id);const m=[];let _=0;const f=[];for(const t of d.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&&m.length<Xo;){const{id:e,depth:t,path:a}=f.shift();if(u.has(e))continue;if(null!==r&&t>r)continue;u.add(e);const i=l.get(e);if(i&&(m.push({item_id:e,title:i.title,type:i.type,depth:t,relationship_path:a}),t>_&&(_=t),null===r||t<r))for(const r of d.get(e)??[])u.has(r.neighbor)||f.push({id:r.neighbor,depth:t+1,path:[...a,{from_id:e,to_id:r.neighbor,relationship_type:r.relType}]})}let h=0;if(e.include_variable_refs){const{data:t}=await a.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 a.from("project_variables").select("id, name").in("id",r),i=new Map((t??[]).map(e=>[e.id,e.name])),{data:n}=await a.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 n??[]){const r=t.item_id;if(u.has(r))continue;if(m.length>=Xo)break;u.add(r);const a=l.get(r);if(!a)continue;const n=i.get(t.variable_id)??t.variable_id;m.push({item_id:r,title:a.title,type:a.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:r,relationship_type:`variable_ref:${n}`}]}),h++}}}const g={};for(const e of m)g[e.type]=(g[e.type]??0)+1;const y=l.get(e.item_id);return Aa(ea({root:{item_id:e.item_id,title:y?.title??i.title,type:y?.type??i.type},impacted_items:m,summary:{total_impacted:m.length,by_type:g,max_depth_reached:_,...h>0?{variable_impact_count:h}:{},...m.length>=Xo?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}E(ic,{impactAnalysisHandler:()=>nc});var sc,oc,cc,lc,dc,pc,uc=x({"src/tools/impact-analysis.ts"(){Ya(),sn(),Oa(),Xo=200,ec=["parent","verifies","traces_to","allocated_from","decomposed_from"],tc=["child","verified_by","allocated_to","decomposes_to","traced_by"],rc={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"}}}),mc=x({"src/core/relationship-sync.ts"(){}});function _c(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function fc(e){return null==e?"":String(e)}function hc(e){if(null==e||""===e)return"null";if(Array.isArray(e))return 0===e.length?"null":`[${e.map(hc).join(",")}]`;if("object"==typeof e){const t=e,r=Object.keys(t).filter(e=>"null"!==hc(t[e])).sort();return 0===r.length?"null":`{${r.map(e=>`${JSON.stringify(e)}:${hc(t[e])}`).join(",")}}`}return JSON.stringify(e)}function gc(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function yc(e,t){const r=gc(e),a=gc(t),i=[],n=gc(r.analysis_props),s=gc(a.analysis_props),o=Array.from(new Set([...Object.keys(n),...Object.keys(s)])).sort();for(const e of o){if(sc.has(e))continue;const t=n[e],r=s[e];_c(t)&&_c(r)?fc(t)!==fc(r)&&i.push(`analysis_props.${e}`):hc(t)!==hc(r)&&i.push(`analysis_props.${e}`)}const c=e=>{const t=new Map;for(const[r,a]of Object.entries(e))"string"==typeof a&&t.set(r.toLowerCase(),{key:r,value:a});return t},l=c(gc(r.fields)),d=c(gc(a.fields)),p=Array.from(new Set([...l.keys(),...d.keys()])).sort();for(const e of p)if((l.get(e)?.value??"")!==(d.get(e)?.value??"")){const t=d.get(e)?.key??l.get(e)?.key??e;i.push(`fields.${t}`)}return i}function wc(e,t){for(const[r,a]of Object.entries(e))if(r.toLowerCase()===t)return"string"==typeof a?a:null;return null}function vc(e,t,r){const a=gc(e.data),i=gc(t.data),n=new Set(r),s={};for(const o of r)if("title"===o)s[o]={from:e.title??null,to:t.title??null};else if("type"===o)s[o]={from:e.type??null,to:t.type??null};else if("status"===o)s[o]={from:a.status??null,to:i.status??null};else if("tags.level"===o)s[o]={from:gc(a.tags).level??null,to:gc(i.tags).level??null};else if("tags.domains"===o)s[o]={from:gc(a.tags).domains??null,to:gc(i.tags).domains??null};else if(o.startsWith("analysis_props.")){const e=o.slice(15);s[o]={from:gc(a.analysis_props)[e]??null,to:gc(i.analysis_props)[e]??null}}else if(o.startsWith("fields.")){const e=o.slice(7).toLowerCase();s[o]={from:wc(gc(a.fields),e),to:wc(gc(i.fields),e)}}else if("data"===o){const e=Array.from(new Set([...Object.keys(a),...Object.keys(i)])).sort(),t={},r={};for(const s of e){const[e,o]=jc(s,a[s],i[s],n);hc(e)!==hc(o)&&(t[s]=e??null,r[s]=o??null)}s[o]={from:t,to:r}}else s[o]={from:null,to:null};return s}function bc(e,t){return null===e||"object"!=typeof e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).filter(([e])=>!t(e)))}function jc(e,t,r,a){if("status"===e)return a.has("status")?[null,null]:[t,r];if("tags"===e){const e=e=>"level"===e&&a.has("tags.level")||"domains"===e&&a.has("tags.domains");return[bc(t,e),bc(r,e)]}if("analysis_props"===e){const e=e=>a.has(`analysis_props.${e}`);return[bc(t,e),bc(r,e)]}if("fields"===e){const e=e=>function(e,t){const r=e.toLowerCase();for(const e of t)if(e.startsWith("fields.")&&e.slice(7).toLowerCase()===r)return!0;return!1}(e,a);return[bc(t,e),bc(r,e)]}return Array.isArray(t)&&Array.isArray(r)?function(e,t){const r={},a={},i=kc(e),n=kc(t);if(i&&n){const s=new Map(i.map((t,r)=>[t,e[r]])),o=new Map(n.map((e,r)=>[e,t[r]]));for(const e of new Set([...i,...n])){const t=s.get(e)??null,i=o.get(e)??null;hc(t)!==hc(i)&&(r[e]=t,a[e]=i)}return i.join("\n")!==n.join("\n")&&(r.order=i,a.order=n),[r,a]}for(let i=0;i<Math.max(e.length,t.length);i++)hc(e[i])!==hc(t[i])&&(r[i]=e[i]??null,a[i]=t[i]??null);return[r,a]}(t,r):[t,r]}function kc(e){const t=[];for(const r of e){const e=gc(r).id;if("string"!=typeof e||"order"===e)return null;t.push(e)}return new Set(t).size===t.length?t:null}function Sc(e){return"string"==typeof e?1:Array.isArray(e)?e.reduce((e,t)=>e+Sc(t),0):null!==e&&"object"==typeof e?Object.values(e).reduce((e,t)=>e+Sc(t),0):0}function Ac(e){const t=JSON.stringify(e,null,2),r=t.split("\n").length;return t.length+r*lc+cc*Sc(e.diff)+2}function xc(e,t,r){if("string"==typeof e){if(e.length<=t+pc)return e;r.n++;let a=t;const i=e.charCodeAt(a-1);return i>=55296&&i<=56319&&a--,`${e.slice(0,a)}... [clipped, ${e.length-a} more characters]`}return Array.isArray(e)?e.map(e=>xc(e,t,r)):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,a])=>[e,xc(a,t,r)])):e}function Ec(e,t){const r=e.diff??{};for(const a of dc){const i={n:0},n=xc(r,a,i),s={...e,diff:n,...i.n>0?{diff_clipped:!0}:{}};if(Ac(s)<=t)return s}const a={n:0},i=xc(r,dc[dc.length-1],a),n=a.n>0?{diff_clipped:!0}:{},s=Object.keys(i);let o={},c={...e,diff:o,...n,diff_omitted:s.length};for(let r=0;r<s.length;r++){const a={...o,[s[r]]:i[s[r]]},l={...e,diff:a,...n,diff_omitted:s.length-r-1};if(Ac(l)>t)break;o=a,c=l}return 0===c.diff_omitted&&delete c.diff_omitted,c}var Ic=x({"src/core/baseline-diff.ts"(){sc=new Set(["field_source","approved","approved_at","approved_by","approved_note"]),oc=2e4,cc=29,lc=6,dc=[1e3,400,160,60,20],pc=40}}),Rc={};function Oc(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):null}async function $c(e,t){const{data:r,error:a}=await e.rpc("restore_baseline_state",{p_baseline_id:t.baselineId,p_project_id:t.projectId,p_items:[],p_variables:[],p_user_id:t.userId});if(a)throw new Error(a.message);return r}async function qc(e,t,r){const{data:a,error:i}=await e.from("items").select("id, deleted_at").eq("project_id",t).eq("id",r).maybeSingle();if(i)throw new Error(i.message);if(n=a,!Boolean(n?.id&&null===n.deleted_at))return;var n;const{error:s}=await e.rpc("sync_item_relationships_from_jsonb",{p_project_id:t,p_item_id:r});if(s)throw new Error(s.message)}async function zc(e,t,r){const{data:a,error:i}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(i)return xa(va(i.message));if(!a)return xa(aa("Project",t));const{data:n,error:s}=await e.from("organizations").select("feature_flags").eq("id",a.org_id).maybeSingle();return s?xa(va(s.message)):!0!==(n?.feature_flags??{})[r]?xa(ra(`Feature '${r}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function Mc(e){try{const t=await Ua(),r=await async function(e,t){const{data:r,error:a}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, release_version, release_status").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1});if(a)throw new Error(`listBaselines: ${a.message}`);return r??[]}(t,e.project_id),a=Math.max(e.offset??0,0),i=Math.min(Math.max(e.limit??50,1),100);return Aa(ea({baselines:r.slice(a,a+i).map(e=>({id:e.id,name:e.name,description:e.description,field_definitions_snapshot:e.field_definitions_snapshot,snapshot_at:e.snapshot_at,created_at:e.created_at,created_by:e.created_by,locked:null!==e.locked_at,locked_at:e.locked_at,release_version:e.release_version,release_status:e.release_status})),total:r.length,offset:a,limit:i},ta(r.length,i,a)))}catch(e){return Oc(e)??xa(va(e instanceof Error?e.message:String(e)))}}async function Tc(e){try{const t=await Ua(),r=await zc(t,e.project_id,"baselines_enabled");if(r)return r;const{data:a,error:i}=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 i?"23505"===i.code?xa(ra(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):xa(va(i.message)):Aa(ea({id:a.id,name:a.name,description:a.description,field_definitions_snapshot:a.field_definitions_snapshot,snapshot_at:a.snapshot_at,created_at:a.created_at,locked:!1}))}catch(e){return Oc(e)??xa(va(e instanceof Error?e.message:String(e)))}}async function Hc(e){try{const t=await Ua(),r=await Xi(t,e.baseline_id);if(!r)return xa(aa("Baseline",e.baseline_id));const a=await zc(t,r.project_id,"baselines_enabled");if(a)return a;if(null!==r.locked_at)return xa(ra("Baseline is already locked",["Locks are one-way; nothing to do"]));const{data:i}=await t.from("projects").select("org_id").eq("id",r.project_id).maybeSingle();if(!i)return xa(aa("Project",r.project_id));const{data:n}=await t.auth.getUser(),s=n?.user?.id;if(!s)return xa(ca());const{data:o}=await t.from("org_members").select("role").eq("user_id",s).eq("org_id",i.org_id).maybeSingle();if(!o||"admin"!==o.role)return xa(ra("Only admins can lock baselines",["Ask an org admin to lock this baseline"]));const{data:c,error:l}=await t.from("baselines").update({locked_at:(new Date).toISOString(),locked_by:s}).eq("id",e.baseline_id).select().single();return l?xa(va(l.message)):Aa(ea({id:c.id,locked_at:c.locked_at,locked_by:c.locked_by}))}catch(e){return Oc(e)??xa(va(e instanceof Error?e.message:String(e)))}}async function Dc(e){try{const t=await Ua(),[r,a]=await Promise.all([Xi(t,e.baseline_a_id),Xi(t,e.baseline_b_id)]);if(!r||!a)return xa(aa("Baseline","one of the baseline_ids"));if(r.project_id!==a.project_id)return xa(ra("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[i,n]=await Promise.all([tn(t,r.project_id,r.snapshot_at),tn(t,a.project_id,a.snapshot_at)]),s=new Map(i.map(e=>[e.id,e])),o=new Map(n.map(e=>[e.id,e])),c=Array.from(new Set([...s.keys(),...o.keys()])).sort(),l=[];let d=0,p=0,u=0;for(const e of c){const t=s.get(e),r=o.get(e);if(!t&&r)d++,l.push({item_id:e,change_type:"added"});else if(t&&!r)p++,l.push({item_id:e,change_type:"removed"});else if(t&&r){const a=[];t.title!==r.title&&a.push("title"),t.type!==r.type&&a.push("type");if(JSON.stringify(t.data??{})!==JSON.stringify(r.data??{})){a.push("data");const e=t.data??{},i=r.data??{};(e.status??null)!==(i.status??null)&&a.push("status"),(e.tags?.level??null)!==(i.tags?.level??null)&&a.push("tags.level"),JSON.stringify(e.tags?.domains??[])!==JSON.stringify(i.tags?.domains??[])&&a.push("tags.domains"),a.push(...yc(t.data,r.data))}a.length>0&&(u++,l.push({item_id:e,change_type:"modified",fields_changed:a}))}}const m=Math.max(e.offset??0,0),_=Math.min(Math.max(e.limit??50,1),200);let f=l.slice(m,m+_);const h={offset:m,limit:_,total:l.length};if(!0===e.detail){const e=function(e,t,r,a,i={}){const n=i.budget??oc,s=i.diffOf??vc,o=[];let c=0,l=!1,d=!1;for(const a of e){let e=a;if("modified"===a.change_type&&a.fields_changed){const i=t.get(a.item_id),n=r.get(a.item_id);i&&n&&(e={...a,diff:s(i,n,a.fields_changed)})}let i=Ac(e);if(c+i>n){if(o.length>0)break;e=Ec(e,n),i=Ac(e)}e.diff_clipped&&(l=!0),e.diff_omitted&&(d=!0),o.push(e),c+=i}if(o.length===e.length&&!l&&!d)return{items:o,pageInfo:{}};const p={returned:o.length,truncated:!0},u=[];return o.length<e.length&&(p.next_offset=a+o.length,u.push(`Response bounded to ${n} characters of items: returned ${o.length} of the ${e.length} items on this page. Call again with offset=${p.next_offset} for the rest, or omit detail to get only the names of the changed fields.`)),l&&u.push('Long values in an item were clipped to fit, each marked "[clipped, N more characters]".'),d&&u.push("diff_omitted counts the changed fields of an item whose values did not fit; their names are still in fields_changed."),(l||d)&&u.push("Compare the two snapshots in the app to see every value in full."),p.truncation_message=u.join(" "),{items:o,pageInfo:p}}(f,s,o,m);f=e.items,Object.assign(h,e.pageInfo)}return Aa(ea({summary:{added:d,removed:p,modified:u,total_compared:c.length},items:f,page_info:h,baselines:{a:{id:r.id,name:r.name,snapshot_at:r.snapshot_at},b:{id:a.id,name:a.name,snapshot_at:a.snapshot_at}}}))}catch(e){return Oc(e)??xa(va(e instanceof Error?e.message:String(e)))}}async function Cc(e){try{const t=await Ua(),r=await Xi(t,e.baseline_id);if(!r)return xa(aa("Baseline",e.baseline_id));const a=await zc(t,r.project_id,"baselines_enabled");if(a)return a;const{data:i}=await t.from("projects").select("org_id").eq("id",r.project_id).maybeSingle();if(!i)return xa(aa("Project",r.project_id));const{data:n}=await t.auth.getUser(),s=n?.user?.id;if(!s)return xa(ca());const{data:o}=await t.from("org_members").select("role").eq("user_id",s).eq("org_id",i.org_id).maybeSingle();if(!o||"admin"!==o.role)return xa(ra("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const{data:c}=await t.rpc("cc_project_is_controlled",{p_project_id:r.project_id});if(!0===c)return xa(ra("Change control is on for this project. Release review before restoring a baseline.",["Release review on the project, then run the restore"]));const l=await tn(t,r.project_id,r.snapshot_at),d=l.map(e=>e.id),{data:p,error:u}=d.length>0?await t.from("items").select("*").eq("project_id",r.project_id).in("id",d):{data:[],error:null};if(u)return xa(va(u.message));const m=function(e,t){const r=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=r.get(e.id),a=[];var i,n;return t?(null!==t.deleted_at&&a.push("deleted_at"),t.type!==e.type&&a.push("type"),t.title!==e.title&&a.push("title"),i=t.data,n=e.data,JSON.stringify(i??{})!==JSON.stringify(n??{})&&a.push("data")):a.push("missing"),0===a.length?[]:[{id:e.id,type:e.type,title:e.title,data:e.data??{},diff_summary:{changed_fields:a,restored:!0},oldData:t?.data??null}]})}(l,p??[]),{data:_,error:f}=await t.rpc("variables_at",{p_project_id:r.project_id,p_snapshot_at:r.snapshot_at});if(f)return xa(va(f.message));const h=_??[];if(!0!==e.confirm)return Aa(ea({preview:!0,items_to_restore:m.length,variables_to_restore:h.length,field_definitions_to_restore:r.field_definitions_snapshot?.length??null}));const g=await $c(t,{baselineId:r.id,projectId:r.project_id,userId:s});return Aa(ea({ok:!0,items_restored:g.items_restored,variables_restored:g.variables_restored,field_definitions_restored:g.field_definitions.length}))}catch(e){return Oc(e)??xa(va(e instanceof Error?e.message:String(e)))}}E(Rc,{createBaselineHandler:()=>Tc,diffBaselinesHandler:()=>Dc,listBaselinesHandler:()=>Mc,lockBaselineHandler:()=>Hc,restoreBaselineHandler:()=>Cc,restoreBaselineStateAtomically:()=>$c,syncRestoredItemRelationships:()=>qc});var Pc,Uc,Nc,Lc,Fc=x({"src/tools/baselines.ts"(){Ya(),Nl(),Oa(),sn(),mc(),Ic()}});function Wc(e){return"string"==typeof e}function Vc(e,t){if(null==e)return{ok:!0,value:{state:"draft",by:null,on:null,count:0,history:[]}};if("object"!=typeof e||Array.isArray(e))return{ok:!1,error:`${t}.acceptance must be an object`};const r=e;return{ok:!0,value:{state:"accepted"===r.state?"accepted":"draft",by:Wc(r.by)?r.by:null,on:Wc(r.on)?r.on:null,count:"number"==typeof r.count&&Number.isFinite(r.count)?r.count:0,history:Array.isArray(r.history)?r.history.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({by:Wc(e.by)?e.by:"",on:Wc(e.on)?e.on:"",count:"number"==typeof e.count&&Number.isFinite(e.count)?e.count:0})):[]}}}function Bc(e){if(null==e)return{ok:!0,value:[]};if(!Array.isArray(e))return{ok:!1,error:"scenario_catalogs must be an array of catalogs"};if(e.length>Nc)return{ok:!1,error:`scenario_catalogs accepts at most ${Nc} catalogs`};const t=[],r=new Set;for(const a of e){if("object"!=typeof a||null===a||Array.isArray(a))return{ok:!1,error:"each catalog must be an object"};const e=a;if(!Wc(e.id)||!e.id.trim())return{ok:!1,error:"each catalog must carry a non-empty id"};if(r.has(e.id))return{ok:!1,error:`duplicate catalog id "${e.id}"`};if(r.add(e.id),!Wc(e.name)||!e.name.trim())return{ok:!1,error:`catalog "${e.id}" must carry a non-empty name`};if(e.name.length>Uc)return{ok:!1,error:`catalog "${e.id}" name must be at most ${Uc} characters`};if(!Array.isArray(e.entries))return{ok:!1,error:`catalog "${e.id}" entries must be an array`};if(e.entries.length>Pc)return{ok:!1,error:`catalog "${e.id}" accepts at most ${Pc} entries`};const i=[],n=new Set;for(const t of e.entries){if("object"!=typeof t||null===t||Array.isArray(t))return{ok:!1,error:`an entry of catalog "${e.id}" must be an object`};const r=t;if(!Wc(r.id)||!r.id.trim())return{ok:!1,error:`an entry of catalog "${e.id}" must carry a non-empty id`};if(n.has(r.id))return{ok:!1,error:`duplicate entry id "${r.id}" in catalog "${e.id}"`};n.add(r.id);const a=Wc(r.text)?r.text.trim():"";if(!a)return{ok:!1,error:`an entry of catalog "${e.id}" must carry non-empty text`};if(a.length>Uc)return{ok:!1,error:`an entry of catalog "${e.id}" must be at most ${Uc} characters`};const s=Array.isArray(r.function_tags)?r.function_tags.filter(Wc).map(e=>e.trim()).filter(Boolean):[];i.push({id:r.id,text:a,function_tags:s})}const s=Vc(e.acceptance,`catalog "${e.id}"`);if(!s.ok)return s;t.push({id:e.id,name:e.name.trim(),entries:i,acceptance:s.value})}return{ok:!0,value:t}}var Jc,Qc=x({"src/core/catalogs.ts"(){Pc=50,Uc=100,Nc=200,Lc=["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]}}),Gc={};function Yc(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}async function Kc(e,t,r){const{data:a,error:i}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(i)throw new Error(`ID generation failed: ${i.message}`);return a}function Zc(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function Xc(e){const t=e?.relationships?.verified_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function el(e){return JSON.parse(JSON.stringify(e??{}))}async function tl(e,t,r){const a=[];for(const e of r){const t=(e??"").trim();t&&null===or(t,a)&&a.push(t)}if(0===a.length)return a;const{data:i,error:n}=await e.from("metadata").select("domains, function_tags").eq("project_id",t).maybeSingle();if(n)throw new Error(`metadata read failed: ${n.message}`);const s=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],o=s(i?.domains),c=s(i?.function_tags),l=a.filter(e=>null===or(e,o)&&null===or(e,c)),d=l.length>0?await async function(e,t,r){const a=[];for(const e of r){const t=(e??"").trim();t&&null===or(t,a)&&a.push(t)}if(0===a.length)return[];const{data:i,error:n}=await e.rpc("project_item_domain_tags",{p_project_id:t});if(n)throw new Error(`item domain read failed: ${n.message}`);if(!Array.isArray(i))throw new Error("item domain read failed: the answer was not a list of tags");const s=i.filter(e=>"string"==typeof e),o=[];for(const e of a){const t=or(e,s);null!==t&&o.push(t)}return o}(e,t,l):[],p=function(e,t,r,a=[]){const i=[];for(const n of e){if(null!==or(n,r))continue;const e=or(n,t)??or(n,a);null!==e&&null===or(e,i)&&i.push(e)}return i}(a,o,c,d);if(p.length>0)throw new zr(p,p.filter(e=>null===or(e,o)));const u=a.map(e=>or(e,o)??e);try{const{error:r}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"add_functions",p_values:u});if(r){const e=function(e,t){const r=e;if(!r||"22023"!==r.code||r.hint!==qr)return null;let a=[];if("string"==typeof r.details)try{const e=JSON.parse(r.details);Array.isArray(e)&&(a=e.filter(e=>"string"==typeof e))}catch{}return new zr(a.length>0?a:t)}(r,u);if(e)throw e;process.stderr.write(`[atoms-mcp] Warning: function tag registration failed: ${r.message}\n`)}return u}catch(e){if(null!==Hr(e))throw e;return process.stderr.write(`[atoms-mcp] Warning: function tag registration failed: ${e instanceof Error?e.message:String(e)}\n`),a}}async function rl(e,t){const{data:r,error:a}=await e.from("metadata").select("industry").eq("project_id",t).maybeSingle();if(a)throw new Error(a.message);return i=r,n=i?.industry,"automotive"===n||"medical"===n?i.industry:null;var i,n}function al(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}async function il(e,t,r,a){const i=function(e){const t=e?.analysis_props?.variant;return"iso26262"===(r=t)||"iso14971"===r||"tir57"===r||"design"===r||"process"===r||"software"===r||"use"===r?t:null;var r}(a);return{variant:i,schemeId:Nt(r,i,i?null:await rl(e,t))}}async function nl(e,t,r,a){const i=al(a),n=i?await Ki(e,t,i):null;return il(e,t,r,n?.data)}function sl(e,t,r,a={}){const i=a.where?`${a.where}: `:"",n=new Set([...ot[e],...a.extraKeys??[]]),s=Object.keys(r??{});if(0===s.length)return{ok:!1,message:`${i}fields must contain at least one key`};const o=s.filter(e=>qt.includes(e));if(o.length>0)return{ok:!1,message:`${i}${yr(e,o)}`};const c=wr(e);if(c&&s.includes(c.field))return{ok:!1,message:`${i}${vr(e)}`};const l=s.filter(e=>!n.has(e));if(l.length>0)return{ok:!1,message:`${i}Unknown field(s) for ${e}: ${l.join(", ")}. Allowed: ${[...n].sort().join(", ")}`};const d=st[e],p={};for(const t of s){const a=r[t];if(d[t]){const r="number"==typeof a?String(a):a;if("string"!=typeof r||!d[t].includes(r))return{ok:!1,message:`${i}Invalid ${t} value ${JSON.stringify(a)} for ${e}. Allowed: ${d[t].join(", ")}`};p[t]=r}else{if("string"!=typeof a)return{ok:!1,message:`${i}Field '${t}' must be a string`};p[t]=a}}return{ok:!0,writes:p}}async function ol(e){try{const r=await Ua(),a=Wa();try{await Ba(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const i="string"==typeof(t=e.subtype)&&Object.prototype.hasOwnProperty.call(wt,t)?wt[t]:null;if(!i)return xa(oa(function(e){return`subtype must be one of: ${vt.join(", ")} (got ${JSON.stringify(e)})`}(e.subtype)));const n=e.source_req_ids??[],s=e.source_functions??[];if("hara"===i&&n.length>0)return xa(oa("A HARA is seeded from functions, never requirements (a requirement is an output of the analysis): pass source_functions and omit source_req_ids"));if("dfmea"===i&&s.length>0)return xa(oa("source_functions applies to hara only; seed a DFMEA with source_req_ids"));if(n.length>50)return xa(oa("source_req_ids supports at most 50 entries per call"));if(s.length>50)return xa(oa("source_functions supports at most 50 entries per call"));if(n.length>0){const{data:t,error:a}=await r.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null).in("id",n);if(a)throw new Error(a.message);const i=new Map((t??[]).map(e=>[e.id,e])),s=n.filter(e=>!i.has(e));if(s.length>0)return xa(aa("Source requirement(s)",s.join(", ")));const o=n.filter(e=>{const t=i.get(e);return"requirement"!==t.type||Jc.has(t.data?.req_type)});if(o.length>0)return xa(oa(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${o.join(", ")}`))}if(void 0!==e.variant&&!tr(e.subtype).includes(e.variant))return xa(oa(function(e,t){const r=tr(e),a="risk_analysis"===e||"hazard_analysis"===e?"a risk analysis (ISO 14971)":"security_risk"===e?"a security risk analysis (AAMI TIR57)":"fmea"===e?"an fmea":`a ${e}`;return`variant must be ${1===r.length?"":"one of: "}${r.join(", ")} for ${a} (got ${JSON.stringify(t)}); the analysis carries its standard, so pick the variant that names it`}(e.subtype,e.variant)));const o=e.variant??function(e,t){return"medical"===t?jt[e]:bt[e]}(e.subtype,await rl(r,e.project_id)),c=Nt(i,o),l=Lt(c),d=Jt(c),p={},u=[];for(const t of[...ct,...mt]){const r=e[t];"string"==typeof r&&""!==r&&(u.push(t),d.includes(t)&&(p[t]=ja(r)))}const m=u.filter(e=>!d.includes(e));if(m.length>0)return xa(oa(Xt(c,m)));const _="hara"===i?await tl(r,e.project_id,s):n,f=await Kc(r,e.project_id,gt[c]),h=`New ${br(c).parent}`,g=e.title??h,y=e.revision??"1.0",w=ft[i],v=(new Date).toISOString(),b={id:f,type:"analysis",title:g,body:"",tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis:{subtype:i,scheme:c,revision:y,...l?{standard:l}:{}},analysis_props:{variant:o,...p},metadata:{created_at:v,created_by:a,updated_at:v,updated_by:a}},{error:j}=await r.rpc("save_item_with_revision",{p_item_id:f,p_project_id:e.project_id,p_type:"analysis",p_title:g,p_data:b,p_user_id:a,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null});if(j)throw new Error(j.message);const k=(e,t)=>"hara"===i?{id:e,source_function:t}:{id:e,source_req:t},S=[],A=[];for(const t of _){const n=await Kc(r,e.project_id,ht[c]),s={id:n,type:"requirement",title:"",body:"",req_type:w,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[f],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:"hara"===i?{source_req:null,source_function:t,approved:!1,approved_at:null,field_source:{}}:{source_req:t,approved:!1,approved_at:null,field_source:{}},metadata:{created_at:v,created_by:a,updated_at:v,updated_by:a}},{error:o}=await r.rpc("save_item_with_revision",{p_item_id:n,p_project_id:e.project_id,p_type:"requirement",p_title:"",p_data:s,p_user_id:a,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null});if(o)throw new Error(o.message);const{error:l}=await r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:n,p_to_id:f,p_type:"parent",p_action:"add",p_user_id:a,p_event_source:"mcp"});l&&(process.stderr.write(`[atoms-mcp] Warning: analysis row parent link sync failed for ${n}: ${l.message}\n`),A.push({row_id:n,..."hara"===i?{source_function:t}:{source_req:t},message:l.message})),await r.from("change_history").insert({item_id:n,project_id:e.project_id,changed_by:a,event_type:"created",old_data:null,new_data:s,actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),S.push(k(n,t))}return await r.from("change_history").insert({item_id:f,project_id:e.project_id,changed_by:a,event_type:"created",old_data:null,new_data:b,actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Aa(ea({id:f,subtype:i,title:g,revision:y,scheme:c,variant:o,labels:br(c),...l?{standard:l}:{},rows:S,...A.length>0?{link_warnings:A,warning:`${A.length} row(s) were created but could not be attached to the analysis and will not appear in atoms_get_analysis. Repair: for each row in link_warnings, call atoms_link_items with type 'parent', from_id=<row id>, to_id=${f}.`}:{}}))}catch(e){return xa(ya(e))}var t}function cl(e){for(const t of Object.keys(e)){const r=e[t];"string"==typeof r&&(e[t]=ja(r))}}async function ll(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=await Ki(t,e.project_id,e.row_id);if(!a)return xa(aa("Analysis row",e.row_id));const i=a.data;if("analysis"===a.type)return async function(e,t,r,a,i,n){const{schemeId:s}=await il(e,r,function(e){return"dfmea"===e?.analysis?.subtype?"dfmea":"hara"}(i),i),o=function(e,t){const r=Jt(e),a=Object.keys(t??{});if(0===a.length)return{ok:!1,message:"fields must contain at least one key"};const i=a.filter(e=>{return t=e,Te.includes(t)||He.includes(t);var t});if(i.length>0)return{ok:!1,message:Pe(i)};const n=a.filter(e=>!r.includes(e));if(n.length>0)return{ok:!1,message:Xt(e,n)};const s={};for(const r of a){const a=t[r];if("lifecycle_sources"===r){let e=a;if("string"==typeof a)try{e=JSON.parse(a)}catch{return{ok:!1,message:"Field 'lifecycle_sources' must be a JSON array of [name, considered, note] tuples"}}if(!Array.isArray(e)||!e.every(e=>Array.isArray(e)&&3===e.length&&"string"==typeof e[0]&&"boolean"==typeof e[1]&&"string"==typeof e[2]))return{ok:!1,message:"Field 'lifecycle_sources' must be an array of [name, considered, note] tuples"};s[r]=e;continue}if("string"!=typeof a)return{ok:!1,message:`Field '${r}' must be a string`};const i=Qt(e);if("overall_residual_risk"===r&&""!==a&&!i.includes(a))return{ok:!1,message:er(r,a,i)};if("software_safety_class"===r&&""!==a&&!ut.includes(a))return{ok:!1,message:er(r,a,ut)};s[r]=a}return{ok:!0,writes:s}}(s,n);if(!o.ok)return xa(oa(o.message));const c=o.writes;cl(c);const l=el(i);l.analysis_props&&"object"==typeof l.analysis_props||(l.analysis_props={});const d=l.analysis_props;for(const[e,t]of Object.entries(c))d[e]=t;const p=(new Date).toISOString();l.metadata={...l.metadata??{},updated_at:p,updated_by:t};const{data:u,error:m}=await e.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:r,p_type:a.type,p_title:a.title,p_data:l,p_user_id:t,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});if(m)throw new Error(m.message);return u?(await e.from("change_history").insert({item_id:a.id,project_id:r,changed_by:t,event_type:"updated",old_data:i,new_data:l,actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Aa(ea({analysis_id:a.id,scheme:s,written_fields:Object.keys(c),scope:Yt(d),overall:Kt(d)}))):xa(ra(`Fill silently failed for '${a.id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]))}(t,r,e.project_id,a,i,e.fields??{});const n=Yc(i?.req_type);if(!n)return xa(oa(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const{schemeId:s}=await nl(t,e.project_id,n,i),o=sl(s,0,e.fields??{},{extraKeys:"hara"===n?["effect","title"]:["effect"]});if(!o.ok)return xa(oa(o.message));const c=o.writes;if(cl(c),"hara"===n&&"string"==typeof c.source_function&&c.source_function.trim()){const r=i?.analysis_props?.source_function;if("string"==typeof r&&null!==or(c.source_function,[r]))c.source_function=r;else{const[r]=await tl(t,e.project_id,[c.source_function]);r&&(c.source_function=r)}}const l=i?.analysis_props??null,d=el(i);d.analysis_props&&"object"==typeof d.analysis_props||(d.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const p=d.analysis_props;p.field_source&&"object"==typeof p.field_source||(p.field_source={});let u=a.title;for(const[e,t]of Object.entries(c))"effect"===e?d.body=t:"title"===e?(d.title=t,u=t):(p[e]=t,"failure_mode"===e&&"dfmea"===n&&(d.title=t,u=t)),p.field_source[e]="mcp";const m=Ir(p),_=(new Date).toISOString();d.metadata={...d.metadata??{},updated_at:_,updated_by:r};const{data:f,error:h}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:u,p_data:d,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});if(h)throw new Error(h.message);if(!f)return xa(ra(`Fill silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await t.from("change_history").insert({item_id:a.id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:i,new_data:d,actor:Pl(),session_id:Cl(),...m?{reason:`${Object.keys(c).join(", ")} written through atoms_fill_row; approval cleared (a signature never covers content the approver did not see)`}:{}}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});let g=!1;const y=al(i);if(y){const a=await Ki(t,e.project_id,y),i=a?.data,n=i?.analysis_props??{};if(a&&Le(n)){g=!0;const s={...i,analysis_props:n},{error:o}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:s,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});o&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${a.id}': ${o.message}\n`)}}const w=fr(s,p),v=[];if("hara_iso26262"===s){const i=fr(s,l),n=Zc(d);if(n.length>0&&w!==Ke&&w!==i)for(const i of n){const n=await Ki(t,e.project_id,i);if(!n)continue;const s=n.data;if(s?.asil===w&&s?.asil_source===a.id)continue;const o=s?.asil??null,c=s?.asil_source??null,l=el(s);l.asil=w,l.asil_source=a.id,l.metadata={...l.metadata??{},updated_at:_,updated_by:r};const{error:d}=await t.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:e.project_id,p_type:n.type,p_title:n.title,p_data:l,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at});if(d)throw new Error(d.message);await t.from("change_history").insert({item_id:n.id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:{asil:o,asil_source:c},new_data:{asil:w,asil_source:a.id},actor:Pl(),session_id:Cl(),reason:`ASIL propagated from ${a.id} (rating change via atoms_fill_row)`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),v.push(i)}}return Aa(ea({row_id:a.id,subtype:n,written_fields:Object.keys(c),computed_level:w,...v.length>0?{asil_propagated_to:v}:{},...m?{approval_cleared:!0}:{},acceptance_revoked:g}))}catch(e){return xa(ya(e))}}function dl(e){const t=e??{},r=String(t.threat_model_method??"").trim(),a=e=>String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e),i=Array.isArray(t.lifecycle_sources)?t.lifecycle_sources.filter(e=>Array.isArray(e)&&3===e.length&&"string"==typeof e[0]&&"boolean"==typeof e[1]&&"string"==typeof e[2]).map(([e,t,r])=>({name:e,considered:t,note:r})):[];return{stated:""!==r,method:r,rationale:String(t.threat_model_rationale??"").trim(),environment_assumptions:a(t.environment_assumptions),attack_surfaces:a(t.attack_surfaces),lifecycle_sources:i,related_documents:String(t.related_documents??"").trim()}}async function pl(e,t,r){const a=await Ki(e,t,r);if(!a)return{ok:!1,result:xa(aa("Analysis",r))};if("analysis"!==a.type)return{ok:!1,result:xa(oa(`Item ${r} is not an analysis (type='${a.type}')`))};const i=a.data,n=Yc("hara"===i?.analysis?.subtype?"safety-goal":"dfmea"===i?.analysis?.subtype?"failure-mode":null);if(!n)return{ok:!1,result:xa(oa(`Analysis ${r} is missing a valid analysis.subtype`))};const s=ft[n],{variant:o,schemeId:c}=await il(e,t,n,i),l=Array.isArray(i?.relationships?.children)?i.relationships.children.filter(e=>"string"==typeof e):[];let d=[];if(l.length>0){const{data:r,error:a}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",l);if(a)throw new Error(a.message);const i=new Map((r??[]).filter(e=>!e.deleted_at&&l.includes(e.id)&&e.data?.req_type===s).map(e=>[e.id,e]));d=l.map(e=>i.get(e)).filter(e=>Boolean(e))}const p=new Set;for(const e of d){const t=e.data?.analysis_props??{};"string"==typeof t.source_req&&t.source_req&&p.add(t.source_req);for(const t of Zc(e.data))p.add(t);for(const t of Xc(e.data))p.add(t)}const u=new Map;if(p.size>0){const{data:r,error:a}=await e.from("items").select("id, updated_at").eq("project_id",t).is("deleted_at",null).in("id",[...p]);if(a)throw new Error(a.message);for(const e of r??[])u.set(e.id,e.updated_at)}const m=d.map(e=>{const t=e.data?.analysis_props??{},r=Zc(e.data).filter(e=>u.has(e)),a=Xc(e.data).filter(e=>u.has(e)),i=r.length>0,n=fr(c,t),s=function(e,t,r){if(r)return null;if("hara_iso26262"===e){const e=cr(t);return"QM"!==e&&e!==Ke?`asil ${e} unmitigated`:null}if("hazard_iso14971"===e){const e=pr(t);return"Low"!==e&&e!==Ke?`${e.toLowerCase()} risk uncontrolled`:null}if("security_tir57"===e){const e=mr(t);return Me(e)?`${e.toLowerCase()} security risk uncontrolled`:null}const a=parseInt(fr(e,t),10),i=parseInt(t?.severity||"",10);return!Number.isNaN(a)&&a>=100?"rpn >= 100":!Number.isNaN(i)&&i>=9?"severity >= 9":null}(c,t,i),o={id:e.id,title:"string"==typeof e.title?e.title:"",source_req:"string"==typeof t.source_req?t.source_req:null,effect:"string"==typeof e.data?.body?e.data.body:"",computed_level:n,computed_level_text:nr(c,n),is_gap:null!==s,gap_rule:s,is_critical:hr(c,t,i),is_stale:gr(t,r,e=>u.get(e)??null),mitigated_by:r,link_roles:t.link_roles??{},approved:!0===t.approved,approved_at:t.approved_at??null,approved_by:t.approved_by??null,approved_note:"string"==typeof t.approved_note?t.approved_note:"",verified_by:a,residual_level:"hazard_iso14971"===c?ur(t):"security_tir57"===c?_r(t):null,mitigation_types:t.mitigation_types??{},mcp_fields:Object.entries(t.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort()};for(const e of ot[c])o[e]=t[e]??null;return o});return{ok:!0,analysis:{id:a.id,title:"string"==typeof a.title?a.title:"",subtype:n,scheme:c,revision:"string"==typeof i?.analysis?.revision?i.analysis.revision:"1.0",standard:"string"==typeof i?.analysis?.standard?i.analysis.standard:Lt(c)??null,variant:o,labels:br(c),acceptability:ir(c),definitions:ar(c),control_types:kr(c),field_labels:rr(c),scope:Jt(c).length>0?Yt(i?.analysis_props):null,overall:Jt(c).length>0?Kt(i?.analysis_props,Qt(c)):null,threat_model:"security_tir57"===c?dl(i?.analysis_props):null,acceptance:Ne(i?.analysis_props)},schemeId:c,parentProps:i?.analysis_props??null,rows:m,counts:{rows:m.length,gaps:m.filter(e=>e.is_gap).length,critical:m.filter(e=>e.is_critical).length,stale:m.filter(e=>e.is_stale).length,approved:m.filter(e=>e.approved).length,linked:m.filter(e=>e.mitigated_by.length>0).length}}}async function ul(e){try{const t=await Ua(),r=await pl(t,e.project_id,e.analysis_id);return r.ok?Aa(ea({analysis:r.analysis,rows:r.rows,counts:r.counts})):r.result}catch(e){return xa(ya(e))}}async function ml(e){try{const i=await Ua(),n=Wa();try{await Ba(i,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}if(e.row_id===e.req_id)return xa(oa("row_id and req_id must be different items"));const s=await Ki(i,e.project_id,e.row_id);if(!s)return xa(aa("Analysis row",e.row_id));const o=s.data,c=Yc(o?.req_type);if(!c)return xa(oa(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const l=await Ki(i,e.project_id,e.req_id);if(!l)return xa(aa("Requirement",e.req_id));const d=l.data;if("requirement"!==l.type||Jc.has(d?.req_type))return xa(oa(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));const{schemeId:p}=await nl(i,e.project_id,c,o);if(function(e){return"hara_iso26262"===e||"hazard_iso14971"===e||"security_tir57"===e}(p)&&d?.req_type!==Qe)return xa(oa(function(e,t){return`${e} is not a ${zt[t].mitigating_requirement}: a mitigation target must be a requirement of req_type '${Qe}'. Create or convert one, then link it.`}(e.req_id,p)));const u=jr(p);if(0===u.length&&void 0!==e.control_type)return xa(oa(function(e){return`control_type applies to the medical schemes only (ISO 14971 clause 7); ${zt[e].parent} links carry none, so omit it.`}(p)));if(u.length>0&&!e.control_type)return xa(oa(Sr(p)));if(!(void 0===e.control_type||Ft(e.control_type)&&function(e,t){return jr(e).some(e=>e.id===t)}(p,e.control_type)))return xa(oa(Sr(p)));if("dfmea"===c&&!e.role)return xa(oa(`role is required for dfmea mitigation links. Choose one of: ${Ze.join(", ")}`));if("hara"===c&&e.role)return xa(oa("role is not applicable to hara mitigation links; omit it (roles are a dfmea concept)"));let m=Ke;if("hara_iso26262"===p){m=fr(p,o?.analysis_props);const i=d?.asil;if(m!==Ke&&"string"==typeof i&&i.length>0&&i!==m&&!0!==e.override)return xa((r=m,{...ra(`ASIL conflict: the target requirement already carries asil '${t=i}' but ${a=s.id} computes '${r}'.`,["Pass override=true to apply the HARA value; the override is history-logged like a dialog accept","Or align the row's S/E/C ratings with the existing ASIL before linking"]),details:{code:"asil_conflict",current_value:t,incoming_value:r,source_row:a,hint:"pass override=true to apply the HARA value; the override is history-logged like a dialog accept"}}))}const _="dfmea"===c?e.role:null,{error:f}=await i.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:e.row_id,p_to_id:e.req_id,p_type:"mitigated_by",p_action:"add",p_user_id:n,p_event_source:"mcp",p_expected_from_updated_at:s.updated_at,p_expected_to_updated_at:l.updated_at,p_role:_});if(f)throw new Error(f.message);await i.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"add",type:"mitigated_by",from:e.row_id,to:e.req_id,..._?{role:_}:{}}},actor:Pl(),session_id:Cl()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});{const t=al(o);if(t){const r=await Ki(i,e.project_id,t);if(r){const{revoked:t,parentProps:a}=We(r.data);if(t){const t={...r.data,analysis_props:a},{error:s}=await i.rpc("save_item_with_revision",{p_item_id:r.id,p_project_id:e.project_id,p_type:r.type,p_title:r.title,p_data:t,p_user_id:n,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:r.updated_at});s&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${r.id}': ${s.message}\n`)}}}}let h,g;if(e.control_type&&Ft(e.control_type)){const t=await Ki(i,e.project_id,e.row_id)??s,r=el(t.data);r.analysis_props&&"object"==typeof r.analysis_props||(r.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const a=r.analysis_props;a.mitigation_types&&"object"==typeof a.mitigation_types||(a.mitigation_types={}),a.mitigation_types[e.req_id]=e.control_type;const o=(new Date).toISOString();r.metadata={...r.metadata??{},updated_at:o,updated_by:n};const{error:c}=await i.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:r,p_user_id:n,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});if(c)throw new Error(c.message);h=e.control_type}if("hara_iso26262"===p&&m!==Ke){const t=await Ki(i,e.project_id,e.req_id);if(t){const r=t.data,a=r?.asil??null,o=r?.asil_source??null,c=el(r);c.asil=m,c.asil_source=s.id;const l=(new Date).toISOString();c.metadata={...c.metadata??{},updated_at:l,updated_by:n};const{error:d}=await i.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:c,p_user_id:n,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});if(d)throw new Error(d.message);await i.from("change_history").insert({item_id:t.id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:{asil:a,asil_source:o},new_data:{asil:m,asil_source:s.id},actor:Pl(),session_id:Cl(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${a??"unset"}', now '${m}' from ${s.id})`:`ASIL set via atoms_link_mitigation from ${s.id}`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),g=m}}return Aa(ea({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:_,scheme:p,...h?{control_type:h}:{},...g?{asil_written:g}:{}}))}catch(e){return xa(ya(e))}var t,r,a}async function _l(e){try{const r=await Ua(),a=await pl(r,e.project_id,e.analysis_id);if(!a.ok)return a.result;const i=a.rows.filter(e=>e.is_gap).map(e=>({id:e.id,title:e.title,source_req:e.source_req,source_function:"string"==typeof e.source_function?e.source_function:null,computed_level:e.computed_level,rule:e.gap_rule})),n=Wt(await async function(e,t){const{data:r,error:a}=await e.from("metadata").select("levels").eq("project_id",t).maybeSingle();if(a)throw new Error(a.message);const i=r?.levels;return Array.isArray(i)?i.filter(e=>"string"==typeof e):[]}(r,e.project_id)),s=Er(a.schemeId).some(e=>"requirement"===e.scope)?await async function(e,t,r){const{data:a,error:i}=await e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null).eq("type","requirement");if(i)throw new Error(i.message);const n=(a??[]).filter(e=>e.data?.req_type===Qe&&function(e,t){const r=Vt(e);return r.length>0&&r===Vt(t)}(e.data?.tags?.level,r));if(0===n.length)return[];const s=e=>{const t=e.data?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]},o=new Set;for(const e of n)for(const t of s(e))o.add(t);const c=new Set;if(o.size>0){const{data:r,error:a}=await e.from("items").select("id").eq("project_id",t).is("deleted_at",null).in("id",[...o]);if(a)throw new Error(a.message);for(const e of r??[])c.add(e.id)}return n.filter(e=>!s(e).some(e=>c.has(e))).map(e=>e.id)}(r,e.project_id,n.level):[],o=a.rows.map(e=>({id:e.id,level:e.computed_level,linked:e.mitigated_by.length>0,verified:e.verified_by.length>0,residualLevel:e.residual_level??Ke,severity:Ar(e.severity)})),c="hara_iso26262"===a.schemeId&&function(e,t){const r=Array.isArray(e)?e:[];return 0!==r.length&&r.some(e=>{const r=t.find(t=>t.id===e);return!r||"accepted"!==r.acceptance.state})}(a.parentProps?.scenario_catalogs,await async function(e,t){const{data:r,error:a}=await e.from("metadata").select("scenario_catalogs").eq("project_id",t).maybeSingle();if(a)throw new Error(a.message);const i=Bc(r?.scenario_catalogs??[]);return i.ok?i.value:[]}(r,e.project_id)),l=function(e,t,r,a=!1){const i="security_tir57"===r,n=i?String(e?.threat_model_method??"").trim():void 0;return{hasRows:t.length>0,scopeStated:i?""!==n:Zt(e),overallJudged:""!==Kt(e,i?Ae:pt).residual_risk,everyRowSettled:t.every(e=>e.linked&&e.residualLevel!==Ke),catalogsDraft:a,accepted:"accepted"===e?.acceptance_state}}(a.parentProps,o,a.schemeId,c),d=function(e,t,r,a){const i=[];for(const n of Er(e)){if("analysis"===n.scope){if(!a||!n.matchesAnalysis||!n.matchesAnalysis(a))continue;i.push({kind:n.kind,label:n.label(1),rowIds:[],reqIds:[],count:1,fix:n.fix,fixLabel:n.fixLabel});continue}if("requirement"===n.scope){if(0===r.length)continue;i.push({kind:n.kind,label:n.label(r.length),rowIds:[],reqIds:[...r],count:r.length,fix:n.fix,fixLabel:n.fixLabel});continue}const e=n.matches;if(!e)continue;const s=t.filter(t=>e(t)).map(e=>e.id);0!==s.length&&i.push({kind:n.kind,label:n.label(s.length),rowIds:s,reqIds:[],count:s.length,fix:n.fix,fixLabel:n.fixLabel})}return i}(a.schemeId,o,s,l),p=d.map(e=>({kind:e.kind,label:e.label,row_ids:e.rowIds,req_ids:e.reqIds,gap_count:e.count,fix:e.fix,fix_label:e.fixLabel}));return Aa(ea({analysis_id:a.analysis.id,subtype:a.analysis.subtype,scheme:a.analysis.scheme,labels:a.analysis.labels,gaps:i,count:(t=d,t.reduce((e,t)=>e+t.count,0)),gap_kinds:p,system_level:n.level,system_level_source:n.source}))}catch(e){return xa(ya(e))}var t}function fl(e){return(e.failure_mode??"").trim()||(e.hazard??"").trim()||""}async function hl(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=await Ki(t,e.project_id,e.analysis_id);if(!a)return xa(aa("Analysis",e.analysis_id));if("analysis"!==a.type)return xa(oa(`Item ${e.analysis_id} is not an analysis (type='${a.type}')`));const i=a.data,n=i?.analysis?.subtype,s="hara"===n?"hara":"dfmea"===n?"dfmea":null;if(!s)return xa(oa(`Analysis ${e.analysis_id} is missing a valid analysis.subtype`));const{variant:o,schemeId:c}=await il(t,e.project_id,s,i);if("hara"===s&&e.source_req)return xa(oa("A risk analysis row is seeded from a function, never a requirement: pass source_function"));if("dfmea"===s&&e.source_function)return xa(oa("source_function applies to a risk analysis only; seed an FMEA row with source_req"));const l=Array.isArray(e.rows)?e.rows:[];if(0===l.length)return xa(oa("rows must contain at least one drafted row"));if(l.length>Ye)return xa(oa(`Propose rows accepts at most ${Ye} rows per call; ${l.length} were sent. Split the proposal and call again.`));const d=[];for(let e=0;e<l.length;e++){const t=sl(c,0,l[e]??{},{extraKeys:"hara"===s?["effect","title"]:["effect"],where:`row ${e+1}`});if(!t.ok)return xa(oa(t.message));cl(t.writes),d.push(t.writes)}let p=ja(e.source_function??"").trim();if("hara"===s&&p){const[r]=await tl(t,e.project_id,[p]);r&&(p=r)}const u=(new Date).toISOString(),m=ft[s],_=[],f=[];for(const a of d){const i=await Kc(t,e.project_id,ht[c]),n={source_req:"dfmea"===s?e.source_req??null:null,..."hara"===s?{source_function:p||null}:{},approved:!1,approved_at:null,approved_by:null,field_source:{}};let o="",l="";for(const[e,t]of Object.entries(a))"effect"===e?o=t:"title"===e?l=t:(n[e]=t,"failure_mode"===e&&"dfmea"===s&&(l=t)),n.field_source[e]="mcp";l||(l=fl(a));const d={id:i,type:"requirement",title:l,body:o,req_type:m,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[e.analysis_id],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:n,metadata:{created_at:u,created_by:r,updated_at:u,updated_by:r}},{error:h}=await t.rpc("save_item_with_revision",{p_item_id:i,p_project_id:e.project_id,p_type:"requirement",p_title:l,p_data:d,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null});if(h)throw new Error(h.message);const{error:g}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:i,p_to_id:e.analysis_id,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"});g&&(process.stderr.write(`[atoms-mcp] Warning: proposed row parent link sync failed for ${i}: ${g.message}\n`),f.push({row_id:i,message:g.message})),await t.from("change_history").insert({item_id:i,project_id:e.project_id,changed_by:r,event_type:"created",old_data:null,new_data:d,actor:Pl(),session_id:Cl(),reason:"Row proposed through atoms_propose_rows (machine-proposed, unapproved)"}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),_.push({id:i,written_fields:Object.keys(a),computed_level:fr(c,n)})}if(_.length>0){const{revoked:n,parentProps:s}=We(i);if(n){const n={...i,analysis_props:s},{error:o}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:n,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});o&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${a.id}': ${o.message}\n`)}}return Aa(ea({analysis_id:e.analysis_id,subtype:s,scheme:c,...o?{variant:o}:{},labels:br(c),..."hara"===s?{source_function:p||null}:{source_req:e.source_req??null},rows:_,count:_.length,max_rows:Ye,approved:!1,...f.length>0?{link_warnings:f,warning:`${f.length} proposed row(s) were created but could not be attached to ${e.analysis_id}. Repair: call atoms_link_items with type 'parent', from_id=<row id>, to_id=${e.analysis_id}.`}:{}}))}catch(e){return xa(ya(e))}}async function gl(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=await Ki(t,e.project_id,e.row_id);if(!a)return xa(aa("Analysis row",e.row_id));const i=a.data,n=Yc(i?.req_type);if(!n)return xa(oa(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const{schemeId:s}=await nl(t,e.project_id,n,i),o=e.rationale?function(e,t){return st[e][t]?"hara_iso26262"===e?"severity"===t?"s_rationale":"exposure"===t?"e_rationale":"controllability"===t?"c_rationale":null:"hazard_iso14971"===e?"severity"===t||"residual_s"===t?"s_rationale":"p1"===t||"residual_p1"===t?"p1_rationale":"p2"===t||"residual_p2"===t?"p2_rationale":null:"security_tir57"===e?"severity"===t||"residual_s"===t?"s_rationale":"exploitability"===t||"residual_e"===t?"e_rationale":null:"rationale":null}(s,e.field):null;if(e.rationale&&!o)return xa(oa(`rationale applies to a rating field only; ${e.field} is not a rating of ${s}`));const c={[e.field]:e.value};o&&e.rationale&&(c[o]=e.rationale);const l=sl(s,0,c,{extraKeys:"hara"===n?["effect","title"]:["effect"]});if(!l.ok)return xa(oa(l.message));const d=l.writes;cl(d);const p=el(i);p.analysis_props&&"object"==typeof p.analysis_props||(p.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const u=p.analysis_props;u.field_source&&"object"==typeof u.field_source||(u.field_source={});let m=a.title;for(const[e,t]of Object.entries(d))"effect"===e?p.body=t:"title"===e?(p.title=t,m=t):(u[e]=t,"failure_mode"===e&&"dfmea"===n&&(p.title=t,m=t)),u.field_source[e]="mcp";const _=Ir(u),f=(new Date).toISOString();p.metadata={...p.metadata??{},updated_at:f,updated_by:r};const{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:m,p_data:p,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});if(g)throw new Error(g.message);if(!h)return xa(ra(`Suggestion silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await t.from("change_history").insert({item_id:a.id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:i,new_data:p,actor:Pl(),session_id:Cl(),reason:`${e.field} suggested through atoms_suggest_field (machine-proposed, unapproved)`+(_?"; approval cleared (a signature never covers content the approver did not see)":"")}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=Object.entries(u.field_source).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return Aa(ea({row_id:a.id,subtype:n,scheme:s,field:e.field,field_source:"mcp",written_fields:Object.keys(d),...o?{rationale_field:o}:{},..._?{approval_cleared:!0}:{},row:{id:a.id,computed_level:fr(s,u),approved:!0===u.approved,mcp_fields:y,...Object.fromEntries(ot[s].map(e=>[e,u[e]??null]))}}))}catch(e){return xa(ya(e))}}async function yl(e){try{const t=await Ua(),r=Wa();try{await Ba(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}const a=await Ki(t,e.project_id,e.row_id);if(!a)return xa(aa("Analysis row",e.row_id));const i=a.data,n=Yc(i?.req_type);if(!n)return xa(oa(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const s=e.approver_id??r,o=await async function(e,t,r){const{data:a,error:i}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(i)throw new Error(i.message);if(!a)throw new Error(`Project '${t}' not found`);const{data:n,error:s}=await e.from("org_members").select("role").eq("user_id",r).eq("org_id",a.org_id).maybeSingle();if(s)throw new Error(s.message);const o=n?.role;return"string"==typeof o?o:null}(t,e.project_id,s);if(!o)return xa(oa(`Approver '${s}' is not a member of this project's organization. Approve as a project member (omit approver_id to approve as yourself).`));const{schemeId:c}=await nl(t,e.project_id,n,i),l=i?.analysis_props??{},d=fr(c,l);if(d===Ke)return xa(oa(`${e.row_id} cannot be approved before it is rated: complete the rating fields first (the computed ${"hara_iso26262"===c?"ASIL":"hazard_iso14971"===c?"risk":"RPN"} is unset).`));const p=el(i);p.analysis_props&&"object"==typeof p.analysis_props||(p.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const u=p.analysis_props;u.field_source&&"object"==typeof u.field_source||(u.field_source={});const m=ja(e.note??""),_=(new Date).toISOString();u.approved=!0,u.approved_at=_,u.approved_by=s,u.approved_note=m;const f=[];for(const[e,t]of Object.entries(u.field_source))"mcp"===t&&(u.field_source[e]="user",f.push(e));f.sort(),p.metadata={...p.metadata??{},updated_at:_,updated_by:r};const{data:h,error:g}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:p,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});if(g)throw new Error(g.message);if(!h)return xa(ra(`Approval silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await t.from("change_history").insert({item_id:a.id,project_id:e.project_id,changed_by:r,event_type:"updated",old_data:{approved:!0===l.approved,approved_at:l.approved_at??null,approved_by:l.approved_by??null,approved_note:l.approved_note??""},new_data:{approved:!0,approved_at:_,approved_by:s,approved_note:m},actor:Pl(),session_id:Cl(),reason:`${e.row_id} approved by ${s} via atoms_approve_row`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=al(i);if(y){const a=await Ki(t,e.project_id,y);if(a){const{revoked:i,parentProps:n}=We(a.data);if(i){const i={...a.data,analysis_props:n},{error:s}=await t.rpc("save_item_with_revision",{p_item_id:a.id,p_project_id:e.project_id,p_type:a.type,p_title:a.title,p_data:i,p_user_id:r,p_event_source:"mcp",p_event_session_id:Cl()??null,p_diff_summary:null,p_expected_updated_at:a.updated_at});s&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${a.id}': ${s.message}\n`)}}}return Aa(ea({row_id:a.id,subtype:n,scheme:c,approved:!0,approved_by:s,approved_at:_,approved_note:m,approver_role:o,computed_level:d,cleared_markers:f}))}catch(e){return xa(ya(e))}}E(Gc,{approveRowHandler:()=>yl,createAnalysisHandler:()=>ol,fillRowHandler:()=>ll,getAnalysisHandler:()=>ul,getGapsHandler:()=>_l,linkMitigationHandler:()=>ml,proposeRowsHandler:()=>hl,registerFunctionTags:()=>tl,suggestFieldHandler:()=>gl});var wl=x({"src/tools/analysis.ts"(){Ya(),sn(),Nl(),Oa(),Tr(),Yr(),Qc(),Ut(),Jc=new Set(["safety-goal","failure-mode"])}}),vl={};async function bl(e,t){const{data:r,error:a}=await e.from("metadata").select("scenario_catalogs").eq("project_id",t).maybeSingle();if(a)throw new Error(a.message);const i=Bc(r?.scenario_catalogs??[]);return i.ok?i.value:[]}async function jl(e){try{const t=await Ua(),r=Math.min(Math.max(e.limit??50,1),200),a=Math.max(e.offset??0,0),i=await bl(t,e.project_id);return Aa(ea(i.slice(a,a+r),ta(i.length,r,a)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}}async function kl(e){try{const r=await Ua();Wa();try{await Ba(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return xa(sa("Viewer"));throw e}if("string"!=typeof(t=e.op)||!Lc.includes(t))return xa(oa("op must be one of create_catalog, rename_catalog, delete_catalog, add_entry, edit_entry, remove_entry, tag_entry, accept_catalog."));const a=e.op;if("create_catalog"===a&&(await bl(r,e.project_id)).length>=Nc)return xa(oa(`This project already carries the maximum of ${Nc} catalogs.`));const i={};"create_catalog"!==a||e.catalog_id?void 0!==e.catalog_id&&(i.catalog_id=e.catalog_id):i.catalog_id=`cat-${crypto.randomUUID().replace(/-/g,"").slice(0,12)}`,void 0!==e.name&&(i.name=ja(e.name)),void 0!==e.entry_id&&(i.entry_id=e.entry_id),void 0!==e.text&&(i.text=ja(e.text)),void 0!==e.function_tags&&(i.function_tags=e.function_tags),void 0!==e.by&&(i.by=e.by),void 0!==e.on&&(i.on=e.on);const{data:n,error:s}=await r.rpc("mutate_project_scenario_catalogs",{p_project_id:e.project_id,p_op:a,p_payload:i});return s?xa(oa(s.message)):Aa(ea({scenario_catalogs:n?.scenario_catalogs??[]}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?xa(ca()):xa(va(e instanceof Error?e.message:String(e)))}var t}E(vl,{listScenarioCatalogsHandler:()=>jl,mutateScenarioCatalogHandler:()=>kl});var Sl,Al,xl,El,Il,Rl,Ol,$l,ql,zl,Ml=x({"src/tools/catalogs.ts"(){Ya(),Oa(),Qc()}}),Tl={};function Hl(e){F(e.toolName)&&function(e,t){const r=`ui://${t.toolName}/${t.htmlFile}`,a=function(e,t){const r=s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:u&&"SCRIPT"===u.tagName.toUpperCase()&&u.src||new URL("index.cjs",document.baseURI).href),a=j.default.dirname(r);return j.default.resolve(a,"apps","src","apps",e,t)}(t.appName,t.htmlFile),i=[...Li.resourceDomains,...t.extraResourceDomains??[]];c.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:r}}},t.handler),c.registerAppResource(e,`${t.title} UI`,r,{mimeType:c.RESOURCE_MIME_TYPE},async()=>{const e=await b.default.readFile(a,"utf-8");return{contents:[{uri:r,mimeType:c.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:i}}}}]}})}(El,e)}function Dl(e,t){return async r=>{let a="",i=null;try{i=await Ua(),a=Wa()}catch{i=null}if(i){const e=await async function(e,t){let r;try{r=await $a(e,t)}catch(e){return process.stderr.write(`[atoms-mcp] platform_status lookup failed: ${e instanceof Error?e.message:String(e?.message??e)}\n`),ra("Authorization check failed.",["ATOMS could not confirm your account status, so the call was refused","Retry in a moment; if it keeps failing, run atoms_status"])}return"suspended"===r?ia("account"):"pending"===r?ra("Account pending platform approval.",["A platform admin must approve your ATOMS account before ATOMS tools can be used","Sign in to the ATOMS web app to check your account status"]):null}(i,a);if(e)return xa(e)}const n=O(P(),e);if(!n.allowed)return xa(ra(`Tool ${e} is blocked by org policy.`,[q(n.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=fi();if(!t)return;if("object"!=typeof e||null===e)return;const r=e.project_id;if("string"==typeof r&&r!==t)throw new ui(t,r)}(r)}catch(e){if(e instanceof ui)return xa(da(e.expectedProjectId));throw e}{const e=P(),t=r?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return xa(ra("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"]))}if(!i)return t(r);const s=await async function(e,t){const r=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||ci,a=new Date,i=new Date(a.getTime()-li);try{const{count:n,error:s}=await t.from("mcp_rate_limits").select("id",{count:"exact",head:!0}).eq("user_id",e).gte("requested_at",i.toISOString());if(s)throw new Error(s.message);if((n??0)>=r){const{data:r,error:n}=await t.from("mcp_rate_limits").select("requested_at").eq("user_id",e).gte("requested_at",i.toISOString()).order("requested_at",{ascending:!0}).limit(1).maybeSingle();if(n)throw new Error(n.message);const s=(r?new Date(r.requested_at).getTime():a.getTime())+li-a.getTime();return{allowed:!1,retryAfterSeconds:Math.max(1,Math.ceil(s/1e3))}}t.from("mcp_rate_limits").insert({user_id:e,requested_at:a.toISOString()}).then(({error:e})=>{e&&process.stderr.write(`[rate-limiter] insert failed: ${e.message}\n`)});const o=new Date(a.getTime()-2*li);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}}}(a,i);if(!s.allowed)return xa(pa(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(()=>(Ya(),Pa));await t(i,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(Oa(),Kr));return xa(e("Viewer (lockdown mode: read access requires editor or admin)"))}}}const o=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let c,l="success";try{const e=await t(r),a=e;if(!0===a?.isError){l="error";const e=a?.content;if(e?.[0]?.text)try{c=JSON.parse(e[0].text).message}catch{}}return e}catch(e){throw l="error",c=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:r,status:l,duration_ms:o(),error_msg:c,project_id:r.project_id,session_id:Rl,client_name:Ol};try{!function(e,t,r){const a=oi(r.params);e.from("mcp_audit_log").insert({user_id:t,tool_name:r.tool_name,params:a,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 Ua(),a,t)}catch{}}}}function Cl(){return Rl}function Pl(){return $l}function Ul(){return Ol}E(Tl,{ATOMS_MCP_SERVER_VERSION:()=>xl,getMcpActor:()=>Pl,getMcpClientName:()=>Ul,getMcpSessionId:()=>Cl,server:()=>El});var Nl=x({"src/server.ts"(){mi(),_i(),B(),gi(),U(),D(),ki(),Si(),Tr(),zi(),Fi(),Ya(),Ca(),Oa(),Wi(),Sl=d.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:u&&"SCRIPT"===u.tagName.toUpperCase()&&u.src||new URL("index.cjs",document.baseURI).href),Al=Sl("../package.json"),xl=Al.version,El=new l.McpServer({name:"atoms-mcp-server",version:xl}),Il=(e,t,r)=>{if(F(e))return El.registerTool(e,t,r)},Rl=n.randomUUID(),Ol=yi(process.env.ATOMS_CLIENT_NAME),$l=function(){const e=yi(Ol);return"cursor"===e?"mcp_cursor":"copilot"===e?"mcp_copilot":"mcp_claude"}(),Il("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"|"suspended"|"pending", email, message, next_steps?, org_suspended? }\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()=>{const e=(e,t)=>async function(e,t,r){try{const e=await(async()=>async function(e,t){Ia.delete(t);const r=await $a(e,t);let a=null;const{data:i,error:n}=await e.from("organizations").select("id, name").eq("status","suspended");return n||(a=(i??[]).map(e=>({org_id:e.id,name:e.name}))),{platform_status:r,org_suspended:a}}(await Ua(),Wa()))();return"suspended"===e.platform_status?{status:"suspended",email:t,message:"Your ATOMS account is suspended. ATOMS tools are unavailable.",next_steps:["Contact ATOMS support or your organization admin to restore access"]}:"pending"===e.platform_status?{status:"pending",email:t,message:"Your ATOMS account is waiting for platform approval. ATOMS tools are unavailable until then.",next_steps:["Sign in to the ATOMS web app to check your account status"]}:{status:"authenticated",email:t,message:(e.org_suspended??[]).length>0?Ra:r,...e.org_suspended?{org_suspended:e.org_suspended}:{}}}catch(e){return{status:"error",email:t,message:`Credentials are valid, but ATOMS could not check your account status: ${e instanceof Error?e.message:String(e)}`,next_steps:["Retry in a moment; tool calls are refused until the account status can be checked"]}}}(0,e,t);try{const{readCredentials:t,isTokenValid:r}=await Promise.resolve().then(()=>(oe(),J)),a=await t();if(!a)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(!r(a))try{const{getValidToken:t}=await Promise.resolve().then(()=>($e(),ve)),{email:r}=await t(),{invalidateClient:a}=await Promise.resolve().then(()=>(Ya(),Pa));return a(),{content:[{type:"text",text:qa(await e(r,"Token was expired but has been refreshed. You're good to go!"))}]}}catch{return{content:[{type:"text",text:JSON.stringify({status:"expired",email:a.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:qa(await e(a.user_email??"unknown","ATOMS MCP is connected and authenticated. All tools are ready."))}]}}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)}]}}}),Il("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}},Dl("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(ln(),on));return e()})),Il("atoms_list_items",{title:"List ATOMS Items",description:'List items in an ATOMS project with optional type/domain/level filters.\n\nThis is the primary ENTRY POINT for discovering items. Use it to browse\nproject contents before drilling into specific items with atoms_get_item.\n\nArgs:\n - project_id (string, UUID): The project to list items from\n - type (string, optional): Filter: requirement|test-case|note|table\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - limit (number, optional): Max results, 1-200 (default 50)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { status: "success", data: [{ id, title, type, status, domains, level }], meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me all requirements" → atoms_list_items(project_id, type="requirement")\n - "What test cases exist?" → atoms_list_items(project_id, type="test-case")\n\nErrors:\n - "Project not found" → verify project_id\n - "Access denied" → check org membership',inputSchema:{project_id:o.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),domain:o.z.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:o.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:o.z.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns items as they were at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(mn(),dn));return t(e)})),Il("atoms_get_item",{title:"Get ATOMS Item Details",description:'Get full details of a single item including relationships, test history, and ownership.\n\nUse after atoms_list_items or atoms_search to drill into a specific item.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID (e.g., "REQ-001", "TC-050")\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\nExamples:\n - "Show me requirement REQ-001" → atoms_get_item(project_id, "REQ-001")\n - "Get test case details" → atoms_get_item(project_id, "TC-050")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID. Returns the item as it was at that baseline's moment. Mutually exclusive with as_of."),as_of:o.z.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns the item as it was at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(gn(),_n));return t(e)})),Il("atoms_search",{title:"Search ATOMS Items",description:'Full-text search across items in a project. Searches title, body, and summary.\n\nAlternative entry point to atoms_list_items when you know what you\'re looking for.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Search text (max 1000 chars)\n - type (string, optional): Filter by type\n - asset (string, optional): Filter to items with at least one run on the given asset\n (VIN, module, lot, ...). Case-sensitive exact match.\n - limit (number, optional): Max results, 1-100 (default 25)\n\nReturns:\n Matching items with @basic fields, ranked by relevance.\n\nExamples:\n - "Find braking requirements" → atoms_search(project_id, "braking system")\n - "Search for safety tests" → atoms_search(project_id, "safety", type="test-case")\n - "Tests that ran on this VIN" → atoms_search(project_id, "", asset="WEV...0005")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),query:o.z.string().min(1).max(1e3).describe("Search text"),type:o.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),asset:o.z.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID. Searches within the project state at that baseline's moment.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(vn(),yn));return t(e)})),Il("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:'Meaning-based search across items using pgvector embeddings (GTE-small, 384d).\n\nUse when atoms_search (exact/substring) misses conceptually related items.\nBest for natural-language concept queries; atoms_search is better for exact phrases or IDs.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Natural-language concept query (max 1000 chars)\n - type (string, optional): Filter by type\n - limit (number, optional): Max results, 1-50 (default 10)\n\nReturns:\n Semantically similar items ranked by cosine similarity.\n\nExamples:\n - "Find braking-related requirements" → atoms_semantic_search(project_id, "braking deceleration stopping distance")\n - "Safety-related test cases" → atoms_semantic_search(project_id, "hazard risk mitigation safety", type="test-case")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),query:o.z.string().min(1).max(1e3).describe("Natural-language concept query"),type:o.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),limit:o.z.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(Sn(),bn));return t(e)})),Hl({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, covered_via_mitigation: { count, ids }, uncovered_items: [...] }\n\n${Ti}\n\nExamples:\n - "What's our test coverage?" → atoms_get_coverage(project_id)\n - "Safety coverage gaps?" → atoms_get_coverage(project_id, domain="Safety")\n - "Coverage at PDR submission" → atoms_get_coverage(project_id, baseline_id="...")`,inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),domain:o.z.string().max(64).optional().describe("Filter by domain tag"),level:o.z.string().max(32).optional().describe("Filter by level"),baseline_id:o.z.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:o.z.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Dl("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>($n(),In));return t(e)})}),Il("atoms_verification_status",{title:"Get Release Verification Status",description:"Release-bound verification state per requirement, matching the in-app projection.\n\nEach requirement's state is derived from the runs bound to a formal Release:\nverified, failing, incomplete, or not-run, plus a stale flag and the\n(points_run / points_total) counts for its parameterized test points.\nA requirement's test cases are those linked from either side (its verified_by,\nor a test case's verifies). stale is true when the state is verified or\nincomplete and the requirement's content changed after the Release snapshot AND\nafter the newest run bound to this Release of at least one passed point of a\nlinked test case (a point of its matrix on an asset that reads passed at this\nRelease). Each such point is judged on its own: a passing run of it bound to\nthis Release after the change clears that point only, and the requirement stays\nstale until every one of them has passed again.\nThe content of a requirement is its title, its text, its item type and\nrequirement type, and the value of a project variable its text uses; a tag, a\nlink, the level, a custom field, a domain rename, turning review on and an\napproval do not change it. The app shows a stale requirement as Rerun. A row's\nstate stays verified or incomplete when its stale flag is true.\n\nArgs:\n - project_id (string, UUID): The project to report on\n - release_id (string, UUID, optional): A formal Release (a baselines row with\n a release_version). Defaults to the project's CURRENT Release\n (release_status = 'released'). Errors if the project has none.\n - include_gaps (boolean, optional, default false): Also return the not-run\n (test x unit x value) points for the Release.\n\nReturns:\n { release: {id, version, status},\n readiness: {requirements, verified, failing, incomplete, not_run, stale,\n points_total, points_run}. Each requirement is counted once:\n verified = state verified and not stale; incomplete = state incomplete\n and not stale; failing = state failing; not_run = state not-run;\n stale = state verified or incomplete and stale. A stale requirement is\n counted under stale only (never also under verified or incomplete), so\n verified + failing + incomplete + not_run + stale = requirements,\n requirements: [{requirement_id, state, stale, points_total, points_run}],\n gaps?: [{tc_id, asset, point_key}] }\n An empty requirements array with a \"hint\" field means the projection has not\n been rebuilt for this project yet, NOT that everything is unverified.\n\nExamples:\n - \"Are we ready to ship 2.0?\" → atoms_verification_status(project_id)\n - \"What's still not run for release R?\" → atoms_verification_status(project_id, release_id=\"...\", include_gaps=true)",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),release_id:o.z.string().uuid().optional().describe("Formal Release (baselines row) UUID; defaults to the project's current Release"),include_gaps:o.z.boolean().default(!1).describe("Include the not-run (test x unit x value) points for the Release")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_verification_status",async e=>{const{verificationStatusHandler:t}=await Promise.resolve().then(()=>(Mn(),qn));return t(e)})),Il("atoms_get_history",{title:"Get Item Change History",description:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_<client>) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID"),limit:o.z.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(Pn(),Dn));return t(e)})),Hl({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Shows parent-child relationships\nand requirement-to-test-case verification links.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive pan/zoom diagram.\nFalls back to Mermaid text for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to visualize\n - root_item_id (string, optional): Start node (default: all roots)\n - depth (number, optional): Max depth (default 3, max 10)\n - include_tests (boolean, optional): Show test case links (default true)\n - baseline_id (string, UUID, optional): render the graph at that baseline's moment\n - as_of (string ISO 8601, optional): render the graph at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n Mermaid graph string.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),root_item_id:o.z.string().max(20).optional().describe("Root item ID to start from"),depth:o.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:o.z.boolean().default(!0).describe("Include test case links"),baseline_id:o.z.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:o.z.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Dl("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(Gn(),Vn));return t(e)})}),Il("atoms_create_item",{title:"Create ATOMS Item",description:'Create a new requirement, test case, or note in a project.\n\nFor a hazard analysis, HARA, DFMEA or FMEA, use atoms_create_analysis instead (it creates the analysis parent and its rows). This tool does not create analysis items; do not model a hazard analysis as notes with custom fields.\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 - req_type (string, optional): requirement classification (functional|interface|performance|safety)\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 (a tag flagged as a function is not a domain and is rejected)\n - level (string, optional): System|Subsystem|Component\n - parent_ids (string[], optional): Parent item IDs to link\n - fields (object, optional): Project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field first and values must match each field type.\n\nReturns:\n Created item with generated ID (e.g., "REQ-058")\n\nSide effects:\n - Logs to change_history with actor=\'mcp_<client>\'\n - Creates relationships if parent_ids provided',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the target project"),type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),req_type:o.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe("Requirement classification (functional|interface|performance|safety). safety-goal and failure-mode are analysis rows created by atoms_create_analysis, not here."),body:o.z.string().max(5e4).optional().describe("Rich text body"),summary:o.z.string().max(2e3).optional().describe("Brief summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("Domain tags"),level:o.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:o.z.array(o.z.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional().describe("Project-field values keyed by defined field name"),echo:o.z.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Cs(),Hs));return t(e)})),ql={steps:o.z.array(o.z.object({id:o.z.string().describe("Stable step id within the item"),instruction:o.z.string().describe("What the tester does"),test_data:o.z.string().optional().describe("Optional test data for the step"),expected:o.z.string().describe("Expected result")}).passthrough()).optional().describe("Test-case script steps: array of {id, instruction, test_data?, expected}. Max 50 steps, enforced by the DB trigger."),params:o.z.array(o.z.object({name:o.z.string().describe("Parameter name; steps reference it as {name}"),unit:o.z.string().optional().describe("Optional unit (e.g. km/h, V, m)"),values:o.z.array(o.z.union([o.z.string(),o.z.number()])).describe("Value set the test sweeps")}).passthrough()).optional().describe("Matrix parameters: array of {name, unit, values[]}. Matrix points (product of value-set sizes) capped at 64 by the DB trigger.")},Il("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, req_type: Fields to update (all optional) (a tag flagged as a function is not a domain and is rejected)\n - ${ji}\n - fields (object, optional): Project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field; merged per key, "" clears a key; non-empty values must match each field type\n - steps (array, optional): Test-case script steps [{id, instruction, test_data?, expected}]. Max 50 steps (DB-enforced)\n - params (array, optional): Matrix parameters [{name, unit, values[]}]. Matrix points capped at 64 (DB-enforced)\n - expected_updated_at (string, optional): Pass metadata.updated_at from atoms_get_item to reject stale writes\n\nReturns:\n Updated item.`,inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).optional().describe("Item ID (single form)"),title:o.z.string().min(1).max(500).optional().describe("New title"),body:o.z.string().max(5e4).optional().describe("New body"),summary:o.z.string().max(2e3).optional().describe("New summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("New domain tags (a tag flagged as a function is not a domain and is rejected)"),level:o.z.string().max(32).optional().describe("New level"),status:o.z.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status, only for a test case with no runs (a test case that has runs takes its status from its newest run; use atoms_record_test_result)"),req_type:o.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe("Requirement classification (functional|interface|performance|safety). safety-goal and failure-mode are analysis rows created by atoms_create_analysis, not here."),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),...ql,expected_updated_at:wi.optional().describe("metadata.updated_at value from atoms_get_item; rejects stale writes"),echo:o.z.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:o.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:o.z.array(o.z.object({item_id:o.z.string().min(1).max(20),title:o.z.string().min(1).max(500).optional(),body:o.z.string().max(5e4).optional(),summary:o.z.string().max(2e3).optional(),domains:o.z.array(o.z.string().max(64)).max(20).optional(),level:o.z.string().max(32).optional(),status:o.z.enum(["passed","failed","blocked","not-run"]).optional(),req_type:o.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional(),fields:o.z.record(o.z.string().max(60),o.z.string().max(1e4)).optional(),...ql,expected_updated_at:wi.optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:o.z.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:o.z.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(Vs(),Ls));return t(e)})),Il("atoms_delete_item",{title:"Delete ATOMS Item",description:'Soft-delete an item (sets deleted_at, preserves for audit trail).\n\nRequires editor or admin role. The item is never truly removed.\n\nWhen ATOMS_MCP_REQUIRE_CONFIRMATION is set on the server, this tool uses a\ntwo-step flow: the first call returns a preview + confirmation_token; the\nsecond call (with the token) executes. Tokens expire in 60s and are bound\nto (tool, project_id, item_id).\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to delete\n - confirmation_token (string, optional): Token from a prior preview call\n\nReturns:\n Confirmation with deleted item summary, or { status: "confirmation_required",\n preview, confirmation_token } when the confirmation gate is active.',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:o.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Qs(),Bs));return t(e)})),Il("atoms_restore_item",{title:"Restore ATOMS Item",description:'Undo a soft-delete — restores an item that was previously deleted with atoms_delete_item.\n\nOnly works on items that have been soft-deleted (still in the database with deleted_at set).\nHas no effect if the item is not deleted. Logs the restoration to change_history.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): ID of the deleted item to restore\n\nReturns:\n Confirmation with the restored item\'s title and type.\n\nExamples:\n - "Restore the deleted requirement REQ-042" → atoms_restore_item(project_id, "REQ-042")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().max(256).describe("ID of the soft-deleted item to restore")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(Xs(),Gs));return t(e)})),Il("atoms_link_items",{title:"Link ATOMS Items",description:"Add or remove relationships between items.\n\nSingle-op form:\n - project_id, from_id, to_id, type (parent|child|related|verifies|verified_by|affects|affected_by), action (add|remove)\n - affects/affected_by (REQ-ANL-242): links a security risk analysis row (CYB-n) to an ISO 14971\n risk row (RSK-n) only; nothing is derived onto the risk row's own ratings. Any other pair is\n refused by name.\n - expected_from_updated_at? / expected_to_updated_at?: metadata.updated_at values from atoms_get_item to reject stale link commands\n - echo? false → lean {action,from_id,to_id} response\n - reason?: persisted in audit history\n\nArray form (batch link ops, same tool, much faster for restructures):\n - project_id, operations: [{action, from_id, to_id, type, expected_from_updated_at?, expected_to_updated_at?}]\n - Validated as a whole (DAG cycle check) before any write, then applied one at a time (removes before adds), NOT in a single transaction: a mid-batch failure leaves earlier operations committed and names which ones\n - reason?, idempotency_key? supported",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),from_id:o.z.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:o.z.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:o.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by"]).optional().describe("Relationship type"),action:o.z.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:wi.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:wi.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:o.z.boolean().optional().describe("false → lean response"),reason:o.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:o.z.array(o.z.object({action:o.z.enum(["add","remove"]),from_id:o.z.string().min(1).max(20),to_id:o.z.string().min(1).max(20),type:o.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by"]),expected_from_updated_at:wi.optional(),expected_to_updated_at:wi.optional()})).optional().describe("Array form: batch relationship ops, DAG-validated as a whole then applied in sequence (not one transaction); a mid-batch failure reports which ops committed."),idempotency_key:o.z.string().max(128).optional().describe("Safe retry key (24h TTL)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(ao(),eo));return t(e)})),Hl({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 (a tag flagged as a function is not a domain and is rejected)\n - level (string, optional): System|Subsystem|Component\n - parent_id (string, optional): Parent item ID to link\n\nReturns:\n { created: number, items: [{ id, title, type }], errors: [] }\n\nLimits:\n - Maximum 100 items per call\n - If any item fails, others still succeed — errors reported separately\n\nSide effects:\n - Logs to change_history with actor='mcp_<client>' for each created item\n - Creates parent relationships for items with parent_id",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the target project"),items:o.z.array(o.z.object({type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),body:o.z.string().max(5e4).optional().describe("Rich text body"),summary:o.z.string().max(2e3).optional().describe("Brief summary"),domains:o.z.array(o.z.string().max(64)).max(20).optional().describe("Domain tags"),level:o.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:o.z.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)"),confirmation_token:o.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:Dl("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(co(),no));return t(e)})}),zl={point:o.z.record(o.z.string(),o.z.union([o.z.string(),o.z.number()])).optional().describe('Matrix point this run executed, e.g. {"speed": 40}'),release_id:o.z.string().uuid().optional().describe("Formal Release to bind this run to (a baseline with a release_version)"),build:o.z.string().optional().describe("Free-text build label"),environment:o.z.string().optional().describe("Structured environment field, distinct from build"),tooling:o.z.string().optional().describe("Structured tooling field, distinct from build"),steps_rev:o.z.string().optional().describe("Item revision id the run's steps were pinned to"),step_results:o.z.array(o.z.object({step_id:o.z.string().describe("Step id from data.steps"),status:o.z.enum(["passed","failed","blocked","skipped"]).describe("Per-step status"),actual:o.z.string().optional().describe("Actual-result note"),evidence_url:o.z.string().optional().describe("Evidence URL (validated server-side)")}).passthrough()).optional().describe("Per-step results [{step_id, status, actual?, evidence_url?}]. When present the run verdict is derived server-side and the top-level result is ignored.")},Il("atoms_record_test_result",{title:"Record Test Result",description:"Record a pass/fail/blocked result for a test case.\n\nAppends to canonical items.data.runs and projects test_results from that\nhistory. Use atoms_get_item to see all results.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., \"TC-001\")\n - result (string): passed|failed|blocked|not-run\n - note (string, optional): Reason or comment for this result\n - asset (string, optional): Asset identifier this run was executed against\n (VIN, module ID, lot number, serial number, etc). Max 200 chars.\n Auto-trimmed; empty/whitespace is treated as omitted. If the asset\n name does not yet exist in the project, it is auto-registered.\n - point, release_id, build, environment, tooling, steps_rev (optional):\n run metadata. release_id must be a formal Release (a baseline with a\n release_version). All validated server-side.\n - step_results (array, optional): per-step outcomes for a stepped run.\n When provided, the verdict is derived server-side from the steps.\n\nReturns:\n Recorded result with the stored run_at (server time at microsecond\n precision, never the caller's clock). When asset is provided, also returns\n asset_id and asset_created.\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts into assets table if asset name is new in this project\n - Logs to change_history with actor='mcp_<client>'",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:o.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:o.z.string().max(500).optional().describe("Reason or comment for this result"),asset:o.z.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new."),...zl},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(uo(),lo));return t(e)})),Il("atoms_record_test_results",{title:"Record Test Results (bulk)",description:'Record many runs on one test case in a single atomic call.\n\nOptimized for multi-asset campaigns. Each entry can have its own asset and\nresult. Asset lookup-or-create happens per entry; new asset names are\nauto-registered. Runs are appended to canonical items.data.runs, then\ntest_results is projected from that history. The whole call is one DB\ntransaction; any entry failure rolls back the rest.\n\nUse the singular atoms_record_test_result for one-off runs.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., "TC-001")\n - results (array, 1-100 entries): Each entry has:\n - asset (string, optional): Asset identifier (VIN, module ID, lot)\n - result (string, required): passed|failed|blocked|not-run\n - note (string, optional): Run note\n - date (string, optional): IGNORED. Every run is stamped with server time\n when it is recorded; a supplied date is reported in the\n response warning, never stored. The entries of one call are stamped\n one microsecond apart in the order sent and stored newest-first, so\n the LAST entry is the newest run.\n - point, release_id, build, environment, tooling, steps_rev (optional):\n run metadata; release_id must be a formal Release. Server-validated.\n - step_results (array, optional): per-step outcomes; when present the\n verdict is derived server-side from the steps.\n\nReturns:\n Per-entry outcomes with asset_id, asset_created, run_at (the stored server\n time), ok flags, and a warning (with ignored_date_entries) when any entry\n supplied a date.\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts new rows into assets for any asset name not already registered\n - Logs a single change_history entry summarizing the batch',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:o.z.array(o.z.object({asset:o.z.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:o.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:o.z.string().max(500).optional().describe("Run note"),date:o.z.string().optional().describe("Ignored: runs are stamped with server time. A supplied date is reported in the response warning, never stored."),...zl})).min(1).max(100).describe("1 to 100 result entries on this test case")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_record_test_results",async e=>{const{recordTestResultsBulkHandler:t}=await Promise.resolve().then(()=>(wo(),mo));return t(e)})),Hl({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:'Walk the traceability graph from a starting item.\n\nAnswers questions like "which requirements does TC-003 verify?" or\n"if I change REQ-001, what\'s affected downstream?"\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive graph visualization.\nFalls back to flat list for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Starting item ID\n - direction (string): upstream|downstream|both\n - upstream: follow parent/verifies links (dependencies)\n - downstream: follow child/verified_by links (dependents)\n - both: trace in both directions\n - depth (number, optional): Max traversal depth (default 5, max 10)\n - relationship_types (string[], optional): Filter to specific types (parent, child, related, verifies, verified_by, mitigated_by, mitigates)\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], total_count }\n\nExamples:\n - "What does TC-003 verify?" → atoms_trace(project_id, "TC-003", "upstream")\n - "What\'s affected by REQ-001?" → atoms_trace(project_id, "REQ-001", "downstream")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Starting item ID"),direction:o.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:o.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:o.z.array(o.z.enum(["parent","child","related","verifies","verified_by","mitigated_by","mitigates","affects","affected_by"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Dl("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(So(),jo));return t(e)})}),Il("atoms_list_assets",{title:"List Project Assets",description:"List asset identifiers registered in a project.\n\nAssets are free-form per-instance IDs (VINs, module names, lot numbers,\nserial numbers) that test runs are tagged against. They are auto-registered\nthe first time they appear on a run via atoms_record_test_result.\n\nArgs:\n - project_id (string, UUID): Project to list assets for\n - include_archived (boolean, optional): Include archived assets (default false)\n\nReturns:\n { assets: [{ id, name, archived_at, created_at }], total }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),include_archived:o.z.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(Eo(),Ao));return t(e)})),Il("atoms_list_variables",{title:"List Project Variables",description:"List all parameterized variables defined in a project.\n\nVariables are shared values (e.g., backup_camera_latency = 2s) that can be\nreferenced in requirement bodies as {variable_name}.\n\nArgs:\n - project_id (string, UUID): Project to list variables for\n - baseline_id (string, UUID, optional): list variables as they were at that baseline\n - as_of (string ISO 8601, optional): list variables as they were at that moment\n - limit (number, optional): max results (default 50, max 200)\n - offset (number, optional): pagination offset (default 0)\n\nReturns:\n { variables: [{ id, name, value, unit, description }], total }, meta: { total_count, limit, offset, has_more }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:o.z.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(Co(),Io));return t(e)})),Il("atoms_get_variable",{title:"Get Project Variable",description:'Get a specific variable by name, including which items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name (e.g., "backup_camera_latency")\n - baseline_id (string, UUID, optional): get the variable as it was at that baseline\n - as_of (string ISO 8601, optional): get the variable as it was at that moment\n\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).max(64).describe("Variable name"),baseline_id:o.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:o.z.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(Co(),Io));return t(e)})),Il("atoms_update_variable",{title:"Update Project Variable",description:"Update a variable's value, unit, or description.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name\n - value (string, optional): New value\n - unit (string, optional): Unit abbreviation (e.g., 's', 'Hz')\n - description (string, optional): Human-readable description\n\nReturns:\n { variable }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).max(64).describe("Variable name"),value:o.z.string().max(500).optional().describe("New value"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(Co(),Io));return t(e)})),Il("atoms_create_variable",{title:"Create Project Variable",description:'Create one or many parameterized variables for a project.\n\nSingle form: provide name + value.\nArray form: provide variables[] for bulk creation (one atomic INSERT).\n\nVariables can then be embedded in requirement bodies as {variable_name}.\n\nArgs (single form):\n - project_id (string, UUID): Project to add the variable to\n - name (string): Variable name, letters, digits, underscores; must start with letter/underscore\n - value (string): Initial value (e.g., "100", "true", "nominal")\n - unit (string, optional): Unit abbreviation (e.g., "Hz", "ms", "m/s²")\n - description (string, optional): Human-readable description\n - echo (bool, optional): false → lean {name} response (default true)\n\nArgs (array form):\n - project_id (string, UUID): Project UUID\n - variables[]: Array of { name, value, unit?, description? }\n - echo (bool, optional): false → lean {name} list (default true)\n - idempotency_key (string, optional): Dedup key\n\nReturns (single): { variable, message }\nReturns (array): { batch_id, created, variables, message }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).optional().describe("Variable name (single form)"),value:o.z.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description"),echo:o.z.boolean().optional().describe("false → lean response (default true)"),variables:o.z.array(o.z.object({name:o.z.string().min(1).max(64).describe("Variable name"),value:o.z.string().min(1).max(500).describe("Initial value"),unit:o.z.string().max(32).optional().describe("Unit abbreviation"),description:o.z.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:o.z.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(Co(),Io));return t(e)})),Il("atoms_delete_variable",{title:"Delete Project Variable",description:"Delete a project variable. Refuses by default if any items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - name (string): Variable name to delete\n - force (bool, optional): Delete even if items still reference it (default false)\n\nReturns:\n { deleted, name, referenced_by_items, warning? }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Variable name to delete"),force:o.z.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:o.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(Co(),Io));return t(e)})),Il("atoms_list_domains",{title:"List Project Domains",description:"List the domain tags of a project's taxonomy, with item counts.\n\nA tag flagged as a FUNCTION (metadata.function_tags, the seed of a HARA row) is not a domain: it is\nleft out of this list, exactly as the app's domain picker leaves it out, because atoms_create_item,\natoms_update_item and atoms_bulk_import refuse it as a domain. Such tags are named in\nexcluded_function_tags; use them through atoms_create_analysis source_functions or atoms_fill_row\nsource_function. To turn one back into a domain, call atoms_update_domain with is_function=false.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { domains: [{ name, registered, item_count }], total, registered_count, unregistered_count,\n excluded_function_tags: string[], note? }\n registered: false marks a tag found on items but not in the taxonomy (an orphan); a flagged tag\n an item still carries is a function on that item, never counted as an orphan.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(Bo(),Po));return t(e)})),Il("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.\nA name that is already a function is refused (a function is not a domain tag): unflag it first with atoms_update_domain is_function=false.\n\nArgs:\n - project_id (string, UUID): Project to add the domain to\n - name (string): Domain name (lowercased automatically, e.g., "safety", "can-bus")\n\nReturns:\n { domain: { name }, message }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(Bo(),Po));return t(e)})),Il("atoms_list_levels",{title:"List Project Levels",description:"List the project's level taxonomy in order, with each level's L# (positional index) and item count.\n\nArgs:\n - project_id (string, UUID): Project to list levels for\n\nReturns:\n { levels: [{ name, prefix, item_count }], total }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(us(),rs));return t(e)})),Il("atoms_create_level",{title:"Create Project Level",description:'Register a new level in the project taxonomy so items can be tagged with it and it shows in the Strata view. Appended to the ordered level list; its L# is the next index. Names are user-defined labels (lowercased automatically); matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID): Project to add the level to\n - name (string): Level name, e.g. "feature", "system", "subsystem"\n\nReturns:\n { level: { name, prefix }, message }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(us(),rs));return t(e)})),Il("atoms_delete_level",{title:"Delete Project Level",description:"Delete an UNUSED level from the project taxonomy. Refuses if any item still uses the level (re-tag those items with atoms_update_item first). A level is positional, so deleting one shifts every later level's L# down by one. Matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID)\n - name (string): the level to delete\n - confirmation_token (string, optional): from the first call, when confirmation is required\n\nReturns:\n { level: { name }, remaining_levels, message } — or a confirmation_required payload",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Level name to delete"),confirmation_token:o.z.string().optional().describe("Token from the first (preview) call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_delete_level",async e=>{const{deleteLevelHandler:t}=await Promise.resolve().then(()=>(us(),rs));return t(e)})),Il("atoms_reorder_levels",{title:"Reorder Project Levels",description:"Reorder the project's levels. Provide every existing level name exactly once, in the order you want them (any casing). L# is positional, so this changes every level's L# wherever it renders (Strata, sidebar, exports). Touches no item.\n\nArgs:\n - project_id (string, UUID)\n - names (string[]): every existing level name, in the new order\n\nReturns:\n { levels: [{ name, prefix }], message }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),names:o.z.array(o.z.string().min(1).max(64)).min(1).describe("Every existing level name, in the desired order")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_reorder_levels",async e=>{const{reorderLevelsHandler:t}=await Promise.resolve().then(()=>(us(),rs));return t(e)})),Il("atoms_list_fields",{title:"List Project Fields",description:'List the project\'s custom field definitions (project-scoped key-value slots on items, e.g. "Verification Method"), with counts of items carrying a value.\n\nField values are set per item via atoms_create_item / atoms_update_item fields.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { fields: [{ name, type, options, item_count }], total }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(Ts(),ys));return t(e)})),Il("atoms_create_field",{title:"Create Project Field",description:'Define a project custom field so items can carry a value for it (shown as a Matrix column, e.g. "Verification Method").\n\nThe name keeps its casing; uniqueness is case-insensitive. Type is one of text, long, bool, date, person, select, number, link. Select fields require options. Field definitions never carry visibility rules, permissions, or workflow logic. A definition applies to every item type unless appliesTo restricts it (requirement|test-case|note|table).\n\nArgs:\n - project_id (string, UUID): Project to define the field in\n - name (string): Field name, 1-60 characters (e.g. "Verification Method", "Essential Output?")\n - type (string, optional): Defaults to text\n - options (string[], optional): Required when type=select\n - scope (string, optional): project (default) or organization (org admin only)\n - appliesTo (string[], optional): item types the field shows on (requirement|test-case|note|table); omit for all types\n\nReturns:\n { field: { name, type, options }, message }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:o.z.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:o.z.array(o.z.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:o.z.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization"),appliesTo:o.z.array(o.z.enum(["requirement","test-case","note","table"])).max(4).optional().describe("Item types this field shows on (requirement|test-case|note|table); omit for all types")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(Ts(),ys));return t(e)})),Il("atoms_delete_field",{title:"Delete Project Field",description:"Delete a project field definition. Existing item values are left in item JSON but no longer render as Matrix columns until a matching field is created again.\n\nArgs:\n - project_id (string, UUID): Project containing the field\n - name (string): Field name to delete",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(60).describe("Field name")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(Ts(),ys));return t(e)})),Il("atoms_reorder_fields",{title:"Reorder Project Fields",description:"Reorder project field definitions. Definition order drives the Column Picker listing and a fresh user's Matrix column order.\n\nOrdering only: no definition is added, dropped, renamed, or retyped, and no item value moves. Use this instead of deleting and recreating definitions to change their order.\n\nArgs:\n - project_id (string, UUID): Project containing the fields\n - names (string[]): Every existing field name exactly once, in the order you want them. A list that is not a permutation of the current names is refused, not partially applied.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),names:o.z.array(o.z.string().min(1).max(60)).describe("Every existing field name exactly once, in the desired order")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(Ts(),ys));return t(e)})),Il("atoms_update_domain",{title:"Update Project Domain",description:"Rename a domain tag, or flag it as a function and unflag it again. Pass exactly one of new_name or is_function.\n\nRename (new_name): updates the taxonomy and propagates to all tagged items. Use dry_run=true first to see how many items will be affected before committing.\n\nFlag (is_function=true): makes a registered domain a function, the seed of a HARA row (atoms_create_analysis source_functions, atoms_fill_row source_function). A tag is a domain or a function, never both: the flagged tag leaves the Domains group, items that already carry it keep the tag, and no new item can take it as a domain until it is unflagged. Using a domain as a function never flags it as a side effect: atoms_create_analysis, atoms_fill_row and atoms_propose_rows refuse it until you flag it here.\n\nUnflag (is_function=false): turns a function back into a domain, so items can be tagged with it again. Analysis rows that name it as their function keep the name as text (they are not changed) and the answer counts them; flag it again to restore the Functions listing.\n\ndry_run=true previews either change and changes nothing.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Current domain name (or function name, to unflag it)\n - new_name (string, optional): New domain name (rename)\n - is_function (bool, optional): true flags the domain as a function, false unflags a function back to a domain\n - dry_run (bool, optional): If true, return the impact without making changes (default false)\n\nReturns (rename, dry_run=false):\n { domain: { name }, renamed_from, items_updated, message }\n\nReturns (rename, dry_run=true):\n { dry_run: true, rename: { from, to }, items_affected, message }\n\nReturns (is_function=true):\n { domain: { name }, is_function: true, changed, items_carrying_tag, message }\n\nReturns (is_function=false):\n { domain: { name }, is_function: false, changed, analysis_rows_using_function, message }\n\nWith dry_run=true a flag change returns the same fields plus dry_run: true and changes nothing.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Current domain name (or function name, to unflag it)"),new_name:o.z.string().min(1).max(64).optional().describe("New domain name (rename)"),is_function:o.z.boolean().optional().describe("true flags the domain as a function, false unflags a function back to a domain"),dry_run:o.z.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(Bo(),Po));return t(e)})),Il("atoms_delete_domain",{title:"Delete Project Domain",description:"Delete a domain tag from the project taxonomy.\n\nRefuses by default if any items are tagged with it. With force=true, deletes the\ndomain and strips the tag from all items.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Domain name to delete\n - force (bool, optional): Strip from items and delete anyway (default false)\n\nReturns:\n { deleted, name, items_updated, message }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(64).describe("Domain name to delete"),force:o.z.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:o.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(Bo(),Po));return t(e)})),Hl({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\n${Hi}\n\nExamples:\n - "Give me a compliance snapshot" → atoms_project_summary(project_id)\n - "How's our test coverage?" → atoms_project_summary(project_id)`,inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Dl("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(Yo(),Jo));return t(e)})}),Hl({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:'View and filter items in an ATOMS project with a visual browser.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive filterable list\nwith expandable item details. Falls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to browse\n - type (string, optional): Filter by type (requirement, test-case, note, table)\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - query (string, optional): Full-text search query\n - limit (number, optional): Max results (default 25, max 100)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { items: [...], filters: { domains, levels, types }, meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me the requirements" → atoms_browse(project_id, type="requirement")\n - "Browse safety items" → atoms_browse(project_id, domain="Safety")\n - "Find braking requirements" → atoms_browse(project_id, query="braking")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),domain:o.z.string().max(64).optional().describe("Filter by domain tag"),level:o.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:o.z.string().max(1e3).optional().describe("Full-text search query"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Dl("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(ac(),Ko));return t(e)})}),Il("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:'Analyze the blast radius of changing a specific item.\n\nTraverses the relationship graph from the given item and returns every item that\nwould be affected by a change — with their types, depths, and full relationship paths.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to analyze (e.g., "REQ-001")\n - direction (string, optional): "downstream" (default) | "upstream" | "both"\n - downstream: what this item affects (children, verified_by)\n - upstream: what affects this item (parents, verifies)\n - both: full bidirectional traversal\n - depth (integer, optional): Max traversal depth. Omit for full depth (all reachable nodes).\n - include_variable_refs (boolean, optional): Reserved for future variable-aware impact. Default true.\n\nReturns:\n { root: { item_id, title, type }, impacted_items: [{ item_id, title, type, depth, relationship_path }], summary: { total_impacted, by_type, max_depth_reached } }\n\nExamples:\n - "What breaks if I change REQ-001?" → atoms_impact_analysis(project_id, "REQ-001")\n - "What\'s upstream of TC-005?" → atoms_impact_analysis(project_id, "TC-005", direction="upstream")\n - "Show direct dependencies only" → atoms_impact_analysis(project_id, "REQ-001", depth=1)\n\nErrors:\n - "Item not found" → verify item_id exists in the project',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:o.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:o.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:o.z.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(uc(),ic));return t(e)})),Il("atoms_list_baselines",{title:"List ATOMS Baselines",description:"List named baselines (named project snapshots) for a project, newest first.\n\nA baseline is a labeled moment in time. Use atoms_create_baseline to make one,\natoms_diff_baselines to compare two, and atoms_restore_baseline to roll back.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),limit:o.z.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(Fc(),Rc));return t(e)})),Il("atoms_create_baseline",{title:"Create ATOMS Baseline",description:"Create a named baseline (snapshot label) at the current moment for a project.\n\nThe baseline records a name + timestamp. It does NOT copy item data; the project\nstate at that moment is reconstructed via temporal queries against item_revisions.\nNames must be unique per project (case-insensitive).",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),name:o.z.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:o.z.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(Fc(),Rc));return t(e)})),Il("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:"Lock a baseline so it becomes audit-grade immutable. Admin only. One-way: there is no unlock.\n\nAfter locking, the baseline's name, description, and snapshot_at cannot be changed,\nand it cannot be deleted. Use for regulatory submissions and DRBs.",inputSchema:{baseline_id:o.z.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(Fc(),Rc));return t(e)})),Il("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. Each modified item lists the\nnames of the fields that changed in fields_changed. With detail=true each modified item also carries a diff object keyed by every name in fields_changed, each with the from and to values. Under data, a list such as steps or runs holds only the entries that differ, keyed by the entry id (by position when entries have no id), with order giving each side's id sequence when it changed. A detail=true page is bounded to 20000 characters of items: when items are left out, page_info carries truncated: true and next_offset, so call again with that offset for the rest. Slower for large projects.",inputSchema:{baseline_a_id:o.z.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:o.z.string().uuid().describe("UUID of the second (newer) baseline"),detail:o.z.boolean().default(!1).describe("Add a per-field from/to diff object to each modified item (default false)"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(Fc(),Rc));return t(e)})),Il("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:"Restore project state to a baseline. Admin only. Preview-by-default.\n\nCall with confirm=false (default) for a dry run that returns items_to_restore count.\nCall with confirm=true to execute: each item present at the baseline gets a new\nrevision matching its historical state, event_source='restore'. Items added AFTER\nthe baseline are NOT deleted. Always recoverable via further history.",inputSchema:{baseline_id:o.z.string().uuid().describe("UUID of the baseline to restore from"),confirm:o.z.boolean().default(!1).describe("Set true to execute; false (default) returns a preview")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(Fc(),Rc));return t(e)})),Il("atoms_create_analysis",{title:"Create Analysis (HARA, Risk analysis, FMEA)",description:'Create a new analysis (a HARA under ISO 26262, a Risk analysis under ISO 14971, a Security risk\nanalysis under AAMI TIR57 (subtype security_risk, or hara with variant tir57), a DFMEA, a PFMEA,\na Software FMEA or a Use FMEA) with one empty row per seed. The analysis carries its standard:\nthe subtype and the variant name it, and a project may hold analyses under both standards.\n\nRequires editor or admin role. Structure matches analyses created in the ATOMS web app.\nA hara (HARA or risk analysis) is seeded from FUNCTIONS (tags flagged as functions), never from\nrequirements: a requirement is an output of the analysis. A dfmea (DFMEA or FMEA) is seeded from\nrequirements / design elements; a PFMEA from a process step.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Target project\n - subtype (string): hara | dfmea | risk_analysis | fmea. risk_analysis is an alias of hara and\n fmea an alias of dfmea, so a medical user never has to say HARA or DFMEA.\n hazard_analysis is still accepted as the older name of risk_analysis.\n - variant (string, optional): the standard the analysis carries. hara: iso26262 | iso14971;\n risk_analysis implies iso14971; dfmea: design | process | software | use; fmea implies\n process (the PFMEA). A variant outside the subtype\'s family is refused by name. Every variant\n is accepted in every project. Name none and the default follows the project\'s industry\n setting, exactly as the create menu in the app does: automotive gives hara iso26262 and dfmea\n design, medical device gives hara iso14971 and dfmea process. The variant is stored on the\n analysis and selects its scheme for every later read and write; the setting is only the\n default and never changes an analysis that already exists.\n - title (string, optional): Analysis title (default "New <parent label>": "New HARA",\n "New Risk analysis", "New DFMEA", "New PFMEA", "New Software FMEA", "New Use FMEA")\n - source_functions (string[], hara only, max 50): Function names to seed rows from. A name\n absent from the project\'s tags is registered as a function-flagged tag; a name that is\n already a domain is refused, never flagged (flag it first: atoms_update_domain with\n is_function=true); matching is case-insensitive and trimmed. Rejected for dfmea.\n - source_req_ids (string[], dfmea only, max 50): Requirement IDs to seed rows from.\n Each must exist, be a plain requirement, and not itself be an analysis row. Rejected for hara.\n - revision (string, optional): Revision label (default "1.0")\n - intended_use (string, optional, ISO 14971 risk analysis only): what the device is for, for\n which patient, by which user and in which environment (ISO 14971:2019 5.2).\n - foreseeable_misuse (string, optional, ISO 14971 risk analysis only): the reasonably\n foreseeable misuse, ONE CASE PER LINE (ISO 14971:2019 5.2).\n - safety_characteristics (string, optional, ISO 14971 risk analysis only): the characteristics\n related to safety, ONE PER LINE (ISO 14971:2019 5.3).\n The three scope fields are the analysis\'s, not a row\'s. They are refused by name on a scheme\n that carries no scope (a HARA, a DFMEA, an FMEA), and they can be written later on the\n analysis id with atoms_fill_row.\n The stored subtype and the row req_types are the same under every standard; ids follow the\n scheme: HARA-n / SG-n (hara_iso26262), RA-n / RSK-n (hazard_iso14971), DFMEA-n / FM-n (dfmea_rpn),\n PFMEA-n / PF-n (fmea_process), SFMEA-n / FM-n (fmea_software), UFMEA-n / FM-n (fmea_use).\n\nReturns:\n { id (e.g. "HARA-001", "RA-001", "PFMEA-001"), subtype, title, revision,\n standard? ("ISO 26262" | "ISO 14971" for a hara; "AIAG-VDA FMEA Handbook" for a DFMEA or PFMEA;\n absent for a Software FMEA or a Use FMEA), scheme, variant,\n labels: { parent, row, row_statement, mitigating_requirement, lane, level },\n rows: [{ id, source_function }] (hara) | [{ id, source_req }] (dfmea),\n link_warnings?: [{ row_id, source_function | source_req, message }], warning? }\n rows lists every created row. If any row could not be attached to the analysis, it is\n named in link_warnings and warning explains the repair (atoms_link_items with type\n \'parent\', from_id=<row id>, to_id=<analysis id>); such rows will not appear in\n atoms_get_analysis until relinked.\n\nSide effects:\n - Creates the analysis parent item plus one row item per seed (row ids follow the scheme: SG-n or RSK-n, FM-n or PF-n)\n - hara: registers new function names in the project\'s tags and function flags (metadata)\n - Links each row to the parent (dual-written to the relationship shadow table)\n - Logs each created item to change_history with actor=\'mcp_<client>\'',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the target project"),subtype:o.z.enum(["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"]).describe("Analysis subtype; risk_analysis is an alias of hara and fmea of dfmea, hazard_analysis is still accepted as the older name of risk_analysis, and security_risk names the AAMI TIR57 security risk analysis (implies variant tir57) (REQ-ANL-192, REQ-ANL-245)"),title:o.z.string().min(1).max(500).optional().describe("Analysis title"),source_functions:o.z.array(o.z.string().min(1).max(100)).max(50).optional().describe("hara only: function names to seed rows from (0-50); new names are registered as function-flagged tags"),source_req_ids:o.z.array(o.z.string().min(1).max(20)).max(50).optional().describe("dfmea only: requirement IDs to seed rows from (0-50)"),revision:o.z.string().min(1).max(32).optional().describe("Revision label (default 1.0)"),variant:o.z.enum(["iso26262","iso14971","tir57","design","process","software","use"]).optional().describe("The standard the analysis carries (REQ-ANL-212). hara: iso26262 | iso14971 | tir57; dfmea: design | process | software | use. risk_analysis implies iso14971, fmea implies process, security_risk implies tir57. Omit it and the default follows the project industry setting (REQ-ANL-216)."),intended_use:o.z.string().max(1e4).optional().describe("ISO 14971 risk analysis only: what the device is for, for which patient, by which user and in which environment (ISO 14971:2019 5.2)."),foreseeable_misuse:o.z.string().max(1e4).optional().describe("ISO 14971 risk analysis only: the reasonably foreseeable misuse, one case per line (ISO 14971:2019 5.2)."),safety_characteristics:o.z.string().max(1e4).optional().describe("ISO 14971 risk analysis only: the characteristics related to safety, one per line (ISO 14971:2019 5.3)."),threat_model_method:o.z.string().max(1e4).optional().describe("Security risk analysis only: the threat modeling methodology used, e.g. STRIDE."),threat_model_rationale:o.z.string().max(1e4).optional().describe("Security risk analysis only: why that methodology was chosen."),environment_assumptions:o.z.string().max(1e4).optional().describe("Security risk analysis only: assumptions about the operating environment, one per line."),attack_surfaces:o.z.string().max(1e4).optional().describe("Security risk analysis only: interfaces and entry points considered, one per line."),related_documents:o.z.string().max(1e4).optional().describe("Security risk analysis only: where the SBOM, the security testing report and the architecture views live.")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_fill_row",{title:"Fill Analysis Row Fields",description:'Fill fields on one analysis row: a HARA or risk analysis row, a security risk analysis row, a DFMEA or FMEA row (row ids follow the scheme: SG-n or RSK-n, CYB-n, FM-n or PF-n).\n\nRequires editor or admin role. Written fields are marked as MCP-sourced so the\nweb app shows their provenance. The computed level (ASIL, RPN or Risk) is derived and\nnever stored: asil is never a writable key.\n\nA security risk analysis row (CYB-n) accepts threat_event, vulnerability, impact, harm,\nseverity, exploitability (E: the ease of exploiting the vulnerability across the device\nlifecycle; it is NOT a probability), residual_s, residual_e, s_rationale, e_rationale,\njustification, safety_goal (the security control statement), safety_impact (Yes|No),\nsafety_impact_justification, source_function (the asset), assumptions and rationale. It\nrefuses p1, p2, occurrence and detection by name (those belong to the other schemes).\n\nrow_id may also name the ANALYSIS PARENT (e.g. "RA-001", "SEC-001"), which carries the\nanalysis\'s own fields rather than a row\'s: on an ISO 14971 risk analysis exactly intended_use,\nforeseeable_misuse, safety_characteristics (its scope, ISO 14971:2019 5.2 and 5.3),\noverall_residual_risk (Low | Medium | High) with overall_residual_rationale (its overall\nresidual risk, ISO 14971:2019 clause 8) and software_safety_class (A | B | C) with\nsoftware_safety_rationale (IEC 62304 4.3); on a security risk analysis exactly\nthreat_model_method, threat_model_rationale, environment_assumptions, attack_surfaces,\nrelated_documents, lifecycle_sources (a JSON array of [name, considered, note] tuples) and\noverall_residual_risk (Very Low | Low | Moderate | High | Very High) with\noverall_residual_rationale. Any other key on a parent is refused by name with that list\ngiven, and a scheme that carries no parent field (a HARA, a DFMEA, an FMEA) refuses all of\nthem. Both judged values are a PERSON\'s: nothing computes them, the empty string clears\none, and the app only ever suggests one from the rows.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. "SG-001", "RSK-002", "FM-003", "PF-004"), or the\n analysis parent ID (e.g. "RA-001") to write the analysis\'s scope and overall judgement\n - fields (object): Field name to value map. Allowed keys:\n hara: failure_mode, operating_scenario, hazard, assumptions, severity (S0-S3), exposure (E0-E4),\n controllability (C0-C3), safe_state, ftti, rationale, source_function, effect, title\n dfmea: failure_mode, cause, severity (1-10), occurrence (1-10), detection (1-10),\n rationale, effect\n medical risk analysis: failure_mode (the hazard), operating_scenario (the sequence of events),\n hazard (the harm), assumptions, severity (1-5), p1 (1-5), p2 (1-5), rationale, source_function,\n safety_goal (the risk control statement), s_rationale, p1_rationale, p2_rationale,\n residual_s, residual_p1, residual_p2, benefit_note, effect\n medical FMEA: the FMEA keys of its variant; a PFMEA adds process_step and current_controls,\n and a Software FMEA has NO occurrence (fixed at 10, IEC 62304).\n The analysis carries its standard: the variant stored on the row\'s parent analysis selects\n the scheme (an analysis stored before v5.4 without one resolves through the project\'s legacy hint).\n The derived level (asil / rpn / risk / p0) and the approval keys (approved, approved_at,\n approved_by, approved_note, field_source, link_roles, mitigation_types) are refused BY NAME.\n A suggested rating is written together with its rationale: pass the rating and its evidence\n field in one call (severity + s_rationale, p1 + p1_rationale), or use atoms_suggest_field.\n \'effect\' writes the row\'s long text body (the hazardous event of a HARA row, the hazardous situation\n of a medical risk analysis row, the effect of an FMEA row). dfmea failure_mode also\n becomes the row title. dfmea ratings accept numbers and are stored as strings.\n hara failure_mode: the standardized suggestions are No function, Loss of function, Partial function,\n Degradation of function, Misinterpretation of function (a suggestion; any text is accepted).\n hara source_function: the function the row analyzes, registered as a function-flagged tag if new;\n a name that is already a domain is refused, never flagged (atoms_update_domain is_function=true).\n\nReturns:\n { row_id, subtype, written_fields, computed_level, asil_propagated_to?, approval_cleared? }\n approval_cleared: true means the row WAS approved and this write cleared approved, approved_by,\n approved_at and approved_note: a signature never covers content the approver did not see. A\n person approves the row again with atoms_approve_row once they have read the new values.\n On the analysis parent instead: { analysis_id, scheme, written_fields,\n scope: { intended_use, foreseeable_misuse: string[], safety_characteristics: string[] },\n overall: { residual_risk, residual_rationale, safety_class, safety_rationale } }.\n\nSide effects:\n - Saves the row with stale-write protection and logs to change_history\n - On an approved row: clears the approval (history-logged with the reason)\n - ISO 26262 HARA only (scheme hara_iso26262): if the row is linked and its computed ASIL changed,\n updates each linked requirement\'s asil / asil_source (each update is history-logged). asil is an\n ISO 26262 field: a row of an ISO 14971 risk analysis or of a TIR57 security risk analysis never\n writes it (REQ-ANL-257)',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003), or the analysis parent ID (e.g. RA-001) for its scope and overall residual risk"),fields:o.z.record(o.z.string().max(64),o.z.union([o.z.string().max(5e4),o.z.number()])).describe("Field name to value map (see description for allowed keys per subtype)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_get_analysis",{title:"Get Analysis",description:'Get a full analysis view: every row with its computed level (ASIL, RPN or Risk, by the\nanalysis\'s scheme) and gap / critical / stale classifications, plus summary counts and the\nscheme\'s vocabulary.\n\nClassifications match the ATOMS web app exactly (same rules, same thresholds). The analysis\ncarries its standard: the variant stored on it selects the scheme (a hara is a HARA under\nISO 26262 or a Risk analysis under ISO 14971; a dfmea is a DFMEA, a PFMEA, a Software FMEA or\na Use FMEA). An analysis stored before v5.4 without a variant resolves through the project\'s\nlegacy hint and reads variant null.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "RA-001", "PFMEA-002")\n\nReturns:\n { analysis: { id, title, subtype, scheme, revision, standard, variant,\n labels: { parent, row, row_statement, mitigating_requirement, lane, level },\n acceptability: { Low, Medium, High } | null (the ISO 14971 wording per risk level, e.g. High is\n "Not acceptable"; null on every scheme but the medical risk analysis),\n definitions: [{ key, text }] (the scheme\'s glossary, the text the app\'s tooltips show),\n control_types: [{ id, abbr, label, precedence }] (ISO 14971 clause 7, applied in precedence\n order; empty on the automotive schemes),\n field_labels: [{ key, label }] (each raw row key to the label this scheme shows for it, e.g. in a\n medical risk analysis failure_mode is "Hazard", effect is "Hazardous situation" and hazard is\n "Harm"; read the raw keys through this list, never as automotive words),\n scope: { intended_use, foreseeable_misuse: string[], safety_characteristics: string[] } | null\n (the analysis\'s scope, ISO 14971:2019 5.2 and 5.3; the two lists are the stored lines, blank\n lines dropped; null on a scheme that carries no scope),\n overall: { residual_risk, residual_rationale, safety_class, safety_rationale } | null\n (the overall residual risk a person judged, ISO 14971:2019 clause 8, and the IEC 62304 4.3\n software safety class; an unjudged value reads as the empty string; null on a scheme that\n carries neither),\n threat_model: { stated, method, rationale, environment_assumptions: string[], attack_surfaces: string[],\n lifecycle_sources: [{ name, considered, note }], related_documents } | null (security risk\n analysis only; null on every other scheme),\n acceptance: { acceptance_state, accepted_by, accepted_at, acceptance_note,\n open_gaps_at_acceptance: [{ kind, label }] } (REQ-ANL-249: the analysis-level acceptance\n record; a parent never accepted reads acceptance_state "draft" with an empty gap list,\n never null) },\n rows: [{ id, title, source_req, effect, <the scheme\'s fields under their raw keys>,\n computed_level, computed_level_text (the acceptability wording behind the level, or null),\n is_gap, gap_rule, is_critical, is_stale, mitigated_by, link_roles, mitigation_types,\n verified_by, residual_level (medical risk analysis and security risk analysis only; null\n elsewhere),\n approved, approved_at, approved_by, approved_note, mcp_fields }],\n counts: { rows, gaps, critical, stale, approved, linked } }\n The vocabulary lists are given once per analysis, never repeated per row.',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),analysis_id:o.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:'Link a HARA / risk analysis / FMEA row to the technical requirement that mitigates it (the\nsafety requirement of a HARA row, the risk control of a medical row, the action of an FMEA row).\n\nRequires editor or admin role.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing both items\n - row_id (string): Analysis row ID (e.g. "SG-001", "RSK-002", "FM-003", "PF-004")\n - req_id (string): Target requirement ID (must be a plain requirement, not an analysis row)\n hara / medical risk analysis rows: the target must be a requirement of req_type \'safety\'\n (a safety requirement / risk control); any other requirement is refused with the rule\n named (REQ-ANL-142). An FMEA row accepts any requirement, so long as role is given.\n - control_type (string, medical and security schemes only, REQUIRED there): inherent | protective | information\n (ISO 14971 clause 7: inherently safe design, protective measure, information for safety), or on a security risk analysis row (CYB-n, AAMI TIR57) one of the eight FDA Appendix 1 categories: authentication | authorization | cryptography | code_data_execution_integrity | confidentiality | event_detection_logging | resiliency_recovery | firmware_software_updates (REQ-ANL-241).\n Stored on the LINK (the row\'s analysis_props.mitigation_types keyed by req_id), never on the\n requirement. The analysis carries its standard: control_type is required exactly when the\n row\'s resolved scheme is medical (hazard_iso14971, fmea_process, fmea_software, fmea_use: a\n risk analysis, PFMEA, Software FMEA or Use FMEA link carries one) and refused on a HARA\n (ISO 26262) or a DFMEA row.\n - role (string, dfmea rows only, REQUIRED there): prevention | detection | mitigation.\n Must be omitted for hara rows (a HARA or a risk analysis).\n - override (boolean, optional, default false): ISO 26262 HARA only. When the target\n already carries a different ASIL, the call fails with a structured error\n (details.code=\'asil_conflict\') unless override=true; the override is\n history-logged like a dialog accept.\n\nReturns:\n { row_id, req_id, type: "mitigated_by", role, scheme, control_type? (medical links, the type stored\n on the link), asil_written? (ISO 26262 HARA only: the row\'s computed ASIL, written\n onto the target) }\n\nSide effects:\n - Adds the mitigated_by/mitigates relationship (JSONB + shadow table, one transaction)\n - ISO 26262 HARA only (scheme hara_iso26262): writes the row\'s computed ASIL onto the target\n requirement (data.asil + data.asil_source) with a history entry recording previous/new values.\n An ISO 14971 risk row and a TIR57 security row write no field on the target (REQ-ANL-257)\n - dfmea / every FMEA: never modifies any field on the target requirement',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:o.z.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:o.z.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows (every FMEA); must be omitted for hara rows."),override:o.z.boolean().optional().describe("hara only: apply the row's level (ASIL or Risk) over a conflicting existing value (history-logged)"),control_type:o.z.enum(["inherent","protective","information","authentication","authorization","cryptography","code_data_execution_integrity","confidentiality","event_detection_logging","resiliency_recovery","firmware_software_updates"]).optional().describe("Medical schemes only (required there): the ISO 14971 clause 7 control type. Security risk analysis rows (required there): one of the eight FDA Appendix 1 categories (authentication, authorization, cryptography, code_data_execution_integrity, confidentiality, event_detection_logging, resiliency_recovery, firmware_software_updates). Stored on the link; refused when it does not belong to the row's own scheme (REQ-ANL-241).")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:'List only the gap rows of a HARA / risk analysis / FMEA analysis, each naming the rule that matched.\n\nGap rules (identical to the web app):\n hara (HARA): unmitigated row with ASIL A-D ("asil <X> unmitigated")\n hara (medical risk analysis): uncontrolled row with Risk above Low ("<level> risk uncontrolled")\n dfmea (DFMEA, PFMEA and every FMEA variant): unmitigated row with RPN >= 100 ("rpn >= 100") or\n severity >= 9 ("severity >= 9")\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "RA-001", "PFMEA-002")\n\nReturns:\n { analysis_id, subtype, gaps: [{ id, title, source_req, source_function, computed_level, rule }], count }\n count is the gap-line TOTAL: the sum of every gap kind\'s gap_count (a controlled-but-unverified risk, an analysis-scope gap all count), matching the app\'s gap banner, so it can be GREATER than gaps.length, which lists only the per-row gap rules.\n plus scheme, labels and gap_kinds: [{ kind, label, row_ids, req_ids, gap_count, fix, fix_label }],\n the scheme\'s gap kinds with the ids behind each, in the same order and wording the app banner uses.\n gap_count is how many gaps the kind stands for: its rows, or its requirements, or 1 for a kind\n that is one fact about the ANALYSIS and therefore carries neither list.\n hara: unmitigated, no_test (no test on its ODD), no_parent (safety requirement at the system\n level with no parent)\n medical: no_control (a risk above Low), not_verified, no_residual, no_parent (risk control at the\n system level with no parent), no_scope (the analysis holds rows but states no intended\n use, ISO 14971:2019 5.2) and no_overall (every row is controlled and residual-rated but\n the overall residual risk is not judged, ISO 14971:2019 clause 8); both are written on\n the analysis id with atoms_fill_row\n FMEA: rpn (RPN 100 or above with no mitigating requirement), severity (severity 9 or above\n below RPN 100 with no mitigating requirement, the REQ-ANL-047 floor; a row is under one\n kind, never both); an FMEA has no requirement-scope kind, so no project-wide scan runs\n for it\n and system_level, system_level_source: the level the no_parent kind was judged against. The system\n level is the SECOND rung of the project\'s level ladder (metadata.levels, positional: the L1 of\n REQ-ASH-031), matched against tags.level by name; source is "taxonomy". Only when the ladder has\n fewer than two rungs does the literal "L1" apply, and source then reads "fallback".',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),analysis_id:o.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_propose_rows",{title:"Write Proposed Analysis Rows",description:"Write rows YOU have drafted for one function into a HARA / risk analysis / FMEA (a DFMEA, a\nPFMEA, a Software FMEA or a Use FMEA). The analysis carries its standard: the rows are validated\nagainst the scheme its stored variant selects.\n\nThe drafting is the assistant's job: read the analysis with atoms_get_analysis (its scope, its\nODD / operating modes and its existing rows), draft the rows, then send them here. This tool\nvalidates every value against the analysis's scheme and writes the rows; it never invents a value.\n\nRequires editor or admin role. Every written value is marked as MCP-sourced and every row is\nwritten UNAPPROVED: a person approves it with atoms_approve_row.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. \"HARA-001\", \"RA-001\", \"PFMEA-002\")\n - source_function (string, risk analysis only): the function these rows analyse; registered\n as a function-flagged tag if new (matching is case-insensitive and trimmed); a name that is\n already a domain is refused, never flagged (atoms_update_domain is_function=true)\n - source_req (string, FMEA only): the requirement these rows analyse\n - rows (object[], 1 to 8): the drafted rows, each a field name to value map using the\n analysis's scheme keys (the same keys atoms_fill_row accepts, plus 'effect', and 'title'\n on a risk analysis row). A risk analysis row sent without a title is named by its\n failure_mode (the hazard), else by its hazard; an FMEA row by its failure_mode. The cap of 8\n is shared with the app and the assistant; a longer list is refused, never truncated.\n The derived level (asil / rpn / risk) and the approval keys are refused by name.\n\nReturns:\n { analysis_id, subtype, scheme, variant?, labels, source_function | source_req,\n rows: [{ id, written_fields, computed_level }], count, max_rows, approved: false,\n link_warnings?, warning? }\n\nSide effects:\n - Creates one row item per drafted row, attached to the analysis (row ids follow the scheme: SG-n or RSK-n, FM-n or PF-n)\n - Marks every written field field_source='mcp' and leaves each row unapproved\n - Logs each created row to change_history with actor='mcp_<client>'",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),analysis_id:o.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),rows:o.z.array(o.z.record(o.z.string().max(64),o.z.union([o.z.string().max(5e4),o.z.number()]))).min(1).max(Ye).describe(`The drafted rows (1-${Ye}), each a scheme field name to value map`),source_function:o.z.string().min(1).max(100).optional().describe("Risk analysis only: the function these rows analyse"),source_req:o.z.string().min(1).max(20).optional().describe("FMEA only: the requirement these rows analyse")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_propose_rows",async e=>{const{proposeRowsHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_suggest_field",{title:"Write a Suggested Value for One Analysis Field",description:"Write ONE value YOU have suggested for one field of one analysis row.\n\nThe suggestion is the assistant's job (Suggest evidence, Suggest safety goal, Suggest risk control\nstatement); this tool is the write half: it validates the value against the row's scheme, writes it marked as MCP-sourced and\nreturns the row. A suggested rating is written together with its rationale: pass 'rationale' and\nit lands in the scheme's evidence field for that rating (severity -> s_rationale, exposure ->\ne_rationale, controllability -> c_rationale, p1 -> p1_rationale, p2 -> p2_rationale, and the\nsingle 'rationale' column on an FMEA).\n\nAccepting a suggestion is a client action: it flips that one field's field_source to 'user'. The\nrow stays unapproved either way, until atoms_approve_row records who approved it.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. \"SG-001\", \"RSK-002\", \"FM-003\", \"PF-004\")\n - field (string): the field to fill (any key atoms_fill_row accepts for this row's scheme)\n - value (string | number): the suggested value; a rating must be one the scheme allows\n - rationale (string, optional): the evidence behind a suggested RATING\n\nReturns:\n { row_id, subtype, scheme, field, field_source: \"mcp\", written_fields,\n rationale_field?, approval_cleared?, row: { id, computed_level, approved, mcp_fields, ...scheme fields } }\n approval_cleared: true means the row WAS approved and this suggestion cleared approved, approved_by,\n approved_at and approved_note: a signature never covers content the approver did not see.\n\nSide effects:\n - Saves the row with stale-write protection and logs to change_history\n - Marks the written field(s) field_source='mcp'; the row stays unapproved\n - On an approved row: clears the approval (history-logged with the reason)",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),field:o.z.string().min(1).max(64).describe("The field to fill (a scheme key of this row)"),value:o.z.union([o.z.string().max(5e4),o.z.number()]).describe("The suggested value"),rationale:o.z.string().max(5e4).optional().describe("The evidence behind a suggested rating; written to the scheme's evidence field")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_suggest_field",async e=>{const{suggestFieldHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_approve_row",{title:"Approve an Analysis Row in a Named Person's Name",description:'Record the sign-off of ONE analysis row, naming who approved it.\n\nRequires editor or admin role. The approver must be a member of the project\'s organization: a\nname that cannot be traced to a member is refused, never stored. The note is optional. Approving\nclears the machine-proposed (✦) markers on the row: the approver takes those values as their own.\nA row whose ratings are incomplete cannot be approved (its level is unset), matching the grid.\n\nThis tool signs off one analysis row. It has nothing to do with change control: it never\napproves, dismisses or applies a suggestion (REQ-CHG-062).\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. "SG-001", "RSK-002", "FM-003", "PF-004")\n - approver_id (string, UUID, optional): the approving member; defaults to the calling user\n - note (string, optional): the note captured with the approval\n\nReturns:\n { row_id, subtype, scheme, approved: true, approved_by, approved_at, approved_note,\n approver_role, computed_level, cleared_markers }\n\nSide effects:\n - Saves the row with stale-write protection: approved, approved_at, approved_by, approved_note\n - Flips every field_source=\'mcp\' entry on the row to \'user\'\n - Logs the approval (previous and new values) to change_history',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),row_id:o.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),approver_id:o.z.string().uuid().optional().describe("The approving project member; defaults to the calling user"),note:o.z.string().max(2e3).optional().describe("Optional note captured with the approval")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_approve_row",async e=>{const{approveRowHandler:t}=await Promise.resolve().then(()=>(wl(),Gc));return t(e)})),Il("atoms_list_scenario_catalogs",{title:"List Operational Scenario Catalogs",description:'List a project\'s operational scenario catalogs: the situational analysis written\nand accepted before a HARA (ISO 26262) starts. Each catalog is a list of entries (operational\nscenarios), each tagged with the functions it applies to.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): The project to list catalogs from\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, name, entries: [{id, text, function_tags}], acceptance }],\n meta: { total_count, limit, offset, has_more } }',inputSchema:{project_id:o.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Dl("atoms_list_scenario_catalogs",async e=>{const{listScenarioCatalogsHandler:t}=await Promise.resolve().then(()=>(Ml(),vl));return t(e)})),Il("atoms_mutate_scenario_catalog",{title:"Mutate an Operational Scenario Catalog",description:"Create/rename/delete a catalog, or add/edit/remove/tag one of its entries, or accept\na catalog. Every op goes through a row-locked database function and returns the STORED list, so a\nwrite can never report success for an entry the row did not retain.\n\nRequires editor or admin role.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID)\n - op: create_catalog | rename_catalog | delete_catalog | add_entry | edit_entry | remove_entry |\n tag_entry | accept_catalog\n - catalog_id (string, optional for create_catalog, which generates one when omitted; required for every other op)\n - name (string): the catalog name (create_catalog, rename_catalog)\n - entry_id (string, required for add_entry/edit_entry/remove_entry/tag_entry; caller-generated)\n - text (string): the entry's operational scenario text (add_entry, optional on edit_entry)\n - function_tags (string[]): the functions this entry applies to; [] = every function\n (add_entry, edit_entry, tag_entry)\n - by (string): the accepter's name (accept_catalog)\n - on (string): the acceptance date (accept_catalog)\n\nReturns:\n { status: \"success\", data: { scenario_catalogs: [...] } }\n\nSide effects:\n - add_entry/edit_entry/remove_entry return an ACCEPTED catalog to draft, keeping the prior\n acceptance in history. tag_entry and rename_catalog do not.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),op:o.z.enum(["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]).describe("The mutation to apply"),catalog_id:o.z.string().min(1).max(64).optional().describe("The catalog id (optional for create_catalog: generated when omitted)"),name:o.z.string().min(1).max(100).optional().describe("The catalog name (create_catalog, rename_catalog)"),entry_id:o.z.string().min(1).max(64).optional().describe("The entry id (caller-generated for add_entry)"),text:o.z.string().min(1).max(100).optional().describe("The entry's operational scenario text"),function_tags:o.z.array(o.z.string()).optional().describe("The functions this entry applies to; [] = every function"),by:o.z.string().min(1).max(200).optional().describe("The accepter's name (accept_catalog)"),on:o.z.string().min(1).max(32).optional().describe("The acceptance date (accept_catalog)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Dl("atoms_mutate_scenario_catalog",async e=>{const{mutateScenarioCatalogHandler:t}=await Promise.resolve().then(()=>(Ml(),vl));return t(e)}))}});B(),U(),Ya(),C();var Ll=d.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:u&&"SCRIPT"===u.tagName.toUpperCase()&&u.src||new URL("index.cjs",document.baseURI).href)("../package.json"),Fl=process.argv.slice(2)[0];(async function(){switch(Fl){case"login":{const{login:e}=await Promise.resolve().then(()=>(ni(),Ka));try{const{email:t}=await e();process.stderr.write(`\n ✓ Authenticated as ${t}\n`),process.stderr.write(" ✓ Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" Next steps:\n"),process.stderr.write(" $ 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(' {\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp"]\n }\n }\n }\n\n')}catch(e){process.stderr.write(`\n ✗ ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>($e(),ve));try{const{email:t,user_id:r}=await e();process.stderr.write(`\n ✓ Logged in as ${t}\n User ID: ${r}\n\n`)}catch(e){process.stderr.write(`\n ✗ Not authenticated: ${e instanceof Error?e.message:String(e)}\n Run: npx @atoms-tech/atoms-mcp login\n\n`),process.exit(1)}break}case"logout":{const{clearCredentials:e}=await Promise.resolve().then(()=>(oe(),J));await e(),process.stderr.write("Logged out. Credentials removed.\n"),process.stderr.write("Run 'npx @atoms-tech/atoms-mcp login' to authenticate again.\n");break}case"--version":case"-v":process.stderr.write(`@atoms-tech/atoms-mcp v${Ll.version}\n`);break;case"--help":case"-h":process.stderr.write("ATOMS MCP Server — AI agent integration for requirements management\n\nUsage:\n npx @atoms-tech/atoms-mcp Start MCP server (stdio)\n npx @atoms-tech/atoms-mcp login Authenticate with ATOMS.tech\n npx @atoms-tech/atoms-mcp logout Switch account / clear credentials\n npx @atoms-tech/atoms-mcp whoami Show current user\n npx @atoms-tech/atoms-mcp --version Show version\n");break;default:{process.stderr.write("[atoms-mcp] Starting MCP server via stdio...\n");{const{getValidToken:e,readValidToken:t}=await Promise.resolve().then(()=>($e(),ve)),{runExclusiveAuth:r}=await Promise.resolve().then(()=>(he(),ce)),{login:a}=await Promise.resolve().then(()=>(ni(),Ka));try{let i;try{i=(await e()).email}catch(e){process.stderr.write(`[atoms-mcp] Could not use the saved session: ${e instanceof Error?e.message:String(e)}\n`),process.stderr.write("[atoms-mcp] Starting login flow...\n");const n=async()=>{const e=await t();if(!e)throw new Error("no valid token yet");return{email:e.email}};i=(await r(n,async()=>({email:(await a()).email}))).email}process.stderr.write(`[atoms-mcp] Authenticated as ${i}\n`)}catch(e){process.stderr.write(`[atoms-mcp] Login failed: ${e instanceof Error?e.message:String(e)}\n[atoms-mcp] Starting server without auth. Tools will fail until you run: npx @atoms-tech/atoms-mcp login\n`)}}try{const t=await Ua(),r=Wa(),a=await async function(e,t){const r=process.env.ATOMS_MCP_ORG_ID?.trim();if(r)return r;const{data:a,error:i}=await e.from("org_members").select("org_id, joined_at, organizations!inner(status)").eq("user_id",t).eq("organizations.status","active").order("joined_at",{ascending:!0}).limit(1).maybeSingle();return i?(process.stderr.write(`[atoms-mcp] Could not resolve session org: ${i.message}\n`),null):a?.org_id??null}(t,r),i=await async function(e,t,r){if(!r)return{role:null,is_member:!1,effective:z};const{data:a,error:i}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:r});return i?(process.stderr.write(`[atoms-mcp] mcp_resolve_policy failed (${i.code}): ${i.message}. Falling back to fail-closed policy.\n`),{role:null,is_member:!1,effective:M}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:z};const t=e,r="string"==typeof t.role?t.role:null,a=!0===t.is_member,i=t.effective??{},n=(e,t)=>Array.isArray(e)?e.filter(e=>"string"==typeof e):t,s=(e,t)=>"boolean"==typeof e?e:t,o=i.project_scope,c=Array.isArray(o)&&o.length>0?o.filter(e=>"string"==typeof e):null;return{role:r,is_member:a,effective:{read_only:s(i.read_only,z.read_only),lockdown:s(i.lockdown,z.lockdown),block_destructive:s(i.block_destructive,z.block_destructive),block_bulk_import:s(i.block_bulk_import,z.block_bulk_import),cross_project_browse:s(i.cross_project_browse,z.cross_project_browse),allowed_toolsets:n(i.allowed_toolsets,z.allowed_toolsets),forbidden_tools:n(i.forbidden_tools,z.forbidden_tools),project_scope:c,require_confirmation_for:n(i.require_confirmation_for,z.require_confirmation_for)}}}(a)}(t,r,a);e={effective:i.effective,role:i.role,org_id:a},T=e.effective,H=e.org_id,i.is_member&&a?process.stderr.write(`[atoms-mcp] Org policy loaded: org=${a.slice(0,8)}… role=${i.role??"?"} read_only=${i.effective.read_only} lockdown=${i.effective.lockdown}\n`):process.stderr.write("[atoms-mcp] No org membership detected — running with permissive default policy.\n")}catch(e){process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). Running with permissive default — RLS still enforces row-level access.\n`)}process.stderr.write(`[atoms-mcp] Tool registry: ${function(){const e=L(),t=N(),r=[];r.push(e?"read-only":"read+write"),null===t?r.push("all toolsets"):(r.push(`toolsets=${[...t.allowed].sort().join(",")||"(none — only always-on tools)"}`),t.unknown.length>0&&r.push(`unknown=${t.unknown.join(",")}`));const a=process.env.ATOMS_MCP_PROJECT_ID?.trim();return a&&r.push(`project_scope=${a.slice(0,8)}…`),("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN)&&r.push("lockdown=on"),r.join(" | ")}()}\n`);const{server:t}=await Promise.resolve().then(()=>(Nl(),Tl)),r=new p.StdioServerTransport;await t.connect(r),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}var e})().catch(e=>{process.stderr.write(`[atoms-mcp] Fatal: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)});
2
+ var e=require("fs/promises"),t=require("os"),n=require("path"),r=require("@supabase/supabase-js"),a=require("http"),i=require("crypto"),s=require("url"),o=require("fs"),l=require("zod"),c=require("@modelcontextprotocol/ext-apps/server"),d=require("@modelcontextprotocol/sdk/server/mcp.js"),u=require("module"),p=require("@modelcontextprotocol/sdk/server/stdio.js"),m="undefined"!=typeof document?document.currentScript:null;function _(e){return e&&e.__esModule?e:{default:e}}var f,h,y,g,w,v,b,j,k,S,A,I,x,$,E,q,O,R=_(e),T=_(n),M=_(i),z=Object.defineProperty,C=Object.getOwnPropertyNames,D=(e,t,n)=>function(){if(n)throw n[0];try{return e&&(t=(0,e[C(e)[0]])(e=0)),t}catch(e){throw n=[e],e}},H=(e,t)=>{for(var n in t)z(e,n,{get:t[n],enumerable:!0})};function U(e){return j.get(e)}var P=D({"src/core/tool-catalog.ts"(){f=new Set(["atoms_status","atoms_list_projects"]),h=new Set(["atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_link_items","atoms_bulk_import","atoms_record_test_result","atoms_record_test_results","atoms_create_variable","atoms_update_variable","atoms_delete_variable","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_create_level","atoms_delete_level","atoms_reorder_levels","atoms_create_field","atoms_delete_field","atoms_reorder_fields","atoms_create_baseline","atoms_lock_baseline","atoms_restore_baseline","atoms_create_analysis","atoms_fill_row","atoms_link_mitigation","atoms_propose_rows","atoms_suggest_field","atoms_approve_row","atoms_mutate_scenario_catalog"]),y=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_level","atoms_delete_field","atoms_restore_baseline"]),g={atoms_mutate_scenario_catalog:{param:"op",values:["delete_catalog"]}},w=new Set(["atoms_bulk_import"]),v={items:["atoms_list_items","atoms_get_item","atoms_search","atoms_semantic_search","atoms_browse","atoms_get_history","atoms_list_changes","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_verification_status","atoms_record_test_result","atoms_record_test_results","atoms_project_summary","atoms_list_assets"],variables:["atoms_list_variables","atoms_get_variable","atoms_create_variable","atoms_update_variable","atoms_delete_variable"],domains:["atoms_list_domains","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_list_levels","atoms_create_level","atoms_delete_level","atoms_reorder_levels","atoms_list_fields","atoms_create_field","atoms_delete_field","atoms_reorder_fields"],baselines:["atoms_list_baselines","atoms_create_baseline","atoms_lock_baseline","atoms_diff_baselines","atoms_restore_baseline"],analysis:["atoms_create_analysis","atoms_fill_row","atoms_get_analysis","atoms_link_mitigation","atoms_get_gaps","atoms_propose_rows","atoms_suggest_field","atoms_approve_row","atoms_list_scenario_catalogs","atoms_mutate_scenario_catalog"]},b=Object.keys(v),j=new Map;for(const[e,t]of Object.entries(v))for(const n of t)j.set(n,e);k="The base_token from the read that showed you this item (atoms_get_item, atoms_get_analysis, atoms_get_variable, or a not_applied entry). Without one, a changed field comes back not saved, with its current value and a token to retry with.",S="Retry key: sending the same call again with the same key within 24 hours changes nothing twice.",A="apply_mine keeps your text over what someone saved after your read and tells them. Use it only when the person asked to keep their own text.",I="Set both from the previous answer when it says complete is false, to continue the same restore.",x="Set by the ATOMS editor card. Do not set this yourself.",$="Ignored on projects that save one field at a time; send base_token instead.",E="A result with code not_all_applied still saved every change listed under applied. Do not send those again; each entry under not_applied says why it was not saved and carries a base_token to retry with.",q="List the changes saved in a project after a change number, in order. Use the seq from atoms_get_item or your last call as since_seq to catch up cheaply instead of reading items again. old_value is shortened to 200 characters. Only projects that use the new saving number their changes.",O="If a call answers code rate_limited, wait retry_after_seconds seconds before calling again. Do not retry sooner."}});function N(e,t){if(f.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&&h.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&y.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&w.has(t))return{allowed:!1,reason:"block_bulk_import"};const n=U(t);return void 0===n||e.allowed_toolsets.includes(n)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function L(e,t){return N(e,t).allowed}function F(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 W,V,B=D({"src/core/policy.ts"(){P()}}),J=D({"src/core/types.ts"(){W={read_only:!1,lockdown:!1,block_destructive:!1,block_bulk_import:!1,cross_project_browse:!0,allowed_toolsets:["items","traceability","coverage","variables","domains","baselines","analysis"],forbidden_tools:[],project_scope:null,require_confirmation_for:[]},V={read_only:!0,lockdown:!0,block_destructive:!0,block_bulk_import:!0,cross_project_browse:!1,allowed_toolsets:[],forbidden_tools:[],project_scope:[],require_confirmation_for:[]}}});async function Q(e,t){const n=process.env.ATOMS_MCP_ORG_ID?.trim();if(n)return n;const{data:r,error:a}=await e.from("org_members").select("org_id, joined_at, organizations!inner(status)").eq("user_id",t).eq("organizations.status","active").order("joined_at",{ascending:!0}).limit(1).maybeSingle();if(a)throw process.stderr.write(`[atoms-mcp] Could not resolve session org: ${a.message}\n`),new Error(`Could not resolve session org: ${a.message}`);return r?.org_id??null}async function G(e,t,n){if(!n)return{role:null,is_member:!1,effective:W};const{data:r,error:a}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:n});return a?(process.stderr.write(`[atoms-mcp] mcp_resolve_policy failed (${a.code}): ${a.message}. Falling back to fail-closed policy.\n`),{role:null,is_member:!1,effective:V}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:W};const t=e,n="string"==typeof t.role?t.role:null,r=!0===t.is_member,a=t.effective??{},i=(e,t)=>Array.isArray(e)?e.filter(e=>"string"==typeof e):t,s=(e,t)=>"boolean"==typeof e?e:t,o=a.project_scope,l=Array.isArray(o)&&o.length>0?o.filter(e=>"string"==typeof e):null;return{role:n,is_member:r,effective:{read_only:s(a.read_only,W.read_only),lockdown:s(a.lockdown,W.lockdown),block_destructive:s(a.block_destructive,W.block_destructive),block_bulk_import:s(a.block_bulk_import,W.block_bulk_import),cross_project_browse:s(a.cross_project_browse,W.cross_project_browse),allowed_toolsets:i(a.allowed_toolsets,W.allowed_toolsets),forbidden_tools:i(a.forbidden_tools,W.forbidden_tools),project_scope:l,require_confirmation_for:i(a.require_confirmation_for,W.require_confirmation_for)}}}(r)}var K,Y,Z,X,ee,te,ne,re,ae=D({"src/db/policy.ts"(){J()}});function ie(e,t){e.is_member&&t?process.stderr.write(`[atoms-mcp] Org policy loaded: org=${t.slice(0,8)}… role=${e.role??"?"} read_only=${e.effective.read_only} lockdown=${e.effective.lockdown}\n`):process.stderr.write("[atoms-mcp] No org membership detected — running with permissive default policy.\n")}function se(){te=!1}function oe(){return K}function le(){const e=re,t=!!e&&Object.prototype.hasOwnProperty.call(e,"sendToolListChanged"),n=e?.sendToolListChanged?.bind(e);e&&n&&(e.sendToolListChanged=()=>{});let r=!1;try{for(const[e,t]of ne){const n=f.has(e)||L(K,e),a=!1!==t.enabled;n&&!a?(t.enable(),r=!0):!n&&a&&(t.disable(),r=!0)}}finally{e&&n&&!t&&delete e.sendToolListChanged}r&&n?.()}var ce=D({"src/middleware/session-policy.ts"(){J(),B(),P(),ae(),K=W,Y=null,Z=Date.now(),X=3e4,ee=null,te=!0,ne=new Map,re=null}});function de(){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 n=new Set,r=[];for(const e of t)b.includes(e)?n.add(e):r.push(e);return{allowed:n,unknown:r}}function ue(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function pe(e){if(ue()&&h.has(e))return!1;if(f.has(e))return!0;const t=de();if(null===t)return!0;const n=U(e);return!!n&&t.allowed.has(n)}var me,_e,fe=D({"src/middleware/tool-registry.ts"(){P(),B(),ce()}}),he={};async function ye(){try{const t=await e.readFile(_e,"utf-8"),n=JSON.parse(t);return n.access_token&&n.refresh_token?n:null}catch{return null}}async function ge(t){await e.mkdir(me,{recursive:!0,mode:448}),await e.writeFile(_e,JSON.stringify(t,null,2),{mode:384})}async function we(){const e=await ye();return!!e&&e.expires_at>Date.now()+6e4}function ve(e){return e.expires_at>Date.now()+6e4}async function be(){try{await e.unlink(_e)}catch{}}function je(){return _e}H(he,{clearCredentials:()=>be,getCredentialsPath:()=>je,hasValidCredentials:()=>we,isTokenValid:()=>ve,readCredentials:()=>ye,writeCredentials:()=>ge});var ke,Se,Ae,Ie,xe,$e,Ee,qe=D({"src/auth/token-store.ts"(){me=n.join(t.homedir(),".atoms"),_e=n.join(me,"credentials.json")}}),Oe={};async function Re(){try{await e.mkdir(ke,{recursive:!0,mode:448});const t=await e.open(Se,"wx");try{await t.writeFile(`${process.pid} ${Date.now()}`)}finally{await t.close()}return!0}catch(e){if("EEXIST"===e.code)return!1;throw e}}async function Te(){try{await e.unlink(Se)}catch{}}async function Me(){try{const t=await e.stat(Se);return Date.now()-t.mtimeMs>Ae}catch{return!1}}async function ze(e,t,n=Ee){const r=n.now()+Ie;for(;;){if(await n.tryAcquire())try{try{return await e()}catch{}return await t()}finally{await n.release()}try{return await e()}catch{}if(await n.isStale())await n.release();else{if(n.now()>r)return await t();await n.wait(xe)}}}H(Oe,{runExclusiveAuth:()=>ze});var Ce,De,He,Ue=D({"src/auth/lock.ts"(){ke=n.join(t.homedir(),".atoms"),Se=n.join(ke,".auth.lock"),Ae=7e4,Ie=12e4,xe=300,$e=e=>new Promise(t=>setTimeout(t,e)),Ee={now:Date.now,wait:$e,tryAcquire:Re,release:Te,isStale:Me}}}),Pe={};function Ne(e){return e.trim().replace(/\/+$/,"")}H(Pe,{ATOMS_APP_URL:()=>He,ATOMS_SUPABASE_ANON_KEY:()=>De,ATOMS_SUPABASE_URL:()=>Ce,resolveUrl:()=>Ne});var Le,Fe,We,Ve,Be,Je=D({"src/config.ts"(){Ce=Ne(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),De=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",He=process.env.ATOMS_APP_URL??"https://atoms.tech"}});function Qe(e){return e instanceof Ve||!!e&&"object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const{name:t,status:n,code:r}=e;return"AuthSessionMissingError"===t||"session_not_found"===r||!!Be.statuses.includes(n)||Be.codedStatuses.includes(n)&&"string"==typeof r&&Be.codes.includes(r)}(e)}function Ge(){return{status:"error",code:Le,retryable:!0,message:We,next_steps:[`Wait ${Fe} seconds, then retry the same call`,"Do not sign out or log in again: the saved session is still valid"]}}var Ke,Ye,Ze=D({"src/core/auth-outage.ts"(){Le="auth_unavailable",Fe=5,We="ATOMS could not check your sign-in just now. Your session is kept. Try again in a moment.",Ve=class extends Error{code=Le;constructor(e){super(`${Le}: ${e}`),this.name="AuthServiceUnavailableError"}},Be={statuses:[401],codedStatuses:[400,403],codes:["bad_jwt","no_authorization","user_not_found","session_not_found","session_expired","refresh_token_not_found","refresh_token_already_used","user_banned","validation_failed"]}}}),Xe={};async function et(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=nt(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await ye();if(t&&t.expires_at>Date.now()+6e4){const e=nt(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}return null}async function tt(){const e=await et();if(e)return e;const t=await ye();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp@latest login' to connect your ATOMS account.");return ze(async()=>{const e=await et();if(e)return e;throw new Error("no fresh token yet")},()=>async function(e){process.stderr.write("[atoms-mcp] Refreshing access token...\n");const t=r.createClient(Ce,De,{global:{fetch:Ye}});let n=await t.auth.refreshSession({refresh_token:e.refresh_token});if(n.error||!n.data.session){const r=await ye();if(r&&r.expires_at>Date.now()+6e4){const e=nt(r.access_token);return{access_token:r.access_token,refresh_token:r.refresh_token,user_id:e.sub,email:e.email??r.user_email??""}}r&&r.refresh_token&&r.refresh_token!==e.refresh_token&&(process.stderr.write("[atoms-mcp] Refresh token was rotated by another session; retrying with the latest...\n"),n=await t.auth.refreshSession({refresh_token:r.refresh_token}))}if(n.error||!n.data.session){const e=n.error?[n.error.status,n.error.message].filter(Boolean).join(" ").trim():"no session returned";if(Qe(n.error))throw new Ve(`refresh: ${e}`);throw new Error(`Token refresh failed (${e}). Your saved ATOMS session is no longer valid — re-run 'npx @atoms-tech/atoms-mcp@latest login'.`)}const a=n.data.session;return await ge({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??""}}(t))}function nt(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),r=JSON.parse(Buffer.from(n,"base64").toString("utf-8"));if(!r.sub)throw new Error("JWT missing 'sub' claim");return r}H(Xe,{AUTH_CALL_TIMEOUT_MS:()=>Ke,getValidToken:()=>tt,readValidToken:()=>et});var rt,at=D({"src/auth/refresh.ts"(){qe(),Ue(),Je(),Ze(),Ke=1e4,Ye=async(e,t)=>{const n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Auth did not answer within ${Ke} ms`)),Ke),a=t?.signal,i=()=>n.abort(a?.reason);a?.addEventListener("abort",i);try{const r=await fetch(e,{...t,signal:n.signal}),a=await r.arrayBuffer(),i=502===r.status||503===r.status||504===r.status?500:r.status;return new Response(a.byteLength>0?a:null,{status:i,headers:r.headers})}catch(e){return new Response(JSON.stringify({msg:e instanceof Error?e.message:String(e)}),{status:500,headers:{"content-type":"application/json"}})}finally{clearTimeout(r),a?.removeEventListener("abort",i)}}}});function it(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?rt:t:rt}function st(e){const t=it(e);return"cursor"===t?"mcp_cursor":"copilot"===t?"mcp_copilot":"mcp_claude"}var ot,lt,ct,dt,ut,pt=D({"src/core/client-identity.ts"(){rt="claude_desktop"}});function mt(e){return/(?:^|:\s)(?:429(?:\s+too many requests)?|too many requests|api rate limit exceeded|request rate limit reached|rate limit (?:exceeded|reached))\s*\.?\s*$/i.test(e)}function _t(e){return"string"==typeof e&&e.includes(ct)}function ft(e){return"string"==typeof e&&e.includes(dt)}function ht(e){return"project"===e?{status:"error",message:"An admin or owner of this project is needed to change its field definitions.",next_steps:["Ask an admin of this organization, or the owner of this project (the person who created it), to make this change","Read the current definitions with atoms_list_fields"]}:{status:"error",message:"An org admin is needed to create a field in every project of the organization.",next_steps:["Ask an admin of this organization to make this change","Read the current definitions with atoms_list_fields"]}}var yt,gt,wt,vt,bt,jt,kt,St,At,It,xt,$t,Et,qt,Ot,Rt,Tt,Mt,zt,Ct,Dt,Ht,Ut,Pt,Nt,Lt,Ft,Wt,Vt,Bt,Jt,Qt,Gt,Kt,Yt,Zt,Xt=D({"src/core/errors.ts"(){ot=[/^results must (?:be a JSON array|have between 1 and 100 entries)/,/^item .* is not a test-case in project /,/^(?:run |step )?evidence (?:URL exceeds 2048 characters|link ".*" is not an http, https or mailto link)/s,/^replaces: /,/^step results were sent for a test case with no steps/,/^invalid (?:step status|result) ".*" \(allowed: /s,/^step actual-result note exceeds 500 characters/,/^step result key ".*" is not allowed \(allowed: /s,/^step id ".*" is (?:not a step of this test case|given more than once in one run)/s,/^asset name exceeds 200 characters/,/^run note exceeds 500 characters/,/^release_id .* is not a formal Release in project /],lt=class extends Error{},ct="rollout_switched:multiuser_saving: This project still saves whole items. Reload, then save again.",dt="rollout_switched:multiuser_saving: This project now saves one field at a time. Do not retry. Change the args in your MCP client config to @atoms-tech/atoms-mcp@latest and restart it.",ut=10}});function en(e){return/rollout_switched:multiuser_saving/i.test(e)}function tn(){return{status:"error",message:gt,next_steps:[wt],code:"rollout_switched",retryable:!1}}function nn(e){return/project_in_trash/i.test(e)||e===bt}function rn(){return{status:"error",message:vt,next_steps:["Ask a project admin to restore the project, then retry","Use atoms_list_projects to see the projects you can change"],code:"project_in_trash",retryable:!1}}function an(e){return e===kt||/not a member of this project's organization/i.test(e)}function sn(){return{status:"error",message:jt,next_steps:["Do not retry this call. Access to this project was removed","Use atoms_list_projects to see the projects you can still reach"],code:"project_access_lost",retryable:!1}}function on(e){const t=/change_open_by_other: a change is already open on ([^\s;:]{1,60}) by another user/.exec(e);return t?{status:"error",message:`A change is already open on ${t[1]} by another user, so it is under review and only its author or a project admin can change it. Nothing was saved.`,next_steps:["Do not retry this call. It is refused until the open change is approved or withdrawn","Ask the author of the open change or a project admin to approve or discard it, or have a project admin make the edit","Use atoms_get_item to read the item as it stands now"],code:"change_open_by_other",retryable:!1}:null}function ln(e,t){if(/jwt\s*expired|invalid.?jwt|token.*(?:has\s+)?expired|jwt.*invalid|pgrst30[12]/i.test(`${t?.code??""} ${t?.message??""}`)){const e=t?.message??"";return new Error(/jwt|token/i.test(e)?e:`invalid JWT: ${e||t?.code}`)}return t?.message&&mt(t.message)?new Error(t.message):t&&"42501"!==t.code||!St.test(e)?new Error(`Project '${e}' not found`):new Error(kt)}function cn(e){const t=/item_locked:([^\s:]{1,60}): (locked to (.{1,60}?)|locked for everyone|locked to another person), and this org has Agents respect item locks on\./.exec(e);if(!t)return null;const n=t[2],r=void 0!==t[3]?t[3]:n.replace(/^locked /,""),a=void 0!==t[3]?`locked to ${r}`:n,i=void 0!==t[3]?"Ask them or an admin to unlock it":"Ask an admin to unlock it";return{status:"error",message:`${t[1]} is ${a}, and this org has Agents respect item locks on.`,next_steps:[`${i}, then retry`,"Do not retry until the item is unlocked"],code:"item_locked",retryable:!1}}function dn(e,t){return`ATOMS MCP ${t} is available; this server is ${e}. In your MCP client config change the args to @atoms-tech/atoms-mcp@latest, then restart the client.`}function un(e){if(null==e)return"null";if("number"==typeof e)return Number.isFinite(e)?JSON.stringify(e):"null";if("string"==typeof e||"boolean"==typeof e)return JSON.stringify(e);if("bigint"==typeof e)return JSON.stringify(e.toString());if(Array.isArray(e))return`[${e.map(e=>void 0===e||"function"==typeof e?"null":un(e)).join(",")}]`;if("object"==typeof e){const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]&&"function"!=typeof t[e]).sort().map(e=>`${JSON.stringify(e)}:${un(t[e])}`).join(",")}}`}return"null"}async function pn(e){return t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),Array.from(new Uint8Array(t),e=>e.toString(16).padStart(2,"0")).join("");var t}function mn(e,t,n="item"){return e&&"object"==typeof e?"variable"===n?"variables"!==t[0]?null:t.length<=2?e:_n(e[t[2]],t.slice(3)):0===t.length?e.data??null:Ot.has(t[0])?1===t.length?e[t[0]]??null:null:_n(e.data,t):null}function _n(e,t){let n=e;for(const e of t){if(null==n)return null;if(Array.isArray(n))n=n.find(t=>null!==t&&"object"==typeof t&&!Array.isArray(t)&&t.id===e);else{if("object"!=typeof n)return null;n=n[e]}}return void 0===n?null:n}function fn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function hn(e,t){return e.length<=t.length&&e.every((e,n)=>e===t[n])}function yn(e,t,n="item"){const{scope:r,paths:a}=function(e){return"string"==typeof e?{scope:e,paths:null}:"raw"in e?{scope:e.scope,paths:e.paths}:{scope:"paths",paths:e.paths}}(e);if("variable"===r||"variable"===n)return"variables"===t[0]&&("variable"===r||"paths"===r&&(a??[]).some(e=>hn(e,t)));if(0===t.length||Rt.has(t[0]))return!1;switch(r){case"item":case"all":return!0;case"core":return xt.some(e=>fn(e,t));case"analysis":return fn(t,["title"])||fn(t,["body"])||("analysis_props"===t[0]||"relationships"===t[0])&&t.length>=2;case"paths":return(a??[]).some(e=>hn(e,t))}return!1}async function gn(e,t,n="item"){let r;if("string"!=typeof t)r=t.paths.map(t=>mn(e,t,n));else if("core"===t||"analysis"===t){const a="core"===t?xt:$t;r=Object.fromEntries(a.map(t=>[JSON.stringify(t),mn(e,t,n)]))}else r=e??null;return(await pn(un(r))).slice(0,16)}function wn(e,t,n){return`${e}.${t}~${function(e){return"string"==typeof e?e:`paths:${encodeURIComponent(JSON.stringify(e.paths))}`}(n)}`}async function vn(e,t,n="item"){return wn(e.id,await gn(e.fields_snapshot,t,n),t)}function bn(e){if("string"!=typeof e||0===e.length||e.length>At)return null;const t=qt.exec(e);if(!t)return null;const n=t[1].toLowerCase(),r=t[2].toLowerCase(),a=t[3];if(Et.has(a))return{raw:e,revisionId:n,digest:r,scope:a,paths:null};if(!a.startsWith("paths:"))return null;let i;try{i=JSON.parse(decodeURIComponent(a.slice(6)))}catch{return null}return Array.isArray(i)&&i.length>0&&i.every(e=>Array.isArray(e)&&e.length>0&&e.every(e=>"string"==typeof e))?{raw:e,revisionId:n,digest:r,scope:"paths",paths:i}:null}function jn(e){return"variable"===e?{table:"variable_revisions",idCol:"variable_id"}:{table:"item_revisions",idCol:"item_id"}}function kn(e,t){return{id:String(e.id),item_id:String(e[t]),revision_number:Number(e.revision_number??0),valid_from:e.valid_from??null,fields_snapshot:e.fields_snapshot??null,diff_summary:e.diff_summary??null}}function Sn(e,t){return new Error(String(e?.message??`${t} failed`))}async function An(e,t,n,r="item"){const a=new Map,i=[...new Set(n)];if(0===i.length)return a;const{table:s,idCol:o}=jn(r),{data:l,error:c}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in(o,i).is("valid_to",null).is("deleted_at",null);if(c)throw Sn(c,`${s} read`);for(const e of l??[]){const t=kn(e,o),n=a.get(t.item_id);(!n||t.revision_number>n.revision_number)&&a.set(t.item_id,t)}return a}async function In(e,t,n,r="item"){const a=new Map,i=[...new Set(n)];if(0===i.length)return a;const{table:s,idCol:o}=jn(r),{data:l,error:c}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in("id",i);if(c)throw Sn(c,`${s} read`);for(const e of l??[]){const t=kn(e,o);a.set(t.id,t)}return a}async function xn(e,t){const{data:n,error:r}=await e.rpc("changes_since",{p_project_id:t,p_after_seq:0,p_limit:0});if(r)throw Sn(r,"changes_since");const a=n?.head_seq;return"number"==typeof a?a:Number(a??0)}async function $n(e,t,n,r){const a=new Map,i=[...new Set(n)];for(const e of i)a.set(e,[]);if(0===i.length)return a;const{data:s,error:o}=await e.rpc("fresh_typing_notes",{p_project_id:t,p_item_ids:i});if(o)throw Sn(o,"fresh_typing_notes");for(const e of s??[]){const t=a.get(e.item_id)??[];t.push({path:e.path,field_label:En(e.path,r),person:{name:e.user_name??"Someone",kind:"person"}}),a.set(e.item_id,t)}return a}function En(e,t){if(!e||0===e.length)return"Item";const n=Tt[JSON.stringify(e)];if(n)return n;if("fields"===e[0]&&e.length>=2)return e[1];if("steps"===e[0]&&e.length>=2){const n=t?.stepNumber?.(e[1]);return"number"==typeof n?`Step ${n}`:"Step"}if("analysis_props"===e[0]&&e.length>=2){const n=t?.analysisLabel?.(e[1]);if(n)return n}return"variables"===e[0]&&e.length>=3?e[2].charAt(0).toUpperCase()+e[2].slice(1):e.join(" / ")}function qn(e){return JSON.stringify(e)}async function On(e){const t=e.kind??"item",n=new Map,r=[];for(const t of e.requests){const e=n.get(t.itemId)??{parsed:[],bad:!1};for(const n of t.tokens){const t=bn(n);t?(e.parsed.push(t),r.push(t.revisionId)):e.bad=!0}n.set(t.itemId,e)}const a=await In(e.client,e.projectId,r,t),i=new Map;for(const[e,r]of n){const n=[];for(const i of r.parsed){const s=a.get(i.revisionId);if(!s||s.item_id!==e){r.bad=!0;continue}const o="paths"===i.scope?{paths:i.paths??[]}:i.scope;await gn(s.fields_snapshot,o,t)===i.digest&&n.push({token:i,rev:s})}i.set(e,n)}const s=new Map,o=[],l=[];for(const r of e.requests){const e=s.get(r.itemId)??{itemId:r.itemId,send:!0,bases:new Map,badToken:n.get(r.itemId)?.bad??!1},a=i.get(r.itemId)??[];r.paths.forEach((n,i)=>{let s=null;for(const e of a)yn(e.token,n,t)&&(!s||e.rev.revision_number>s.rev.revision_number)&&(s=e);s?(l.push({req:r,path:n,index:i}),e.bases.set(qn(n),{base:mn(s.rev.fields_snapshot,n,t),base_revision_id:s.rev.id,base_saves:Math.max(1,Number(s.rev.diff_summary?.saves??1)||1),revision_number:s.rev.revision_number,token:s.token.raw})):o.push({req:r,path:n,index:i})}),s.set(r.itemId,e)}const c=[];if(o.length>0){const n=await An(e.client,e.projectId,o.map(e=>e.req.itemId),t);for(const e of o){const r=n.get(e.req.itemId),a=s.get(e.req.itemId);c.push({op_id:"",status:"conflict",reason:a.badToken?"bad_token":"no_base",...Rn(t,e.req),path:e.path,seq:null,current:r?mn(r.fields_snapshot,e.path,t):null,current_revision_id:r?r.id:null,...e.req.values&&e.index<e.req.values.length?{sent:e.req.values[e.index]}:{},...r?{}:{no_revision:!0}})}if("bulk"===e.mode){const e=new Set(o.map(e=>e.req.itemId));for(const t of e){const e=s.get(t);e.send=!1,e.bases.clear()}for(const n of l)e.has(n.req.itemId)&&c.push({op_id:"",status:"skipped",reason:"item_skipped",...Rn(t,n.req),path:n.path,seq:null,...n.req.values&&n.index<n.req.values.length?{sent:n.req.values[n.index]}:{}})}}return{items:s,refusals:c}}function Rn(e,t){return"variable"===e?{item_id:null,name:t.name??t.itemId,variable_id:t.itemId}:{item_id:t.itemId}}function Tn(e,t){const{base:n,base_revision_id:r,base_saves:a,...i}=e;return t?{...i,base:t.base,base_revision_id:t.base_revision_id,base_saves:t.base_saves}:i}function Mn(e){return e?"agent"===e.kind?e.label??e.name??null:e.name??null:null}async function zn(e){const t=new Map;for(const n of e.ops??[])n.op_id&&t.set(n.op_id,n);const n=new Map;for(const t of e.ops??[])n.set(`${t.item_id??""}|${qn(t.path)}`,t);const r=new Map;for(const t of e.skippedItems??[])"string"!=typeof t&&t&&t.item_id&&r.set(t.item_id,t);const a={applied:[],not_applied:[],captured:[],seq:null,merged_fields:[],replayed:!1,replaced:[],total:e.answers.length},i=new Map,s=[],o=e=>{"number"==typeof e&&(null===a.seq||e>a.seq)&&(a.seq=e)};for(const l of e.answers){const c=l.path??null;if(Mt.has(l.status)){const e={item_id:l.item_id??null,path:c,status:l.status,seq:l.seq??null};if(null===l.item_id&&l.name&&(e.name=l.name),l.merged){e.merged=!0;const t=(c??[]).join(".");t&&!a.merged_fields.includes(t)&&a.merged_fields.push(t)}if("replaced"===l.status||l.replaced&&"object"==typeof l.replaced){const t={name:Mn(l.replaced?.author??null)};e.replaced=t,a.replaced.push(t)}l.replayed&&(e.replayed=!0),a.applied.push(e),o(l.seq);continue}if("captured"===l.status){a.captured.push(l),o(l.seq);continue}const d=(l.op_id?t.get(l.op_id):void 0)??n.get(`${l.item_id??""}|${qn(c??[])}`),u={item_id:l.item_id??null,...null===l.item_id&&l.name?{name:l.name}:{},path:c,field_label:En(c,e.labels),status:l.status,reason:l.reason??("skipped_typing"===l.status?"typing":"locked"===l.status?"item_locked":null)};d&&"value"in d?u.your_value=d.value:"sent"in l&&(u.your_value=l.sent);const p=l.item_id?r.get(l.item_id):void 0,m=l.item_id&&"skipped"===l.status?e.openRevisions?.get(l.item_id):void 0;let _=null;"conflict"===l.status?("current"in l&&(u.theirs_value=l.current),l.current_revision_id&&(_={revId:l.current_revision_id,rev:e.revisionsById?.get(l.current_revision_id),value:l.current??null})):m&&c?(u.theirs_value=mn(m.fields_snapshot,c),_={revId:m.id,rev:m,value:u.theirs_value}):"current"in l&&"deleted"!==l.status&&(u.theirs_value=l.current),"base"in l?u.base_value=l.base:d&&"base"in d&&(u.base_value=d.base);const f=l.current_author??p?.change?.author??null;f&&(u.changed_by={kind:f.kind,name:Mn(f)});const h=l.current_at??p?.change?.at??null;(f||h)&&(u.changed_at=h);const y=l.current_seq??p?.change?.seq;if(null!=y&&(u.seq=y),("skipped_typing"===l.status||"skipped"===l.status&&"typing"===l.reason)&&(u.typing={name:l.typing?.name??null,renewed_at:l.typing?.renewed_at??null}),("locked"===l.status||"skipped"===l.status&&"locked"===l.reason)&&(u.locked_by=l.locked_by?{name:l.locked_by.name??null}:null),l.target&&(u.target=l.target),"boolean"==typeof l.restorable&&(u.restorable=l.restorable),l.replayed&&(u.replayed=!0),_&&c){const e=`${u.item_id??u.name??""}|${_.revId}`,t=i.get(e)??{revId:_.revId,rev:_.rev,entries:[]};t.entries.push({entry:u,value:_.value}),i.set(e,t)}s.push({entry:u,answer:l})}for(const e of i.values()){const t=new Set,n=[],r=[];for(const{entry:a,value:i}of e.entries){const s=qn(a.path);t.has(s)||(t.add(s),n.push(a.path),r.push(e.rev?mn(e.rev.fields_snapshot,a.path):i))}const a=(await pn(un(r))).slice(0,16),i=wn(e.revId,a,{paths:n});for(const{entry:t}of e.entries)t.base_token=i}for(const{entry:e,answer:t}of s)e.message=Dn(e,t),a.not_applied.push(Un(e));return a.replayed=e.answers.length>0&&e.answers.every(e=>!0===e.replayed),a}function Cn(e){if(e.item_id)return e.item_id;const t=e.path?.[0],n=e.name??"";return"variables"===t?`Variable ${n}`.trim():"taxonomy"===t&&"domains"===e.path?.[1]?`Domain ${n}`.trim():"taxonomy"===t&&"levels"===e.path?.[1]?`Level ${n}`.trim():n||"The project"}function Dn(e,t){const n=Cn(e),r=e.field_label,a=e.changed_by?.name??"Someone",i=e.changed_at?` at ${e.changed_at}`:"",s=e.reason??"",o=e.locked_by&&e.locked_by.name?`is locked to ${e.locked_by.name}`:"is locked for everyone";switch(e.status){case"conflict":return"no_base"===s?t?.no_revision?`${n} ${r} not saved: ${n} has no saved revision yet; save it once in ATOMS, then try again.`:`${n} ${r} not saved: no base_token covers it. Its current value is in theirs_value; send your change again with this entry's base_token. If you are in an ATOMS editor card, close the card and open ${n} again.`:"bad_token"===s?t?.no_revision?`${n} ${r} not saved: ${n} has no saved revision yet; save it once in ATOMS, then try again.`:`${n} ${r} not saved: the base_token you sent is not a token for ${n}. Its current value is in theirs_value; send your change again with this entry's base_token.`:`${n} ${r} not saved: ${a} changed it${i} after you read it.`;case"skipped_typing":return`${n} ${r} skipped: ${e.typing?.name??"Someone"} is typing in it.`;case"locked":return`${n} ${r} skipped: ${n} ${o}, and this org has Agents respect item locks on.`;case"deleted":return"in_trash"===s?`${n} ${r} not saved: ${n} is in the Trash.`:"row_deleted"===s||"column_deleted"===s?`${n} ${r} not saved: that row was deleted.`:"field_deleted"===s?`${n} ${r} not saved: that field was removed from the project.`:`${n} ${r} not saved: ${n} no longer exists.`;case"forbidden":return s.startsWith("mcp_policy_")?`${n} ${r} not saved: your org's MCP Access Policy does not allow this change.`:"change_open_by_other"===s?`${n} ${r} not saved: ${Mn(t?.change_author??null)??a} has an open change on ${n}.`:"asil_lower_needs_person"===s?`${n} ASIL not changed: lowering an ASIL needs a person. Ask them to review it in ATOMS.`:`${n} ${r} not saved: your role cannot change it.`;case"invalid":return`${n} ${r} not saved: ${l=String(t?.message??(s||"the change is not valid")),l.replace(/[.\s]+$/,"")}.`;case"skipped":switch(s){case"clash":case"changed_since_source":return`${n} ${r} not saved: ${a} changed ${n}${i} after you read it, so nothing of ${n} was saved.`;case"item_skipped":return`${n} ${r} not saved: another change you sent to ${n} was not saved, so nothing of ${n} was saved.`;case"typing":return`${n} ${r} skipped: ${e.typing?.name??"Someone"} is typing in it.`;case"locked":return`${n} ${r} skipped: ${n} ${o}, and this org has Agents respect item locks on.`;case"deleted":return`${n} ${r} not saved: ${n} is in the Trash or no longer exists.`;case"forbidden":return`${n} ${r} not saved: your role cannot change it.`;case"approved":return`${n} ${r} not saved: ${n} is approved.`;case"chunk_not_sent":return`${n} not saved: an earlier part of this call failed, so this part was not sent.`;case"depends_on_refused":return`${n} ${r} not saved: an earlier change of this call that it needs was not saved.`;default:return`${n} ${r} not saved: ${s||"it was skipped"}.`}default:return`${n} ${r} not saved.`}var l}function Hn(e){if("string"==typeof e)return e.length;const t=JSON.stringify(e);return void 0===t?0:t.length}function Un(e){const t={...e},n=[];for(const e of Wt)e in t&&Hn(t[e])>zt&&(delete t[e],n.push(e));return n.length>0&&(t.value_omitted=!0,t.omitted_values=n,t.hint=`A value is longer than ${zt} characters and was left out. Read it with atoms_get_item (${Cn(e)}), then send your change again.`),t}function Pn(e){return"string"==typeof e?`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"&lt;/user_content&gt;")}</user_content>`:Array.isArray(e)?e.map(Pn):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Pn(t)])):e}function Nn(e){const t=new TextEncoder,n=t.encode(JSON.stringify(e)??"").length,r=t.encode(JSON.stringify(Pn(e),null,2)??"").length;return Math.max(n,r)}function Ln(e,t=Nn){if(t(e)<=Ct)return e;const n=e.not_applied.map(e=>{const t={...e};let n=!1;for(const e of Wt)e in t&&(delete t[e],n=!0);return delete t.omitted_values,(n||e.value_omitted)&&(t.value_omitted=!0),t});let r={...e,not_applied:n};if(t(r)<=Ct)return r;const a=n.map(e=>{const{message:t,hint:n,...r}=e;return r});if(r={...r,not_applied:a},t(r)<=Ct)return r;const{applied:i,...s}=r,o={...s,applied_count:i?.length??r.applied_count??0},l=e=>{const t=a.slice(e),n=[];for(const e of t){const t=e.item_id??e.name;t&&!n.includes(t)&&n.length<Ht&&n.push(t)}return{...o,not_applied:a.slice(0,e),not_applied_omitted:{count:t.length,item_ids:n}}};let c=0,d=a.length;for(;c<d;){const e=Math.ceil((c+d)/2);t(l(e))<=Ct?c=e:d=e-1}return l(c)}function Fn(e){const t=e.not_applied.length,n=[`${t} of ${e.total} changes ${1===t?"was":"were"} not saved.`];let r=0;for(const a of e.not_applied.slice(0,5)){const e=a.message??Dn(a),i=t-r-1>0?` And ${t-r-1} more.`:"";if([...n,e].join(" ").length+i.length>Dt)break;n.push(e),r+=1}r<t&&n.push(`And ${t-r} more.`);const a=n.join(" ");return a.length<=Dt?a:a.slice(0,Dt)}function Wn(e){const t=t=>e.not_applied.some(t),n=[Ut];return(t(e=>"conflict"===e.status&&"no_base"!==e.reason&&"bad_token"!==e.reason)||t(e=>"skipped"===e.status&&("clash"===e.reason||"changed_since_source"===e.reason)))&&n.push(Pt),t(e=>"skipped_typing"===e.status||"skipped"===e.status&&"typing"===e.reason)&&n.push(Nt),t(e=>"locked"===e.status||"skipped"===e.status&&"locked"===e.reason)&&n.push(Lt),t(e=>"conflict"===e.status&&("no_base"===e.reason||"bad_token"===e.reason))&&n.push(Ft),n}function Vn(e,t,n){const r=e.applied.length+e.captured.length;return{isError:0===r,result:Ln({...t??{},status:r>0?"partial":"error",code:"not_all_applied",retryable:!1,message:Fn(e),next_steps:Wn(e),applied:e.applied,not_applied:e.not_applied,seq:e.seq,...e.merged_fields.length>0?{merged_fields:e.merged_fields}:{}},n)}}function Bn(e){return{seq:e.seq,...e.merged_fields.length>0?{merged_fields:e.merged_fields}:{},...e.replayed?{replayed:!0}:{},...e.replaced.length>0?{replaced:e.replaced}:{}}}async function Jn(e){return async function(e,t){const n=e.replace(/-/g,"");if(!/^[0-9a-f]{32}$/i.test(n))throw new Error(`uuidV5: bad namespace ${e}`);const r=new Uint8Array(16);for(let e=0;e<16;e+=1)r[e]=parseInt(n.slice(2*e,2*e+2),16);const a=(new TextEncoder).encode(t),i=new Uint8Array(16+a.length);i.set(r,0),i.set(a,16);const s=new Uint8Array(await crypto.subtle.digest("SHA-1",i)).slice(0,16);s[6]=15&s[6]|80,s[8]=63&s[8]|128;const o=Array.from(s,e=>e.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}(Vt,e.map(String).join("\n"))}function Qn(){return crypto.randomUUID()}function Gn(e){return[e.userId,e.projectId,"create_item",e.content,e.k,e.sessionId]}function Kn(e){const t=[e.userId,e.projectId,"key",e.family,e.key,e.itemIdOrK,e.path?encodeURIComponent(JSON.stringify(e.path)):""];return void 0!==e.runHash&&t.push(e.runHash,e.runK??0),t}function Yn(e){return[e.userId,e.projectId,"append_run",e.itemId,e.runHash,e.k,e.effectiveKey]}function Zn(e){return[e.userId,e.projectId,e.what,e.name]}function Xn(e){return"atoms_create_item"===e||"atoms_bulk_import"===e?"item":e}function er(e){const t=new Map;return e.map(e=>{const n=t.get(e)??0;return t.set(e,n+1),n})}function tr(e){return"string"==typeof e?e.replace(/<\s*\/?\s*user_content\s*>/gi,""):Array.isArray(e)?e.map(tr):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,tr(t)])):e}function nr(e){return un(tr({type:e.type,title:e.title,body:e.body??null,summary:e.summary??null,req_type:e.req_type??null,domains:Bt(e.domains),level:e.level??null,parent_ids:Bt(e.parent_ids),fields:e.fields??{}}))}function rr(e){const t=new Map;return e.forEach((e,n)=>{const r=e.item_id??"\0project",a=t.get(r)??{key:r,ops:[]};a.ops.push({op:e,index:n}),t.set(r,a)}),[...t.values()]}function ar(e,t,n){const r=[];let a=[],i=0;for(const s of e)a.length>0&&(i+1>t||a.length+s.ops.length>n)&&(r.push(a),a=[],i=0),a.push(...s.ops),i+=1;return a.length>0&&r.push(a),r.map(e=>e.sort((e,t)=>e.index-t.index).map(e=>e.op))}function ir(e){return e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message:e)}function sr(e){return/too_many_items/.test(ir(e))}function or(e){return e.map(e=>({op_id:e.op_id,status:"skipped",reason:"chunk_not_sent",item_id:e.item_id,path:e.path,seq:null}))}async function lr(e,t){try{const{data:n,error:r}=await e.rpc("rollout_state",{p_project_id:t});return r?null:!!n&&"object"==typeof n&&!0===n.multiuser_saving}catch{return null}}function cr(){return{status:"error",message:Gt,next_steps:["Send the same call again in a moment"],code:"rollout_state_unreadable",retryable:!0}}function dr(e,t){const n=ir(t);return"ops"===e&&_t(n)?"main":"main"===e&&(ft(n)||n.includes(yt))?"ops":null}async function ur(e,t){try{return await t(e)}catch(n){const r=dr(e,n);if(!r)throw n;return t(r)}}function pr(e,t,n){const r=(t??"").trim().split(/\s+/)[0]??"";return`${e} for ${r?r.slice(0,40):((n??"").split("@")[0]||"someone").slice(0,40)}`}async function mr(e,t,n){const r=new Map,a=[...new Set(n.filter(e=>"string"==typeof e&&e.length>0))];for(let n=0;n<a.length;n+=Zt){const{data:i,error:s}=await e.rpc("mcp_op_answers",{p_project_id:t,p_op_ids:a.slice(n,n+Zt)});if(s)throw Sn(s,"mcp_op_answers");for(const e of i?.answers??[])e&&e.op_id&&r.set(e.op_id,{...e,replayed:!0})}return r}async function _r(e,t,n){const r=n.filter(e=>"invalid"===e.status&&"op_id_reused"===e.reason).map(e=>e.op_id);if(0===r.length)return n.map(e=>({...e}));const a=await mr(e,t,r);return n.map(e=>{if("invalid"!==e.status||"op_id_reused"!==e.reason)return{...e};const t=a.get(e.op_id);return t?{...t,replayed:!0}:{...e,message:Kt}})}function fr(e,t,n){const r=new Map(t.map(e=>[e.op_id,e]));return{ops:e.filter(e=>void 0===n||e.item_id===n).map(e=>({op_id:e.op_id,kind:e.kind,path:e.path??null,status:r.get(e.op_id)?.status??"not_sent"}))}}var hr,yr,gr=D({"src/core/agent-saving.ts"(){pt(),Xt(),P(),yt="rollout_switched:multiuser_saving: This project now saves each change on its own. Reload ATOMS to continue. For atoms-mcp, do not retry: set its args to @atoms-tech/atoms-mcp@latest and restart.",gt="rollout_switched:multiuser_saving: This project now saves one field at a time. Do not retry. Change the args in your MCP client config to @atoms-tech/atoms-mcp@latest and restart it.".replace("rollout_switched:multiuser_saving: ",""),wt="Do not retry this call. Tell the person to change the args of the atoms server in their MCP client config to @atoms-tech/atoms-mcp@latest and restart the client.",vt="This project is in the Trash. Nothing was saved. A project admin can restore it in ATOMS, then try again.",bt="PROJECT_IN_TRASH",jt="You no longer have access to this project. Ask an admin of its organization to add you back.",kt="PROJECT_ACCESS_LOST",St=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,At=2e3,It=20,xt=[["title"],["summary"],["body"],["req_type"],["status"],["tags","domains"],["tags","level"]],$t=[["title"],["body"],["analysis_props"],["relationships"]],Et=new Set(["item","all","analysis","core","variable"]),qt=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.([0-9a-f]{16})~(.+)$/i,Ot=new Set(["title","type","approver_user_id","requires_impacted_approval"]),Rt=new Set(["variables","taxonomy","settings"]),Tt={'["title"]':"Title",'["summary"]':"Summary",'["body"]':"Body",'["req_type"]':"Type",'["type"]':"Type",'["status"]':"Status",'["tags","level"]':"Level",'["tags","domains"]':"Domains",'["asil_confirm_lower"]':"ASIL"},Mt=new Set(["applied","noop","replaced"]),zt=4e3,Ct=65536,Dt=600,Ht=200,Ut="Changes under applied are saved; do not send them again. Tell the person which changes were not saved and why.",Pt="For each conflict: merge theirs_value with your change, then call the tool again with that entry's base_token.",Nt="For a field someone is typing in: offer to try again in a minute.",Lt="For a locked item: ask the person it is locked to, or an admin, to unlock it.",Ft="For a change with no base: read the item with atoms_get_item, or use the entry's base_token, then send it again.",Wt=["your_value","theirs_value","base_value"],Vt="0b7e5c1a-3d2f-4e6b-9a8c-1f2e3d4c5b6a",Bt=e=>[...new Set((e??[]).map(e=>String(tr(e))))].sort(),Jt=50,Qt=500,Gt="Could not read how this project saves, so nothing was saved. Try again.",Kt="idempotency_key already used for a different change; use a new key.",Yt="Already created by an earlier identical call. Nothing new was created. To create another copy, call again with a new idempotency_key.",Zt=500}});function wr(e){const t=hr.exec(e);return t?t[1]:null}var vr,br,jr,kr,Sr,Ar,Ir,xr=D({"src/core/rollout-errors.ts"(){hr=/rollout_switched:([a-z][a-z0-9_]{2,62})/,yr="This project's saving rules just changed. Read the item again, then retry your change."}});function $r(e,t){const n=jr.indexOf(String(e??"")),r=jr.indexOf(String(t??""));return n<0||r<0?vr:kr[n][r]}function Er(e){return"Moderate"===e||"High"===e||"Very High"===e}var qr,Or,Rr,Tr=D({"src/core/securityScheme.ts"(){vr="-",br=["Very Low","Low","Moderate","High","Very High"],jr=["1","2","3","4","5"],kr=[["Very Low","Very Low","Very Low","Low","Low"],["Very Low","Very Low","Low","Low","Moderate"],["Very Low","Low","Low","Moderate","Moderate"],["Low","Low","Moderate","Moderate","High"],["Low","Moderate","High","High","Very High"]],Sr={"Very Low":"meets the acceptance criteria",Low:"meets the acceptance criteria",Moderate:"acceptable only with a recorded justification",High:"does not meet the acceptance criteria","Very High":"does not meet the acceptance criteria"},Ar=[{id:"authentication",label:"Authentication",abbr:"Auth"},{id:"authorization",label:"Authorization",abbr:"AuthZ"},{id:"cryptography",label:"Cryptography",abbr:"Crypto"},{id:"code_data_execution_integrity",label:"Code, data and execution integrity",abbr:"Integrity"},{id:"confidentiality",label:"Confidentiality",abbr:"Confid"},{id:"event_detection_logging",label:"Event detection and logging",abbr:"Detect"},{id:"resiliency_recovery",label:"Resiliency and recovery",abbr:"Resil"},{id:"firmware_software_updates",label:"Firmware and software updates",abbr:"Update"}],Ir={id:"The row id. The prefix comes from the scheme: SEC for the analysis, CYB for its rows.",asset:"The thing worth protecting, the seed of a row.",threat_event:"What the adversary does, one per row.",vulnerability:"The weakness the threat event exploits.",impact:"What the attacker achieves on the device.",harm:"The consequence for the patient, the data or the delivery of care.",s:"Severity and pervasiveness: how bad the consequence is and how widely it reaches, 1 to 5. The anchor for each level is in the glossary.",e:"The ease with which the vulnerability can be exploited, assessed across the device lifecycle. It is not a probability. Score the worst case, or write the reason for a lower score in the E rationale (FDA premarket guidance 2026, V.A.2).",risk:"Derived from S and E through the one fixed matrix of the scheme. Acceptability is judged on the residual risk, not here.",security_control:"One control per risk, stated as a requirement the device shall meet.",mit:"The requirements that carry this control, each with one of the eight FDA control categories on the link.",haz:"The ISO 14971 risk rows this security risk affects. Nothing is derived from the link onto the risk row ratings.",safety_impact:"Whether this security risk creates or worsens a pathway to patient harm. Yes means it is transferred into the ISO 14971 file and linked to the risk rows it affects. No means the consequence stays inside security. The answer needs a written reason either way.",safety_impact_justification:"Why this does or does not reach a patient. Required whichever way the answer goes.",assumptions:"One assumption per line. Non normative: it saves live with no change record.",s_rationale:"The evidence for the S rating.",e_rationale:"The evidence for the E rating. Say here why a score lower than the worst case is justified.",residual_s:"Severity and pervasiveness after the control is in place.",residual_e:"Exploitability after the control is in place.",residual_risk:"The same fixed matrix applied to Residual S and Residual E. Acceptability is judged here: Very Low and Low meet the acceptance criteria, Moderate is acceptable only with a recorded justification, High and Very High do not meet them.",justification:"Why this control and why the residual is accepted. Required when the residual is Moderate or worse, and on any row at S5 or Residual S5 whatever the band.",verified:"The test cases that verify the linked control requirements. A row with links and no test case counts as a control not verified.",chgstatus:"The approval state of the row under change control, with its revision.",authentication:"Proving the identity of a user, an endpoint, or a piece of information (FDA Appendix 1).",authorization:"Deciding what an authenticated identity may do, evaluated on every action.",cryptography:"Protecting data in transit and at rest with validated algorithms and key handling.",code_data_execution_integrity:"Proving that code, data and the running artefact are what the manufacturer released.",confidentiality:"Keeping data readable only by those entitled to read it.",event_detection_logging:"Recording security relevant events so they can be detected and reconstructed afterwards.",resiliency_recovery:"Keeping the device usable under attack or failure, and recovering it afterwards.",firmware_software_updates:"Delivering and verifying updates to the device across its lifecycle.",threat_model_method:"The methodology used to enumerate threats (for example STRIDE), and why it was chosen for this system boundary.",environment_assumptions:"What is assumed about the environment the device operates in, one per line (for example: assume the hospital network is hostile).",attack_surfaces:"The interfaces and entry points considered, one per line.",lifecycle_sources:"The device lifecycle stages considered as a source of threats (FDA premarket guidance V.A.1): supply chain, manufacturing, deployment, interoperation, maintenance and update, decommission.",related_documents:"Where the software bill of materials, the security testing report and the architecture views live.",overall_residual_risk:"The residual risk conclusion of the security risk assessment (AAMI TIR57), one of the five bands, judged by a person against every row's residual risk."}}});function Mr(e){return`${e.join(", ")} cannot be written through atoms_fill_row: the acceptance is recorded by a person in the app; it is never written over MCP.`}function zr(e){return`${e}. The signed-in person records that the analysis is accepted, with the date and the open gaps by kind copied at that moment. It is not computed from the rows. Row approval is a separate act. ${Rr}`}function Cr(e){const t=e??{},n="accepted"===t.acceptance_state?"accepted":"draft",r=Array.isArray(t.open_gaps_at_acceptance)?t.open_gaps_at_acceptance.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.kind):[];return{acceptance_state:n,accepted_by:"string"==typeof t.accepted_by?t.accepted_by:null,accepted_at:"string"==typeof t.accepted_at?t.accepted_at:null,acceptance_note:"string"==typeof t.acceptance_note?t.acceptance_note:"",open_gaps_at_acceptance:r}}function Dr(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function Hr(e){const t=e?.analysis_props,n={...t&&"object"==typeof t?t:{}},r=function(e){return"accepted"===e.acceptance_state&&(e.prev_accepted_by=e.accepted_by??null,e.prev_accepted_at=e.accepted_at??null,e.acceptance_state="draft",e.accepted_by=null,e.accepted_at=null,!0)}(n);return{revoked:r,parentProps:n}}async function Ur(e,t,n){const r=`${t} saved but ${e} is still accepted: clearing its acceptance failed. Open the analysis and re-accept it, or call atoms_fill_row on a row to clear it.`;try{for(let e=0;e<3;e+=1){const t=await n.readParent();if(!t)return{revoked:!1,warning:null};const a=t.data??{},{revoked:i,parentProps:s}=Hr(a);if(!i)return{revoked:!1,warning:null};const{error:o}=await n.saveParent(t,{...a,analysis_props:s});if(!o)return{revoked:!0,warning:null};if(!(e<2&&/stale_item_write/i.test(o.message??"")))return n.warn(`acceptance revoke save failed for '${t.id}': ${o.message??"unknown error"}`),{revoked:!1,warning:r}}return{revoked:!1,warning:r}}catch(e){return n.warn(`acceptance revoke failed: ${e instanceof Error?e.message:String(e)}`),{revoked:!1,warning:r}}}var Pr,Nr,Lr,Fr,Wr,Vr,Br,Jr,Qr,Gr,Kr,Yr,Zr,Xr,ea,ta,na,ra,aa,ia,sa,oa,la,ca,da,ua,pa,ma,_a,fa,ha,ya,ga,wa,va,ba,ja,ka,Sa,Aa,Ia,xa,$a,Ea,qa,Oa,Ra,Ta,Ma,za=D({"src/core/acceptance.ts"(){qr=["acceptance_state","accepted_by","accepted_at","acceptance_note","open_gaps_at_acceptance"],Or=["prev_accepted_by","prev_accepted_at","accepted_snapshot_id","accepted_snapshot_name"],Rr="This is a record of a decision, not an electronic signature. The signature of record is applied in the manufacturer's own quality system."}});function Ca(e,t,n){return"hara"===e?"tir57"===t?"security_tir57":"iso14971"===t?"hazard_iso14971":"iso26262"===t?"hara_iso26262":"medical"===n?"hazard_iso14971":"hara_iso26262":"process"===t?"fmea_process":"software"===t?"fmea_software":"use"===t?"fmea_use":"design"===t?"dfmea_rpn":"medical"===n?"fmea_process":"dfmea_rpn"}function Da(e){return Nr[e]}function Ha(e){return Lr.some(t=>t.id===e)||function(e){return Ar.some(t=>t.id===e)}(e)}function Ua(e){const t=Array.isArray(e)?e.filter(e=>"string"==typeof e):[],n=t.length>=2?t[1].trim():"";return n?{level:n,source:"taxonomy"}:{level:Wr,source:"fallback"}}function Pa(e){const t=(e??"").trim().toLowerCase();return"sub-system"===t?"subsystem":t}function Na(e,t){const n=Ua(e),r=Ua(t);return Pa(n.level)===Pa(r.level)?null:`Warning: this changes the system level (the ladder's second rung, L1) from "${n.level}" to "${r.level}". HARA and risk-analysis gap classification (the no_parent / bridge gap) is judged against the system level, so gap results for this project's hazard analyses may change. Re-check atoms_get_gaps on affected analyses.`}function La(e){return"hazard_iso14971"===e?ia:"security_tir57"===e?ca:[]}function Fa(e){return"security_tir57"===e?br:sa}function Wa(e){return String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e)}function Va(e){const t=e??{};return{intended_use:String(t.intended_use??"").trim(),foreseeable_misuse:Wa(t.foreseeable_misuse),safety_characteristics:Wa(t.safety_characteristics)}}function Ba(e,t=sa){const n=e??{},r=String(n.overall_residual_risk??"").trim(),a=String(n.software_safety_class??"").trim();return{residual_risk:t.includes(r)?r:"",residual_rationale:String(n.overall_residual_rationale??"").trim(),safety_class:oa.includes(a)?a:"",safety_rationale:String(n.software_safety_rationale??"").trim()}}function Ja(e){return""!==Va(e).intended_use}function Qa(e,t){const n=La(e);if(0===n.length)return`An analysis parent of scheme ${e} carries no fillable field: ${t.join(", ")} cannot be written on it. Only the ISO 14971 risk analysis carries a scope and an overall residual risk.`;const r=n.filter(e=>!e.endsWith("_rationale"));return`Unknown field(s) for the analysis parent: ${t.join(", ")}. Allowed: ${r.join(", ")} (+ _rationale for the last two)`}function Ga(e,t,n){return`Invalid ${e} value ${JSON.stringify(t)}. Allowed: ${n.join(", ")}`}function Ka(e){return"risk_analysis"===e||"hazard_analysis"===e?["iso14971"]:"security_risk"===e?["tir57"]:Pr[_a[e]]}function Ya(e){return Object.entries(Sa[e]).map(([e,t])=>({key:e,label:t}))}function Za(e){return Object.entries(function(e){return"hara_iso26262"===e?wa:"dfmea_rpn"===e?ja:"hazard_iso14971"===e?ba:"security_tir57"===e?Ir:ka}(e)).map(([e,t])=>({key:e,text:t}))}function Xa(e){return"hazard_iso14971"===e?Xr:"security_tir57"===e?Sr:null}function ei(e,t){const n=Xa(e);return n?n[t]??null:null}function ti(e){return(e??"").trim().toLowerCase()}function ni(e,t){const n=ti(e);if(!n)return null;for(const e of t)if(ti(e)===n)return e;return null}function ri(e){const t=e?.severity||"",n=e?.exposure||"",r=e?.controllability||"";return t&&n&&r?"S0"===t||"E0"===n||"C0"===r?"QM":Qr[`${t}-${n}-${r}`]||Br:Br}function ai(e){const t=parseInt(e?.severity||"",10),n=parseInt(e?.occurrence||"",10),r=parseInt(e?.detection||"",10);return Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r)?Br:String(t*n*r)}function ii(e,t,n){const r=String(e??""),a=String(t??""),i=String(n??"");if(Kr.indexOf(r)<0||Kr.indexOf(a)<0||Kr.indexOf(i)<0)return Br;const s=Yr[`${a}-${i}`];return s&&Zr[`${s}-${r}`]||Br}function si(e){return ii(e?.severity,e?.p1,e?.p2)}function oi(e){return ii(e?.residual_s,e?.residual_p1,e?.residual_p2)}function li(e){return $r(e?.severity,e?.exploitability)}function ci(e){return $r(e?.residual_s,e?.residual_e)}function di(e,t){return"hara_iso26262"===e?ri(t):"hazard_iso14971"===e?si(t):"security_tir57"===e?li(t):"fmea_software"===e?function(e){return ai({...e??{},occurrence:ea})}(t):ai(t)}function ui(e,t,n){if(n)return!1;if("hara_iso26262"===e){const e=ri(t);return"C"===e||"D"===e}if("hazard_iso14971"===e)return"High"===si(t);if("security_tir57"===e){const e=li(t);return"High"===e||"Very High"===e}const r=parseInt(di(e,t),10);return!Number.isNaN(r)&&r>=200}function pi(e,t,n){if(!e?.approved||!e.approved_at)return!1;const r=Date.parse(e.approved_at);return!Number.isNaN(r)&&[...e.source_req?[e.source_req]:[],...t].some(e=>{const t=n(e),a=t?Date.parse(t):NaN;return!Number.isNaN(a)&&a>r})}function mi(e,t){const n=function(e){return"hara_iso26262"===e?"asil":"hazard_iso14971"===e||"security_tir57"===e?"risk":"rpn"}(e);return`Field${t.length>1?"s":""} ${t.join(", ")} cannot be written: ${n} is derived from the ratings and the approval keys are recorded by atoms_approve_row. Write the ratings instead and read ${n} back as computed_level.`}function _i(e){return"fmea_software"===e?{field:"occurrence",value:ea}:null}function fi(e){const t=_i(e);return t?`Field ${t.field} is fixed at ${t.value} in a Software FMEA (IEC 62304: software failure probability is assumed 100 percent), so the RPN follows severity and detection. Omit it.`:""}function hi(e){return $a[e]}function yi(e){return"security_tir57"===e?Ar:function(e){return"hazard_iso14971"===e||"fmea_process"===e||"fmea_software"===e||"fmea_use"===e}(e)?Lr:[]}function gi(e){return yi(e).map((e,t)=>({...e,precedence:t+1}))}function wi(e){return"security_tir57"===e?`control_type is required for a security control link (FDA Appendix 1). Choose one of: ${Ar.map(e=>`${e.id} (${e.label})`).join(", ")}.`:`control_type is required for a risk control link (ISO 14971 clause 7). Choose one of: ${Lr.map(e=>`${e.id} (${e.label})`).join(", ")}.`}function vi(e){if(null==e||""===e)return null;if("number"==typeof e)return Number.isInteger(e)?e:null;if("string"!=typeof e||!/^\s*\d+\s*$/.test(e))return null;const t=parseInt(e,10);return Number.isNaN(t)?null:t}function bi(e){const t=parseInt(e,10);return!Number.isNaN(t)&&t>=100}function ji(e){return"hara_iso26262"===e?Oa:"hazard_iso14971"===e?Ra:"security_tir57"===e?Ma:Ta}function ki(e){return!0===e.approved&&(e.approved=!1,e.approved_at=null,e.approved_by=null,e.approved_note="",!0)}function Si(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function Ai(e,t,n=ti){const r=new Set(t.map(n).filter(e=>e.length>0));return e.filter(e=>r.has(n(e)))}function Ii(e){const t=e.length>1;return`Function-flagged tag${t?"s":""} used as domain${t?"s":""}: ${e.join(", ")}. A function is not a domain tag: seed a HARA row with it instead (atoms_create_analysis source_functions, or atoms_fill_row source_function), or unflag it (atoms_update_domain with is_function=false, or Taxonomy Management).`}var xi,$i,Ei,qi,Oi=D({"src/core/analysis.ts"(){Tr(),Tr(),za(),Pr={hara:["iso26262","iso14971","tir57"],dfmea:["design","process","software","use"]},Nr={hara_iso26262:"ISO 26262",hazard_iso14971:"ISO 14971",dfmea_rpn:"AIAG-VDA FMEA Handbook",fmea_process:"AIAG-VDA FMEA Handbook",fmea_software:void 0,fmea_use:void 0,security_tir57:"AAMI TIR57"},Lr=[{id:"inherent",label:"Inherent design",abbr:"ID"},{id:"protective",label:"Protective measure",abbr:"PM"},{id:"information",label:"Information for safety",abbr:"IFS"}],Fr="safety",Wr="L1",Vr=8,Br="-",Jr=["prevention","detection","mitigation"],Qr={"S1-E1-C1":"QM","S1-E1-C2":"QM","S1-E1-C3":"QM","S1-E2-C1":"QM","S1-E2-C2":"QM","S1-E2-C3":"QM","S1-E3-C1":"QM","S1-E3-C2":"QM","S1-E3-C3":"A","S1-E4-C1":"QM","S1-E4-C2":"A","S1-E4-C3":"B","S2-E1-C1":"QM","S2-E1-C2":"QM","S2-E1-C3":"QM","S2-E2-C1":"QM","S2-E2-C2":"QM","S2-E2-C3":"A","S2-E3-C1":"QM","S2-E3-C2":"A","S2-E3-C3":"B","S2-E4-C1":"A","S2-E4-C2":"B","S2-E4-C3":"C","S3-E1-C1":"QM","S3-E1-C2":"QM","S3-E1-C3":"A","S3-E2-C1":"QM","S3-E2-C2":"A","S3-E2-C3":"B","S3-E3-C1":"A","S3-E3-C2":"B","S3-E3-C3":"C","S3-E4-C1":"B","S3-E4-C2":"C","S3-E4-C3":"D"},Yr={"1-1":"1","1-2":"1","1-3":"1","1-4":"2","1-5":"3","2-1":"1","2-2":"1","2-3":"2","2-4":"3","2-5":"4","3-1":"1","3-2":"2","3-3":"3","3-4":"4","3-5":"5","4-1":"2","4-2":"3","4-3":"4","4-4":"5","4-5":"5","5-1":"3","5-2":"4","5-3":"5","5-4":"5","5-5":"5"},Zr={"1-1":"Low","1-2":"Low","1-3":"Low","1-4":"Low","1-5":"Medium","2-1":"Low","2-2":"Low","2-3":"Low","2-4":"Medium","2-5":"Medium","3-1":"Low","3-2":"Low","3-3":"Medium","3-4":"Medium","3-5":"High","4-1":"Low","4-2":"Medium","4-3":"Medium","4-4":"High","4-5":"High","5-1":"Medium","5-2":"Medium","5-3":"High","5-4":"High","5-5":"High"},Xr={Low:"Acceptable",Medium:"Acceptable with justification",High:"Not acceptable"},ea="10",ta={hara_iso26262:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea_rpn:{severity:Gr=["1","2","3","4","5","6","7","8","9","10"],occurrence:Gr,detection:Gr},hazard_iso14971:{severity:Kr=["1","2","3","4","5"],p1:Kr,p2:Kr,residual_s:Kr,residual_p1:Kr,residual_p2:Kr},fmea_process:{severity:Gr,occurrence:Gr,detection:Gr},fmea_software:{severity:Gr,detection:Gr},fmea_use:{severity:Gr,occurrence:Gr,detection:Gr},security_tir57:{severity:[...jr],exploitability:[...jr],residual_s:[...jr],residual_e:[...jr]}},na={hara_iso26262:["failure_mode","operating_scenario","hazard","assumptions","severity","exposure","controllability","safe_state","ftti","rationale","source_function","safety_goal","s_rationale","e_rationale","c_rationale"],dfmea_rpn:["failure_mode","cause","severity","occurrence","detection","rationale"],hazard_iso14971:["failure_mode","operating_scenario","hazard","assumptions","severity","p1","p2","rationale","source_function","safety_goal","s_rationale","p1_rationale","p2_rationale","residual_s","residual_p1","residual_p2","benefit_note"],fmea_process:["process_step","failure_mode","cause","severity","occurrence","current_controls","detection","rationale"],fmea_software:["failure_mode","cause","severity","detection","rationale"],fmea_use:["failure_mode","cause","severity","occurrence","detection","rationale"],security_tir57:["failure_mode","operating_scenario","hazard","assumptions","severity","exploitability","rationale","source_function","safety_goal","s_rationale","e_rationale","residual_s","residual_e","justification","safety_impact","safety_impact_justification"]},ra=["intended_use","foreseeable_misuse","safety_characteristics"],aa=["overall_residual_risk","overall_residual_rationale","software_safety_class","software_safety_rationale"],ia=[...ra,...aa],sa=["Low","Medium","High"],oa=["A","B","C"],la=["threat_model_method","threat_model_rationale","environment_assumptions","attack_surfaces","related_documents","overall_residual_risk","overall_residual_rationale"],ca=[...la,"lifecycle_sources"],da={hara:"safety-goal",dfmea:"failure-mode"},ua={hara_iso26262:"SG",dfmea_rpn:"FM",hazard_iso14971:"RSK",fmea_process:"PF",fmea_software:"FM",fmea_use:"FM",security_tir57:"CYB"},pa={hara_iso26262:"HARA",dfmea_rpn:"DFMEA",hazard_iso14971:"RA",fmea_process:"PFMEA",fmea_software:"SFMEA",fmea_use:"UFMEA",security_tir57:"SEC"},ma=["HA"],Array.from(new Set([...Object.values(pa),...Object.values(ua),...ma])).sort(),_a={hara:"hara",dfmea:"dfmea",risk_analysis:"hara",fmea:"dfmea",hazard_analysis:"hara",security_risk:"hara"},fa=["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"],ha={hara:"iso26262",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"design",fmea:"process",security_risk:"tir57"},ya={hara:"iso14971",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"process",fmea:"process",security_risk:"tir57"},ga={fmea_failure_mode:"Failure mode: the way the design, the process step or the software fails to do what it should, for example a valve that sticks open or a step skipped.",fmea_effect:"Effect: what the failure mode does to the customer, the patient or the next step of the process. Severity rates the effect.",fmea_cause:"Cause: the mechanism or condition behind the failure mode, what has to be true for it to happen. Occurrence rates the cause.",fmea_action:"Action: the requirement that answers the failure mode. The link records how it answers it, and a row at RPN 100 or above with no action is a gap."},wa={...ga,s:"Severity: how badly people could be hurt if the hazardous event happens. S0 no injuries, S1 light, S2 severe but survivable, S3 life-threatening or fatal (ISO 26262-3).",e:"Exposure: how often the operational scenario occurs. E0 incredible, E1 very low, E2 low, E3 medium, E4 high probability (ISO 26262-3).",c:"Controllability: how likely the driver or others can avoid the harm. C0 controllable in general, C1 simply, C2 normally, C3 difficult or uncontrollable (ISO 26262-3).",asil:"Automotive Safety Integrity Level: computed from S, E and C per ISO 26262-3 Table 4. QM means no safety requirement is needed; D is the most demanding.",safe_state:"The condition the system moves to when the function fails, for example handing braking back to the driver.",ftti:"Fault tolerant time interval: the longest time a fault may stay undetected before the hazardous event can occur.",safety_goal:"The top-level safety requirement derived from a hazardous event. One goal per HARA row; it is met by safety requirements that mitigate it.",safety_req:"A requirement of type Safety that mitigates a safety goal. At L1 it is a functional or technical safety requirement and traces to a system requirement.",verified_by:"The test case that proves this safety goal on its operating design domain (ODD).",hazardous_event:"What happens to the vehicle and the people when the failure occurs in this scenario. One per row.",hazard:"The potential harm, for example unintended braking.",assumptions:"The conditions you assume for the rating, one per line, for example light traffic or a speed limit.",fn:"The system function this row analyses, from the project's function tags.",failure_mode:"How the function fails: no function, loss, partial, degradation or misinterpretation.",scenario:"The driving situation in which the failure is analysed. One per row.",dfmea_s:"Severity: how serious the effect of the failure is for the customer, 1 (no effect) to 10 (safety or regulatory failure without warning).",o:"Occurrence: how likely the cause is, 1 (remote) to 10 (very high).",d:"Detection: how likely current controls detect the cause before it reaches the customer, 1 (certain) to 10 (impossible).",rpn:"Risk priority number: S times O times D. Rows at 100 or above are gaps.",accept_analysis:zr("The confirmation review of the HARA (ISO 26262)")},va={s:"Severity: a measure of the possible consequences of a hazard. 1 Negligible, 2 Minor, 3 Serious, 4 Critical, 5 Catastrophic (ISO 14971).",p1:"P1: the probability of a hazardous situation occurring. 1 Improbable, 2 Remote, 3 Occasional, 4 Probable, 5 Frequent (the example scale of ISO 14971:2007 Annex D, kept in ISO/TR 24971).",p2:"P2: the probability that the hazardous situation leads to harm, given that it occurs. 1 to 5 on the same scale (ISO 14971:2007 Annex D, ISO/TR 24971).",p0:"P0: the overall probability of harm, looked up from P1 and P2 on the 5 by 5 probability table.",risk:"Risk: the combination of the probability of harm and its severity, looked up from P0 and S. Low is acceptable, Medium is acceptable with a justification, High is not acceptable (ISO 14971).",risk_analysis:"Risk analysis: the systematic use of available information to identify hazards and to estimate the risk for each hazardous situation (ISO 14971:2019 definition 3.19 and clause 5). It is the name the standard gives this document.",hazard:"Hazard: a potential source of harm, for example an uncontrolled flow of the drug.",hazardous_situation:"Hazardous situation: the circumstance in which people are exposed to the hazard.",sequence:"Sequence of events: what has to happen for the hazard to become a hazardous situation. One sequence per row.",harm:"Harm: injury or damage to the health of people, or damage to property or the environment.",assumptions:"The conditions you assume for the estimate, one per line, for example the care setting or the patient group.",fn:"The device function this row analyses, from the project's function tags.",risk_control:"Risk control: the measure that reduces the risk. Applied in order: inherent safety by design, then protective measures, then information for safety (ISO 14971 clause 7).",control_req:"A requirement of type Risk control that implements a risk control measure. It carries the control type and traces to a system requirement.",verified_by:"Verification of effectiveness: the test that shows the risk control works, not only that it was implemented (ISO 14971 clause 7.2).",residual:"Residual risk: the risk remaining after the risk control measures are applied, estimated with the same two tables.",benefit:"Benefit-risk analysis: the argument that the medical benefit outweighs a residual risk that is still not acceptable (ISO 14971 clause 7.4).",dfmea_s:"Severity: how serious the effect of the failure is, 1 (no effect) to 10 (harm without warning).",o:"Occurrence: how likely the cause is, 1 (remote) to 10 (very high).",o_sw:"IEC 62304: software failure probability is assumed 100 percent; rate by severity.",d:"Detection: how likely current controls detect the cause before it reaches the patient, 1 (certain) to 10 (impossible).",rpn:"Risk priority number: S times O times D. Rows at 100 or above are gaps.",process_step:"The step of the clinical or manufacturing process this row analyses.",controls:"Current controls: what already stands between this cause and the effect.",intended_use:"Intended use: what the device is for, for which patient, by which user and in which environment. ISO 14971:2019 5.2 asks for it before any hazard is identified.",foreseeable_misuse:"Reasonably foreseeable misuse: use in a way the manufacturer did not intend but can expect, one case per line (ISO 14971:2019 5.2).",safety_characteristics:"Characteristics related to safety: the qualitative and quantitative characteristics that could affect safety, one per line (ISO 14971:2019 5.3).",overall_residual_risk:"Overall residual risk: the risk that remains from the device as a whole, once every individual risk is controlled. Judged by a person against the criteria in the risk management plan (ISO 14971:2019 clause 8).",software_safety_class:"Software safety class: A no injury or damage to health is possible, B non-serious injury is possible, C death or serious injury is possible (IEC 62304 4.3)."},ba={...ga,...va,accept_analysis:zr("The ISO 14971 clause 8 overall residual risk conclusion")},ja={...ga,dfmea_s:wa.dfmea_s,o:wa.o,d:wa.d,rpn:wa.rpn,accept_analysis:zr("The AIAG-VDA FMEA sign-off")},ka={...ga,dfmea_s:va.dfmea_s,o:va.o,o_sw:va.o_sw,d:va.d,rpn:va.rpn,process_step:va.process_step,controls:va.controls,fn:va.fn,risk_control:va.risk_control,control_req:va.control_req,verified_by:va.verified_by,accept_analysis:zr("The FMEA sign-off")},Sa={hara_iso26262:{source_function:"Function",failure_mode:"Failure Mode",operating_scenario:"Operational Scenario",effect:"Hazardous Event",hazard:"Hazard",assumptions:"Assumptions",s_rationale:"S evidence",e_rationale:"E evidence",c_rationale:"C evidence",safe_state:"Safe state",ftti:"FTTI",severity:"S",exposure:"E",controllability:"C",safety_goal:"Safety goal",asil:"ASIL"},dfmea_rpn:{source_req:"Source",failure_mode:"Failure Mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",detection:"D",rpn:"RPN"},hazard_iso14971:{source_function:"Function",failure_mode:"Hazard",operating_scenario:"Sequence of events",effect:"Hazardous situation",hazard:"Harm",assumptions:"Assumptions",s_rationale:"S rationale",p1_rationale:"P1 rationale",p2_rationale:"P2 rationale",residual_s:"Residual S",residual_p1:"Residual P1",residual_p2:"Residual P2",residual_level:"Residual risk",benefit_note:"Benefit-risk note",severity:"S",p1:"P1",p2:"P2",safety_goal:"Risk control statement",risk:"Risk"},fmea_process:{source_req:"Source",process_step:"Process step",failure_mode:"Failure mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",current_controls:"Current controls",detection:"D",rpn:"RPN"},fmea_software:{source_req:"Source",failure_mode:"Failure Mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",detection:"D",rpn:"RPN"},fmea_use:{source_req:"Source",failure_mode:"Failure Mode",effect:"Effect",severity:"S",cause:"Cause",occurrence:"O",detection:"D",rpn:"RPN"},security_tir57:{source_function:"Asset",failure_mode:"Threat event",operating_scenario:"Vulnerability",effect:"Impact",hazard:"Harm",assumptions:"Assumptions",s_rationale:"S rationale",e_rationale:"E rationale",residual_s:"Residual S",residual_e:"Residual E",residual_level:"Residual risk",severity:"S",exploitability:"E",risk:"Risk",safety_goal:"Security control statement",safety_impact:"Safety impact",safety_impact_justification:"Safety impact justification",justification:"Justification"}},Aa=["asil","rpn","risk","p0"],Ia=["approved","approved_at","approved_by","approved_note","field_source","link_roles","mitigation_types"],xa=[...Aa,...Ia],$a={hara_iso26262:{parent:"HARA",row:"Safety goal",row_statement:"Safety goal",mitigating_requirement:"Safety requirement",lane:"Safety lane",level:"ASIL"},dfmea_rpn:{parent:"DFMEA",row:"Failure mode",row_statement:"Action",mitigating_requirement:"Requirement",lane:"Safety lane",level:"RPN"},hazard_iso14971:{parent:"Risk analysis",row:"Risk",row_statement:"Risk control statement",mitigating_requirement:"Risk control",lane:"Risk lane",level:"Risk"},fmea_process:{parent:"PFMEA",row:"Process failure",row_statement:"Action",mitigating_requirement:"Risk control",lane:"Risk lane",level:"RPN"},fmea_software:{parent:"Software FMEA",row:"Failure mode",row_statement:"Action",mitigating_requirement:"Risk control",lane:"Risk lane",level:"RPN"},fmea_use:{parent:"Use FMEA",row:"Failure mode",row_statement:"Action",mitigating_requirement:"Risk control",lane:"Risk lane",level:"RPN"},security_tir57:{parent:"Security risk analysis",row:"Security risk",row_statement:"Security control statement",mitigating_requirement:"Security control",lane:"Security lane",level:"Risk"}},Ea=(e,t,n)=>1===e?t:n,Oa=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft safety requirement",label:e=>`${e} ${Ea(e,"safety goal","safety goals")} unmitigated`,matches:e=>e.level!==Br&&"QM"!==e.level&&!e.linked},{kind:"no_test",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Ea(e,"safety goal","safety goals")} without a test on its ODD`,matches:e=>e.level!==Br&&"QM"!==e.level&&e.linked&&!e.verified},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} ${Ea(e,"safety requirement","safety requirements")} without a system parent`},{kind:"catalog_draft",scope:"analysis",fix:"open_analysis",fixLabel:"Review the scenario catalogs",label:()=>"Scenario catalog not accepted",matchesAnalysis:e=>e.catalogsDraft},qa={kind:"not_accepted",scope:"analysis",fix:"open_analysis",fixLabel:"Accept analysis",label:()=>"Analysis not accepted",matchesAnalysis:e=>e.hasRows&&!e.accepted}],Ra=[{kind:"no_control",scope:"row",fix:"link_requirement",fixLabel:"Draft risk control requirement",label:e=>`${e} ${Ea(e,"risk","risks")} above Low with no control`,matches:e=>e.level!==Br&&"Low"!==e.level&&!e.linked},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Ea(e,"control","controls")} not verified for effectiveness`,matches:e=>e.level!==Br&&"Low"!==e.level&&e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual ${Ea(e,"risk","risks")} not assessed`,matches:e=>e.level!==Br&&"Low"!==e.level&&e.linked&&e.residualLevel===Br},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} risk ${Ea(e,"control","controls")} without a system parent`},{kind:"no_scope",scope:"analysis",fix:"open_analysis",fixLabel:"Open the scope",label:()=>"Scope not stated",matchesAnalysis:e=>e.hasRows&&!e.scopeStated},{kind:"no_overall",scope:"analysis",fix:"open_analysis",fixLabel:"Judge the overall residual risk",label:()=>"Overall residual risk not judged",matchesAnalysis:e=>e.hasRows&&e.everyRowSettled&&!e.overallJudged},qa],Ta=[{kind:"rpn",scope:"row",fix:"link_requirement",fixLabel:"Link a requirement",label:e=>`${e} at RPN 100 or above with no mitigating requirement`,matches:e=>bi(e.level)&&!e.linked},{kind:"severity",scope:"row",fix:"link_requirement",fixLabel:"Link a requirement",label:e=>`${e} at severity 9 or above below RPN 100 with no mitigating requirement`,matches:e=>!bi(e.level)&&null!==e.severity&&e.severity>=9&&!e.linked},qa],Ma=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft security control",label:e=>`${e} security ${Ea(e,"risk","risks")} above Low with no control`,matches:e=>Er(e.level)&&!e.linked},{kind:"unassessed",scope:"row",fix:"open_row",fixLabel:"Rate S and E",label:e=>`${e} not assessed`,matches:e=>e.level===Br},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Ea(e,"control","controls")} not verified`,matches:e=>e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual not assessed`,matches:e=>e.linked&&e.residualLevel===Br},{kind:"no_justification",scope:"row",fix:"open_row",fixLabel:"Write the justification",label:e=>`${e} residual without justification`,matches:e=>{const t=String(e.props?.severity??""),n=String(e.props?.residual_s??""),r="5"===t||"5"===n;return(Er(e.residualLevel)||r)&&!String(e.props?.justification??"").trim()}},{kind:"safety_no_hazard",scope:"row",fix:"open_row",fixLabel:"Link a safety hazard",label:e=>`${e} safety impact Yes with no safety hazard`,matches:e=>"Yes"===e.props?.safety_impact&&!e.affectsLinked},{kind:"safety_no_reason",scope:"row",fix:"open_row",fixLabel:"Write the reason",label:e=>`${e} safety impact without a reason`,matches:e=>("Yes"===e.props?.safety_impact||"No"===e.props?.safety_impact)&&!String(e.props?.safety_impact_justification??"").trim()},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} security ${Ea(e,"control","controls")} without a system parent`},{kind:"no_scope",scope:"analysis",fix:"open_analysis",fixLabel:"Open the threat model",label:()=>"Threat model not stated",matchesAnalysis:e=>e.hasRows&&!e.scopeStated}]}});async function Ri(e,t){const{data:n,error:r}=await e.rpc("project_item_domain_tags",{p_project_id:t});if(r)throw new Error(`item domain read failed: ${r.message}`);if(!Array.isArray(n))throw new Error("item domain read failed: the answer was not a list of tags");return n.filter(e=>"string"==typeof e)}function Ti(e){if(e instanceof $i)return e.names;if(e&&"object"==typeof e&&e.code===xi){const t=e.names;if(Array.isArray(t))return t.filter(e=>"string"==typeof e)}return null}async function Mi(e,t,n,r){const a=await Ri(e,t),i=r.includes(n)||a.includes(n)?n:ni(n,r)??ni(n,a);return{spelling:i,registered:null!==i&&r.includes(i),carried:a.filter(e=>null!==ni(e,[n]))}}async function zi(e,t,n){let r=0;for(const a of n){const{count:n,error:i}=await e.from("items").select("id",{count:"exact",head:!0}).eq("project_id",t).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(i)throw new Error(`item count failed: ${i.message}`);r+="number"==typeof n?n:0}return r}function Ci(e){return 0===e.length?{}:{unregistered_functions:[...e],function_warning:qi}}function Di(e){return`Domain "${e}" registered. You can now tag items with domains=["${e}"].`}function Hi(e,t){return t?`Domain "${e}" already exists as a function, and a function is not a domain tag. To tag items with it, unflag it first: atoms_update_domain with name "${e}" and is_function=false.`:`Domain "${e}" already exists in this project.`}function Ui(e){return`Domain "${e}" already exists. Choose a different name.`}function Pi(e){return`Domain "${e}" is already flagged as a function. Nothing changed.`}function Ni(e){return`"${e}" is already a domain, not a function. Nothing changed.`}function Li(e,t,n){const r=`${t} item${1!==t?"s":""}`;return n?`Dry run: flagging "${e}" as a function would move it out of the Domains group. The ${r} that carry it would keep the tag, and no new item could take it as a domain until it is unflagged (is_function=false). Call again with dry_run=false to apply.`:`Domain "${e}" is now a function. It moved out of the Domains group: the ${r} that carry it keep the tag, and no new item can take it as a domain until you unflag it (is_function=false). Use it through atoms_create_analysis source_functions or atoms_fill_row source_function.`}function Fi(e,t,n){const r=t>0?` ${t} analysis row${1!==t?"s":""} still name${1===t?"s":""} it as their function: they keep the name as text, but it no longer lists under Functions in the sidebar. Flag it again (is_function=true) to restore that.`:"";return n?`Dry run: unflagging "${e}" would turn it back into a domain, so items can be tagged with domains=["${e}"] again.${r} Call again with dry_run=false to apply.`:`"${e}" is a domain again: items can be tagged with domains=["${e}"].${r}`}var Wi,Vi,Bi=D({"src/core/domains.ts"(){Oi(),xi="domain_not_function",$i=class extends Error{code=xi;names;unregistered;constructor(e,t=[]){super(`${xi}: ${e.join(", ")}`),this.name="DomainNotFunctionError",this.names=[...e],this.unregistered=[...t]}},Ei="domain_rename_onto_function",qi="The write was saved, but the function names in unregistered_functions could not be added to the project's Functions list, so the app does not offer them as functions yet. To add one, call atoms_create_domain with its name, then atoms_update_domain with that name and is_function: true."}});function Ji(e,t,n){const r=n("payload has no list to cut, showing a text preview"),a=JSON.stringify(e.data)??"";let i=Math.max(0,t-Vi({...e,data:{preview:""},meta:r})-200);for(;;){const n={...e,data:{preview:a.slice(0,i)},meta:r},s=Vi(n)-t;if(s<=0||0===i)return n;i=Math.max(0,i-s)}}var Qi,Gi,Ki,Yi,Zi,Xi=D({"src/core/response-limit.ts"(){Wi=25e3,Vi=e=>JSON.stringify(e,null,2).length}});function es(){return{status:"error",message:Qi,next_steps:["Do not retry this call","Tell the user that a person can restore it from Trash in ATOMS"],code:Gi,retryable:!1}}function ts(e){const t=e.trashed_by,n=t?.name?.trim()||"Someone";return t?.agent?`${n}'s agent`:n}function ns(e){return(e.deleted_at??"").slice(0,10)}function rs(e,t){const n=`Restored ${e.item_id} from Trash. It was moved there by ${ts(e)} on ${ns(e)}`;return e.trashed_by?.user_id&&e.trashed_by.user_id!==t?`${n}; they have been notified.`:`${n}.`}var as,is,ss,os,ls,cs,ds,us,ps,ms=D({"src/core/restore-confirm.ts"(){Qi="This item has been in Trash for more than 7 days. Only a person can restore it, from Trash in ATOMS.",Gi="item_trash_too_old",Ki=["Show the user this message","Call atoms_restore_item again with confirm: true only after the user agrees"],Yi='Restore an item from Trash (undo a soft-delete made with atoms_delete_item). Two steps:\n\n1. Call without confirm. Nothing is restored. The answer has status "needs_confirmation" and says who moved the item to Trash and when. You MUST show that message to the user and wait for them to agree.\n2. Only after the user agrees, call again with confirm: true. The item is restored and the answer repeats who moved it to Trash; tell the user. The person who moved it to Trash is notified.\n\nAn item that has been in Trash for more than 7 days cannot be restored by an agent (error item_trash_too_old, do not retry): only a person can restore it, from Trash in ATOMS.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): ID of the item in Trash\n - confirm (boolean, optional): true only after the user agreed to the restore\n\nExamples:\n - "Restore the deleted requirement REQ-042" -> atoms_restore_item(project_id, "REQ-042"), show the warning, then atoms_restore_item(project_id, "REQ-042", confirm: true) once the user agrees',Zi="true only after the user has seen the needs_confirmation message and agreed to the restore"}}),_s={};function fs(e,t=is){if("string"!=typeof e)return"";const n=e.replace(ls,"").replace(cs,"");return n.length<=t?n:n.slice(0,t)+"..."}function hs(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function ys(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function gs(e,t,n){return{total_count:e,limit:t,offset:n,has_more:n+t<e}}function ws(e,t,n={}){return{status:"error",message:e,next_steps:t,...n}}function vs(e,t){return ws(`${e} '${fs(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function bs(e){return"account"===e?ws("Account suspended.",["Your ATOMS account is suspended, so ATOMS tools are unavailable","Contact ATOMS support or your organization admin to restore access"]):ws("Organization suspended.",["This project's organization is suspended, so its data is unavailable","Contact your organization admin or ATOMS support to have it reactivated","Projects in your other organizations are unaffected"])}function js(e){const t=/\b(account|organization) suspended\b/i.exec(e);return t?t[1].toLowerCase():null}function ks(e){return ws(`${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 Ss(e,t=ss){return ws(`Validation error: ${fs(e,t)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function As(){return ws("Not authenticated. Run 'npx @atoms-tech/atoms-mcp@latest login' first.",["Run: npx @atoms-tech/atoms-mcp@latest login","Or set ATOMS_ACCESS_TOKEN environment variable"])}function Is(){return ws("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@latest logout && npx @atoms-tech/atoms-mcp@latest login"])}function xs(e){return ws("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 $s(e){return function(e){const t=e&&e>0?Math.ceil(e):ut;return{status:"error",message:"Rate limited: too many requests to ATOMS API.",next_steps:[`Wait ${t} seconds before retrying.`,"Reduce the frequency of back-to-back tool calls"],code:"rate_limited",retryable:!0,retry_after_seconds:t}}(e)}function Es(){return{status:"error",message:"ATOMS could not load your organization's access rules yet, so changes are paused. Reading still works.",next_steps:["Wait a few seconds, then retry the same call","Your saved session is fine: nothing needs doing on your side"],code:"policy_not_loaded",retryable:!0}}function qs(e){return ws(`Parse error: ${fs(e,ss)}`,["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 Os(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function Rs(){return ws("Stale write rejected: this item changed after it was read.",["Call atoms_get_item again and use the returned metadata.updated_at value","Review the current item before retrying so you do not overwrite newer work","Retry atoms_update_item or atoms_link_items with the fresh expected timestamp"])}function Ts(){return ws("Save paused because this item is already being written.",["Wait a few seconds, read the item again, and retry once","Do not repeatedly retry the same stale payload"],{retryable:!0})}function Ms(){return ws("Item saves are temporarily paused by an ATOMS operator.",["Keep your local draft and wait for the operator to re-enable saves","Do not repeatedly retry while the safety brake is active"])}function zs(){return ws("Item save rejected because this item is in Trash.",["Restore the item before changing it","Do not retry the same save while the item remains in Trash"])}function Cs(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const n=e;t="string"==typeof n.message?n.message:"string"==typeof n.code?n.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)}function Ds(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e),n=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";if(r=t,ot.some(e=>e.test(r)))return Ss(t,os);var r;if(e instanceof lt)return Ss(t);if(_t(t))return Hs(e);if(en(t))return tn();if(wr(t))return{status:"error",code:"rollout_switched",retryable:!0,message:yr,next_steps:["Read the item again (atoms_get_item) to get its current state","Apply your change to what you just read, then retry once"]};if(/^auth_unavailable:/.test(t))return Ge();if(/not authenticated/i.test(t))return As();const a=function(e){const t=Ti(e);if(null===t)return null;const n=e.unregistered;return function(e,t=[]){const n=e.map(e=>`"${e}"`).join(", "),r=1===e.length,a=e=>e.trim().toLowerCase(),i=e=>`atoms_update_domain (name: "${a(e)}", is_function: true, dry_run: true)`,s=e.filter(e=>null!==ni(e,t)),o=e.filter(e=>null===ni(e,t)),l=e=>1===e.length?"it":"them",c=o.map(i).join(" and "),d=`${s.map(e=>`atoms_create_domain (name: "${a(e)}")`).join(" and ")}, then preview the flag with ${s.map(i).join(" and ")}`,u=e=>`ask the user, and only if they agree call it again with dry_run: false and use ${l(e)}`,p=[],m=[];o.length>0&&(p.push(`To use ${l(o)} as ${1===o.length?"a function":"functions"}, preview the flag first with ${c}, ${u(o)}.`),m.push(`Preview the flag with ${c}, then ask the user before flagging (dry_run: false)`)),s.length>0&&(p.push(`Register ${l(s)} first with ${d}, ${u(s)}.`),m.push(`Register ${1===s.length?"the tag":"the tags"} (items carry ${l(s)} but the taxonomy does not list ${l(s)}), preview the flag, and ask the user before flagging: ${d}`));const _={code:xi,domains:[...e]};return s.length>0&&(_.unregistered=[...s]),{status:"error",message:`${n} ${r?"is a domain":"are domains"}, not ${r?"a function":"functions"}, so ${r?"it":"they"} cannot be used as ${r?"a function":"functions"} yet. ${p.join(" ")} Flagging moves a tag out of the Domains group: items that already carry it keep the tag, and new items cannot take it as a domain until you unflag it (is_function: false).`,next_steps:[...m,"Or choose a function name that is not already a domain"],details:_}}(t,Array.isArray(n)?n.filter(e=>"string"==typeof e):[])}(e);if(null!==a)return a;if(Cs(e))return Is();if(nn(t))return rn();if(function(e){return/item_trash_too_old/i.test(e)}(t))return es();if(an(t))return sn();const i=cn(t);if(null!==i)return i;const s=on(t);if(null!==s)return s;if("55P03"===n||function(e,t){return"40P01"===e||/deadlock detected/i.test(t)}(n,t)||/item_save_busy/i.test(t))return Ts();if(function(e,t){return!/^[0-9A-Z]{5}$/.test(e)&&/rate.?limit|too many requests|429/i.test(t)}(n,t))return $s();if(Os(t))return Rs();if(/soft_deleted_item_write/i.test(t))return zs();if(/save_temporarily_unavailable/i.test(t))return Ms();if("55P03"===n||"57014"===n||/item_save_busy|statement timeout|request timeout|upstream request timeout/i.test(t))return Ts();const o=js(t);return o?bs(o):"42501"===n&&/org_project_field_admin_required/i.test(t)?ht("organization"):"42501"===n&&/project_field/i.test(t)?ht("project"):"P0002"===n&&/project_field/i.test(t)?ws("Project field not found.",["Refresh the field list and retry with an existing field name"]):["22023","23505","23514"].includes(n)&&/project_field/i.test(t)?Ss(t.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?qs(t):Ps(t)}function Hs(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??"");if(!_t(t)&&!ft(t))return null;const n=t.indexOf(ds);return ws((n>=0?t.slice(n+ds.length):t).trim(),["Wait a moment, read the item again (atoms_get_item), then send your change again"],{code:"rollout_switched",retryable:!0})}function Us(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??""),n=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";return["40001","PT409","55P03","57014"].includes(n)||null!==wr(t)||/stale_item_write|soft_deleted_item_write|save_temporarily_unavailable|item_save_busy|statement timeout|request timeout|upstream request timeout|fetch failed|network error|connection (?:closed|reset|refused)/i.test(t)}function Ps(e){if(/^auth_unavailable:/.test(e))return Ge();if(mt(e))return $s();if(function(e){return/token refresh failed|saved atoms session is no longer valid|jwt\s*expired|invalid.?jwt|jwt.*invalid|pgrst30[12]/i.test(e)}(e))return Is();if(/^not authenticated/i.test(e))return As();if(nn(e))return rn();if(en(e))return tn();if(an(e))return sn();const t=cn(e);if(null!==t)return t;const n=on(e);return null!==n?n:/row.level security|permission denied for/i.test(e)?ws("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"]):ws(`Database error: ${fs(e,ss)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function Ns(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"&lt;/user_content&gt;")}</user_content>`}function Ls(e){return"string"!=typeof e?e:e.replace(/<\s*\/?\s*user_content\s*>/gi,"")}function Fs(e){return us.has(e)}function Ws(e,t,n=!1){return"string"==typeof e?n||null!=t&&us.has(t)?Ns(e):e:Array.isArray(e)?e.map(e=>Ws(e,t,n)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Ws(t,e,n||ps.has(e))])):e}function Vs(e,t={}){const n=t.complete?e:function(e,t=Wi){if(Vi(e)<=t)return e;if("success"!==e.status)return e;const n=n=>({...e.meta??{},truncated:!0,truncation_message:`Response truncated to stay under ${t} characters (${n}). Use 'offset' or 'limit' or add filters to see more results.`});if(Array.isArray(e.data)){const r=e.data.length;let a=e.data,i={...e,data:a,meta:n(`${r} items cut`)};for(;Vi(i)>t&&a.length>1;)a=a.slice(0,Math.max(1,Math.floor(a.length/2))),i={...e,data:a,meta:n(`from ${r} to ${a.length} items`)};return Vi(i)<=t?i:Ji(e,t,n)}if(e.data&&"object"==typeof e.data){const r={...e.data},a=[],i={},s=()=>({...e,data:r,meta:n(`arrays cut: ${a.join(", ")}`)});for(;;){if(Vi(s())<=t)return s();let e,n=0;for(const[t,a]of Object.entries(r))if(Array.isArray(a)&&a.length>1){const r=JSON.stringify(a).length;r>n&&(e=t,n=r)}if(!e)break;const o=r[e];i[e]??=o.length,r[e]=o.slice(0,Math.floor(o.length/2));const l=`${e} ${i[e]} to ${r[e].length}`,c=a.findIndex(t=>t.startsWith(`${e} `));c>=0?a[c]=l:a.push(l)}}return Ji(e,t,n)}(e);return{content:[{type:"text",text:JSON.stringify(Ws(n),null,2)}],structuredContent:n}}function Bs(e){return{content:[{type:"text",text:JSON.stringify(Ws(e),null,2)}],structuredContent:e,isError:!0}}H(_s,{CHARACTER_LIMIT:()=>as,USER_CONTENT_KEYS:()=>us,VALIDATION_MESSAGE_LONG:()=>os,accessDeniedError:()=>ks,authError:()=>As,classifyError:()=>Ds,dbError:()=>Ps,errorResponse:()=>ws,formatErrorResult:()=>Bs,formatToolResult:()=>Vs,isAutoWrappedKey:()=>Fs,isItemSaveStopError:()=>Us,isJwtExpiredErrorForTool:()=>Cs,isStaleWriteErrorMessage:()=>Os,jwtExpiredError:()=>Is,notFoundError:()=>vs,paginationMeta:()=>gs,parseError:()=>qs,policyNotLoadedError:()=>Es,rateLimitError:()=>$s,sanitizeForEcho:()=>fs,sanitizeTagOrLevel:()=>hs,saveBusyError:()=>Ts,saveUnavailableError:()=>Ms,scopeError:()=>xs,softDeletedItemError:()=>zs,staleWriteError:()=>Rs,stripUserContentMarkers:()=>Ls,success:()=>ys,suspendedError:()=>bs,suspensionKind:()=>js,switchRedoFailedError:()=>Hs,validationError:()=>Ss,wrapMcpUserContentFields:()=>Ws,wrapUserContent:()=>Ns});var Js,Qs,Gs,Ks=D({"src/tools/_base.ts"(){Xt(),xr(),Bi(),Ze(),B(),Xi(),gr(),ms(),as=25e3,is=50,ss=200,os=600,ls=new RegExp("[\\u0000-\\u001F\\u007F]","g"),cs=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g"),ds="rollout_switched:multiuser_saving: ",us=new Set(["body","description","domain","domains","error","level","levels","message","name","note","summary","title","value","effect","failure_mode","cause","operating_scenario","safe_state","ftti","rationale","hazard","assumptions","source_function","instruction","test_data","expected","unit","values","actual","not_shown_spellings","unregistered_functions","build","environment","tooling","evidence_url","asset","field_label","presence"]),ps=new Set(["fields","diff","point","theirs_value","base_value","your_value","old_value","new_value"])}});async function Ys(e,t){const n=Qs.get(t),r=Date.now();if(n&&r-n.at<Js)return n.status;const{data:a,error:i}=await e.from("users").select("platform_status").eq("id",t).maybeSingle();if(i)throw i;const s=a?.platform_status??"pending";return Qs.set(t,{status:s,at:r}),s}function Zs(e){return JSON.stringify(Ws(e),null,2)}var Xs,eo,to,no,ro,ao,io,so,oo=D({"src/middleware/status-gate.ts"(){Ks(),Js=3e4,Qs=new Map,Gs="ATOMS MCP is connected. org_suspended lists the suspended organizations visible to you (every suspended organization for a platform admin); their projects are unavailable until a platform admin reactivates them."}}),lo={};async function co(){if(Xs)try{const e=await ye();e&&e.expires_at>ro&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),uo())}catch{}if(Xs&&no>Date.now()+6e4)return Xs;Xs&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:n}=await async function(){if(ao&&Date.now()-ao.at<1e3*Fe)throw ao.error;return io??=tt().then(e=>(ao=null,e)).catch(e=>{throw e instanceof Ve&&(ao={at:Date.now(),error:e}),e}).finally(()=>{io=null}),io}(),a=e.split(".");if(3===a.length)try{const e=JSON.parse(Buffer.from(a[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());no=1e3*(e.exp??0)}catch{no=Date.now()+36e5}try{const e=await ye();ro=e?.expires_at??0}catch{ro=0}const i=r.createClient(Ce,De,{global:{headers:{Authorization:`Bearer ${e}`}}});return eo=t,to=n,Xs=i}function uo(){ao=null,Xs=null,eo=null,to=null,so=void 0,no=0,ro=0,Qs.clear()}function po(e){let t="";if(e instanceof Error)t=e.message;else if(e&&"object"==typeof e){const n=e;t="string"==typeof n.message?n.message:"string"==typeof n.code?n.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 mo(e){try{return await e()}catch(t){if(!po(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),uo(),await e()}}function _o(){if(!eo)throw new Error("Not authenticated. Call getClient() first.");return eo}function fo(){return to??""}async function ho(e){const t=_o();if(so&&so.userId===t)return so.name;try{const{data:n,error:r}=await e.from("users").select("name").eq("id",t).maybeSingle();if(r)return null;const a="string"==typeof n?.name?n.name:null;return so={userId:t,name:a},a}catch{return null}}function yo(e){if(e&&e.deleted_at)throw new Error(bt)}async function go(e,t){const{data:n,error:r}=await e.from("projects").select("deleted_at").eq("id",t).maybeSingle();if(r||!n)throw ln(t,r);yo(n)}async function wo(e,t){const n=_o(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw ln(t,a);yo(r);const{data:i,error:s}=await e.from("org_members").select("role").eq("user_id",n).eq("org_id",r.org_id).maybeSingle();if(s||!i){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"===i.role)throw new Error("VIEWER_ROLE");return i.role}async function vo(e,t){const n=_o(),{data:r,error:a}=await e.from("projects").select("org_id, created_by, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw ln(t,a);yo(r);const{data:i,error:s}=await e.from("org_members").select("role").eq("user_id",n).eq("org_id",r.org_id).maybeSingle();if(s||!i)throw new Error("Not a member of this project's organization");if("admin"===i.role)return"admin";if(r.created_by===n)return"owner";throw new Error("PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED")}H(lo,{assertProjectLive:()=>go,getClient:()=>co,getUserEmail:()=>fo,getUserId:()=>_o,getUserName:()=>ho,invalidateClient:()=>uo,isJwtExpiredError:()=>po,requireProjectFieldDefinitionAccess:()=>vo,requireWriteAccess:()=>wo,throwIfProjectInTrash:()=>yo,withJwtRetry:()=>mo});var bo,jo,ko=D({"src/db/client.ts"(){at(),Ze(),qe(),Je(),gr(),oo(),Xs=null,eo=null,to=null,no=0,ro=0,ao=null,io=null}}),So={};async function Ao(){const e=i.randomBytes(32).toString("base64url"),t=i.createHash("sha256").update(e).digest("base64url"),n=`http://localhost:${bo}${jo}`,r=new s.URL(`${He}/auth/mcp-consent`);return r.searchParams.set("redirect_uri",n),r.searchParams.set("code_challenge",t),r.searchParams.set("code_challenge_method","S256"),new Promise((t,n)=>{let i;function o(){clearTimeout(i)}const l=a.createServer(async(r,a)=>{const i=new s.URL(r.url??"/",`http://localhost:${bo}`);if(i.pathname!==jo)return a.writeHead(404),void a.end("Not found");try{if("access_denied"===i.searchParams.get("error"))return a.writeHead(200,{"Content-Type":"text/html"}),a.end(xo("Authorization was cancelled.")),o(),l.close(),void n(new Error("Authorization cancelled by user."));const r=i.searchParams.get("code");if(r){const i=await fetch(`${Ce}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:De},body:JSON.stringify({auth_code:r,code_verifier:e})}),s=await i.json();if(!i.ok||!s.access_token){const e=s.error_description??s.msg??"Unknown error";return a.writeHead(200,{"Content-Type":"text/html"}),a.end(xo(`Code exchange failed: ${e}`)),o(),l.close(),void n(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(s.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:d}=await import("@supabase/supabase-js"),u=d(Ce,De,{global:{headers:{Authorization:`Bearer ${s.access_token}`}}}),{data:p,error:m}=await u.from("org_members").select("org_id").limit(1);return m||!p||0===p.length?(a.writeHead(200,{"Content-Type":"text/html"}),a.end(xo('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://atoms.tech">atoms.tech</a> first, then run this login command again.')),o(),l.close(),void n(new Error("No ATOMS account found. Sign up at atoms.tech first."))):s.refresh_token?(await ge({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:Date.now()+1e3*(s.expires_in??3600),user_email:c}),a.writeHead(200,{"Content-Type":"text/html"}),a.end(Io(c)),o(),l.close(),void t({email:c})):(a.writeHead(200,{"Content-Type":"text/html"}),a.end(xo("Sign-in succeeded but no refresh token was issued, so the session would expire within the hour. This usually points to a Supabase Auth setting (refresh-token rotation or session policy). Please contact ATOMS support.")),o(),l.close(),void n(new Error("No refresh token issued by Supabase — cannot persist a durable session.")))}const s=i.searchParams.get("access_token"),c=i.searchParams.get("refresh_token"),d=parseInt(i.searchParams.get("expires_in")??"3600",10);s&&c?(await ge({access_token:s,refresh_token:c,expires_at:Date.now()+1e3*d}),a.writeHead(200,{"Content-Type":"text/html"}),a.end(Io("authenticated")),o(),l.close(),t({email:"authenticated"})):(a.writeHead(200,{"Content-Type":"text/html"}),a.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){a.writeHead(500),a.end("Authentication failed"),o(),l.close(),n(e)}});l.on("request",async(e,r)=>{if("POST"===e.method&&"/token"===e.url){let a="";e.on("data",e=>{a+=e.toString()}),e.on("end",async()=>{try{const e=JSON.parse(a);await ge({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})),o(),l.close(),t({email:e.user_email??"authenticated"})}catch(e){r.writeHead(500),r.end("Failed to store credentials"),o(),l.close(),n(e)}})}}),l.listen(bo,"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")}}),i=setTimeout(()=>{l.close(),n(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp@latest login' to try again."))},6e4)})}function Io(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 xo(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>`}H(So,{login:()=>Ao});var $o=D({"src/auth/login.ts"(){qe(),Je(),bo=19275,jo="/callback"}}),Eo={};async function qo(){const{getValidToken:e,readValidToken:t}=await Promise.resolve().then(()=>(at(),Xe)),{runExclusiveAuth:n}=await Promise.resolve().then(()=>(Ue(),Oe)),{login:r}=await Promise.resolve().then(()=>($o(),So));try{return(await e()).email}catch(e){if(e instanceof Ve)return process.stderr.write("[atoms-mcp] ATOMS sign-in check is unavailable right now (auth_unavailable). Your saved session is kept; starting without login. Tool calls retry once it answers.\n"),null;process.stderr.write(`[atoms-mcp] Could not use the saved session: ${e instanceof Error?e.message:String(e)}\n`),process.stderr.write("[atoms-mcp] Starting login flow...\n");const a=async()=>{const e=await t();if(!e)throw new Error("no valid token yet");return{email:e.email}};return(await n(a,async()=>({email:(await r()).email}))).email}}H(Eo,{startupAuth:()=>qo});var Oo,Ro,To,Mo=D({"src/auth/startup.ts"(){Ze()}});function zo(e){const t=e?.asil_pending_lower;if(!t||"object"!=typeof t||Array.isArray(t))return null;const n=t;return"string"==typeof n.level&&Oo.has(n.level)?{level:n.level,source:"string"==typeof n.source?n.source:null,dismissed:!0===n.dismissed}:null}function Co(e,t){if("requirement"!==e.type)return{};const n=e.data??{},r={};"string"==typeof n.asil&&""!==n.asil&&(r.asil=n.asil,r.asil_source="string"==typeof n.asil_source?n.asil_source:null);const a=t.live?zo(e.data):null;return a&&(r.asil_pending_lower={value:a.level,source:a.source,dismissed:a.dismissed,since:t.since}),r}function Do(e){return{op_id:"",status:"forbidden",reason:"asil_lower_needs_person",item_id:e,path:[...Ro],seq:null}}var Ho,Uo,Po,No,Lo=D({"src/core/asil-read.ts"(){Oo=new Set(["QM","A","B","C","D"]),Ro=["asil_confirm_lower"],To="Not accepted from an agent: lowering a requirement's ASIL needs a person (answered forbidden / asil_lower_needs_person, nothing saved). Read asil and asil_pending_lower with atoms_get_item and ask the person to review it in ATOMS."}});function Fo(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Po)if(t.test(e.trim()))return"[redacted]";return e.length>No?e.slice(0,No)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Fo(e,t+1));if(null!==e&&"object"==typeof e){const n={};for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();Ho.has(e)?n[r]="[redacted]":Uo.has(e)?n[r]="string"==typeof a?"[content]":Fo(a,t+1):n[r]=Fo(a,t+1)}return n}return e}function Wo(e){return Fo(e)}var Vo,Bo,Jo,Qo,Go,Ko=D({"src/middleware/audit.ts"(){Ho=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),Uo=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Po=[/^[^\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_-]+$/],No=200}}),Yo=D({"src/middleware/rate-limiter.ts"(){Vo=60,Bo=6e4}});function Zo(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?Jo.test(e)?e:(Qo||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),Qo=!0),null):null}var Xo,el,tl,nl,rl,al,il=D({"src/middleware/project-scope.ts"(){Jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Qo=!1,Go=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}}}}),sl={};function ol(){return T.default.join(t.homedir(),".atoms","update-check.json")}async function ll(){if(!al&&(al=!0,"1"!==process.env.ATOMS_MCP_NO_UPDATE_CHECK))try{const e=await async function(){try{const e=JSON.parse(await o.promises.readFile(ol(),"utf8"));if("number"==typeof e.checked_at&&"string"==typeof e.latest)return{checked_at:e.checked_at,latest:e.latest}}catch{}return null}();if(e&&Date.now()-e.checked_at<el)return void(nl=e.latest);const t=new AbortController,n=setTimeout(()=>t.abort(),tl);try{const e=await fetch(process.env.ATOMS_MCP_UPDATE_URL??Xo,{signal:t.signal});if(!e.ok)return;const n=await e.json();if("string"!=typeof n.version)return;nl=n.version,await async function(e){try{await o.promises.mkdir(T.default.dirname(ol()),{recursive:!0}),await o.promises.writeFile(ol(),JSON.stringify({checked_at:Date.now(),latest:e}),"utf8")}catch{}}(n.version)}finally{clearTimeout(n)}}catch{}}function cl(e){return null!==nl&&function(e,t){const n=/^(\d+)\.(\d+)\.(\d+)$/,r=n.exec(e),a=n.exec(t);if(!r||!a)return!1;for(let e=1;e<=3;e+=1){const t=Number(a[e])-Number(r[e]);if(0!==t)return t>0}return!1}(e,nl)?{current:e,latest:nl,args:["@atoms-tech/atoms-mcp@latest"],command:"npx @atoms-tech/atoms-mcp@latest"}:null}function dl(e){const t=cl(e);return t?dn(t.current,t.latest):null}function ul(e){if(rl)return null;const t=dl(e);return null===t?null:(rl=!0,t)}function pl(e,t){const n=ul(t);if(null===n||!e||"object"!=typeof e)return e;const r=e;r.structuredContent&&"object"==typeof r.structuredContent&&(r.structuredContent.notice=n);const a=r.content?.[0];if(a&&"string"==typeof a.text)try{const e=JSON.parse(a.text);e.notice=n,a.text=JSON.stringify(e,null,2)}catch{a.text=`${a.text}\n\nNotice: ${n}`}return e}function ml(e,t){const n=cl(t);if(null===n||!e||"object"!=typeof e)return e;const r=dn(n.current,n.latest),a=e,i=e=>"string"==typeof e?`${e} ${r}`:r;a.structuredContent&&"object"==typeof a.structuredContent&&(a.structuredContent.update_available=n,a.structuredContent.message=i(a.structuredContent.message));const s=a.content?.[0];if(s&&"string"==typeof s.text)try{const e=JSON.parse(s.text);e.update_available=n,e.message=i(e.message),s.text=JSON.stringify(e,null,2)}catch{}return e}function _l(){nl=null,rl=!1,al=!1}H(sl,{UPDATE_CHECK_TIMEOUT_MS:()=>tl,attachUpdateAvailable:()=>ml,attachUpdateNotice:()=>pl,getUpdateAvailable:()=>cl,resetUpdateCheckForTests:()=>_l,startUpdateCheck:()=>ll,takeUpdateNotice:()=>ul,updateStatusSentence:()=>dl});var fl,hl,yl,gl,wl,vl,bl,jl,kl,Sl,Al,Il,xl,$l,El,ql,Ol=D({"src/middleware/update-check.ts"(){gr(),Xo="https://registry.npmjs.org/@atoms-tech/atoms-mcp/latest",el=864e5,tl=3e3,nl=null,rl=!1,al=!1}}),Rl=D({"src/core/timestamps.ts"(){fl=l.z.string().datetime({offset:!0})}});function Tl(e){return 32===e||9===e||13===e||10===e}function Ml(e){if("string"!=typeof e)return NaN;const t=hl.exec(function(e){let t=0,n=e.length;for(;t<n&&Tl(e.charCodeAt(t));)t++;for(;n>t&&Tl(e.charCodeAt(n-1));)n--;return e.slice(t,n)}(e));if(!t)return NaN;const[,n,r,a,i="0",s="0",o="0",l="",c="Z"]=t,d=Number(n),u=Number(r),p=Number(a),m=Date.UTC(d,u-1,p,Number(i),Number(s),Number(o));if(new Date(m).getUTCDate()!==p)return NaN;let _=0;if("Z"!==c.toUpperCase()){const e="-"===c[0]?-1:1,t=c.slice(1).replace(":","");_=e*(60*Number(t.slice(0,2))+(t.length>2?Number(t.slice(2,4)):0))}return 1e3*(m-6e4*_)+Number(`${l}000000`.slice(0,6))}function zl(e,t){const n=Ml(e),r=Ml(t),a=!Number.isNaN(n),i=!Number.isNaN(r);return a&&i?n===r?0:n>r?-1:1:a?-1:i?1:0}function Cl(e){return"passed"===e||"failed"===e||"blocked"===e}function Dl(e){const t=[];return e.forEach((e,n)=>{e&&void 0!==e.date&&null!==e.date&&t.push(n)}),t}function Hl(e){return`date was ignored on ${e.length} ${1===e.length?"entry":"entries"} (results[${e.join(", ")}]): every run is stamped with server time when it is recorded, never a caller-supplied date. A batch is stored newest-first, the last entry submitted being the newest run. Read each stored time from results[].run_at.`}function Ul(e){const t=e=>(Array.isArray(e)?e:[]).filter(e=>!!e&&"object"==typeof e&&!Array.isArray(e));return{steps:t(e?.steps).map(e=>({id:e.id,instruction:e.instruction,...void 0!==e.test_data&&null!==e.test_data?{test_data:e.test_data}:{},expected:e.expected})),params:t(e?.params).map(e=>({name:e.name,unit:e.unit,values:Array.isArray(e.values)?e.values:[]}))}}function Pl(e,t){return"string"==typeof e?t(e):Array.isArray(e)?e.map(e=>Pl(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Pl(n,t)])):e}function Nl(e,t){const n=Pl(e,t);return xl(n?.point)&&(n.point=Object.fromEntries(Object.entries(n.point).map(([e,n])=>[t(e),n]))),n}function Ll(e,t){if(!Array.isArray(e)||!Array.isArray(t))return e;const n=["source","plus","minus"];return e.map(e=>{if(!xl(e)||n.some(t=>t in e))return e;const r=t.find(t=>xl(t)&&t.name===e.name);return xl(r)&&JSON.stringify(r.values)===JSON.stringify(e.values)?{...e,...Object.fromEntries(Object.entries(r).filter(([e])=>n.includes(e)))}:e})}function Fl(e){const t=e.data?.status,n=e.data?.runs;if("test-case"===e.type&&Array.isArray(n)){const e=function(e){if(!e||0===e.length)return;const t=function(e,t){let n;for(const r of e??[])t&&!t(r)||(void 0===n||zl(r.date,n.date)<0)&&(n=r);return n}(e,e=>Cl(e.result))?.result;return Cl(t)?t:"not-run"}(n);if(void 0!==e)return e}return"test-case"===e.type?function(e){return"string"!=typeof e?void 0:"passed"===e||"failed"===e||"blocked"===e?"not-run":e}(t):"string"==typeof t?t:void 0}function Wl(e){const t=e.data?.runs;return"test-case"===e.type&&Array.isArray(t)&&t.length>0}function Vl(e){return`${e} has runs: ${$l}. Record a run: atoms_record_test_result(s).`}function Bl(e,t){return"test-case"===e.type&&!Wl(e)&&("passed"===t||"failed"===t||"blocked"===t)}function Jl(e){return`${e} has no runs: ${El}. Record a run: atoms_record_test_result(s).`}var Ql=D({"src/core/run-order.ts"(){hl=/^([1-9]\d{3})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?:[T ]([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d+))?)? ?(Z|[+-](?:0\d|1[0-5])(?::?[0-5]\d)?)?)?$/i,yl="date was ignored: every run is stamped with server time when it is recorded, never a caller-supplied date. Read the stored time from run_at.",gl="Ignored: the run is stamped with server time. A supplied date is reported in the response warning, never stored.",wl="Old results: ATOMS does not keep a date you send. Each run is stamped with the time it is recorded, so an old result counts as a run made now. Send dated entries oldest first: atoms_record_test_results refuses a batch whose dates run newest first. Do not record an old pass for a requirement that changed after the test really ran, because it would read as a pass made after the change.",vl="What the server checks before it stores a run: that you can edit the project, that the item is a test case, the result and step status values, a note and each step's actual result of at most 500 characters, an asset name of at most 200 characters, an evidence_url on a run or on a step result that is an http, https or mailto link of at most 2048 characters, and that a release_id is a formal Release of this project. step_results are checked against the test case's steps: they are refused on a test case with no steps, each step_id must be the id of one of its steps (atoms_get_item lists them), each step has at most one result in a run, and a step result carries only step_id, status, actual and evidence_url. A refused call records nothing, not even the entries before the refused one. A refused entry answers with a Validation error that names the check: fix the request instead of retrying it. evidence_url is stored as text: ATOMS does not open the link or check what it points to. steps_rev is ignored: the server pins the test case's current steps itself. When step_results is present, the run's verdict is derived from the step statuses and result is ignored.",bl="Releases: a run counts toward a Release only when it carries that Release's release_id. atoms_verification_status and the app's Release views read only runs bound to the Release, so a run recorded without release_id counts toward no Release, and the Release of a recorded verdict cannot be changed later. On a test case with parameters the run also needs its point, and on one that scopes assets, one of those assets. atoms_list_baselines lists the Releases: the baselines with a release_version (release_status released is the current one).",jl="Ignored: the server pins the test case's current steps revision itself",kl="Link to evidence kept elsewhere, at most 2048 characters. Stored as text; ATOMS does not open it",Sl="Optional link to the evidence for the whole run, such as a design review record, an inspection record or a report kept in your own tools: an http, https or mailto link of at most 2048 characters. Stored as text; ATOMS does not open it or keep the file",Al="A parameter written back with its stored name and values keeps its range settings; one whose values change is stored as a plain list of values.",Il="A test case also returns steps [{id, instruction, test_data?, expected}] and params [{name, unit, values}] (the resolved values); pass a step's id as step_id in step_results when recording.",xl=e=>!!e&&"object"==typeof e&&!Array.isArray(e),$l="its status comes from its runs and cannot be set",El="a result can only come from a run",ql="status (passed|failed|blocked|not-run): a result can only come from a run. A test case with runs takes its status from its newest run, and a test case with no runs has no result to set, so this tool refuses passed, failed and blocked for any test case; record a run with atoms_record_test_result or atoms_record_test_results instead. not-run is accepted on a test case with no runs"}});function Gl(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Kl(e){return e.replace(/[\\%_*]/g,e=>`\\${e}`)}function Yl(e){return Gl(`*${Kl(e)}*`)}function Zl(e){return Kl(e)}function Xl(e){return`*"${Kl(e)}"*`}async function ec(e){const t=await e;if(!(n=t.error)||"PGRST103"!==n.code&&!/requested range not satisfiable/i.test(n.message??""))return t;var n;const r=await e.range(0,0);return r.error?r:{data:[],error:null,count:r.count??null}}var tc,nc,rc,ac,ic,sc,oc,lc,cc,dc,uc,pc=D({"src/core/postgrest.ts"(){}});async function mc(e,t,n=1e3){if(!Number.isInteger(n)||n<1)throw new Error(`selectAllPaged: pageSize must be a positive integer, got ${n}`);if(0===t.length)throw new Error("selectAllPaged: at least one keyset column is required");const r=[];let a;for(let i=1;;i++){let s=e();void 0!==a&&(s=s.or(fc(t,a)));for(const e of t)s=s.order(e,{ascending:!0});const{data:o,error:l}=await s.limit(n);if(l)throw new Error(`${_c(s)} read, page ${i}: ${l.message}`);const c=o??[];if(0===c.length)return r;const d=c[c.length-1];if(void 0!==a&&t.every(e=>String(d[e])===String(a[e])))throw new Error(`${_c(s)} read, page ${i}: the page did not move past the last row read`);r.push(...c),a=d}}function _c(e){const t=e.url;return t instanceof URL?decodeURIComponent(t.pathname).replace(/^.*\/rest\/v1\//,""):"query"}function fc(e,t){const n=e.map(e=>{const n=t[e];if(null==n)throw new Error(`selectAllPaged: keyset column ${e} is missing from the selected row`);return Gl(String(n))});return e.map((t,r)=>{const a=e.slice(0,r).map((e,t)=>`${e}.eq.${n[t]}`);return a.push(`${t}.gt.${n[r]}`),1===a.length?a[0]:`and(${a.join(",")})`}).join(",")}function hc(e,t,n,r){return mc(()=>e.rpc(t,{p_project_id:n,p_snapshot_at:r}),sc[t])}function yc(e,t,n){return"baselineId"in n?mc(()=>e.rpc("baseline_variables_state",{p_baseline_id:n.baselineId}),ic):hc(e,"variables_at",t,n.at)}async function gc(e,t){const n=[];for(let r=0;r<e.length;r+=cc){const{data:a,error:i}=await t(e.slice(r,r+cc));if(i)throw new Error(i.message);n.push(...a??[])}return n}function wc(e){if("string"==typeof e.created_at&&"string"==typeof e.id)return function(e){const t=(new TextEncoder).encode(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(JSON.stringify([e.created_at,e.id]))}var vc,bc,jc=D({"src/core/paginate.ts"(){pc(),nc=["from_id","to_id","type"],rc=["variable_id","item_id","field"],ac=["name","id"],sc={project_state_at:tc=["id"],variables_at:ic=["name","id"]},oc=e=>({at:e}),lc=e=>({baselineId:e}),cc=200,dc=["created_at","id"],uc=class extends Error{constructor(){super("after is not a cursor from a previous atoms_list_items answer. Pass meta.next_cursor exactly as it was returned, or leave after out to start at the first page."),this.name="MalformedAfterError"}}}});function kc(e,t){return"requirement"!==t?`req_type applies only to requirements (type='requirement'), not '${t}'.`:bc.includes(e)?`req_type '${e}' names an analysis row, which is created by atoms_create_analysis, not atoms_create_item / atoms_update_item. Use atoms_create_analysis (variant iso26262 | iso14971 | design | process | software | use).`:vc.includes(e)?null:`Unknown req_type '${e}'. Allowed: ${vc.join(", ")}.`}var Sc,Ac,Ic,xc,$c=D({"src/core/req-type.ts"(){vc=["functional","interface","performance","safety"],bc=["safety-goal","failure-mode"]}});function Ec(e){return"requirement"===e.type&&"string"==typeof e.data?.req_type&&bc.includes(e.data.req_type)}function qc(e,t){const n=new Set(e.filter(e=>"test-case"===e.type).map(e=>e.id)),r=new Set;for(const e of t)"verifies"===e.type&&n.has(e.from_id)?r.add(e.to_id):"verified_by"===e.type&&n.has(e.to_id)&&r.add(e.from_id);return r}function Oc(e,t){const n=new Map;for(const t of e)n.set(t.id,t);const r=new Map,a=(e,t)=>{if(e===t)return;const a=n.get(e),i=n.get(t);if(!a||!i||!Ec(a))return;if("requirement"!==i.type||Ec(i))return;let s=r.get(e);s||r.set(e,s=new Set),s.add(t)};for(const e of t)"mitigated_by"===e.type?a(e.from_id,e.to_id):"mitigates"===e.type&&a(e.to_id,e.from_id);const i=new Map;for(const[e,t]of r)i.set(e,[...t].sort((e,t)=>e.localeCompare(t)));return i}async function Rc(e,t){return mc(()=>e.from("items").select(Sc).eq("project_id",t).eq("type","requirement").is("deleted_at",null).not("data->relationships->mitigates","is",null),tc)}function Tc(e,t){const n=new Map,r=[];for(const e of t){n.set(e.id,{id:e.id,type:e.type,data:{req_type:e.req_type}});for(const t of zc(e.mitigates))r.push({from_id:e.id,to_id:t,type:"mitigates"})}for(const t of e){n.set(t.id,{id:t.id,type:t.type,data:{req_type:t.data?.req_type}});for(const e of zc(t.data?.relationships?.mitigated_by))r.push({from_id:t.id,to_id:e,type:"mitigated_by"})}const a=Oc([...n.values()],r);for(const t of e){const e=a.get(t.id);e&&a.set(t.id,[...new Set([...zc(t.data?.relationships?.mitigated_by).filter(t=>e.includes(t)),...e])])}return a}async function Mc(e,t,n,r){return Tc([n],[...r.map(e=>({id:e.id,type:e.type,req_type:e.data?.req_type,mitigates:e.data?.relationships?.mitigates})),...await Rc(e,t)]).get(n.id)??[]}function zc(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function Cc(e,t){const n=e.filter(e=>(t?.get(e.id)?.length??0)>0).map(e=>e.id);return{count:n.length,ids:n}}function Dc(e,t,n){return e.filter(e=>!t.has(e)&&(n.get(e)?.length??0)>0).length}var Hc,Uc,Pc=D({"src/core/coverage-mitigation.ts"(){jc(),Oi(),$c(),Sc="id, type, updated_at, req_type:data->>req_type, mitigates:data->relationships->mitigates",Ac="role, control_type and override apply to action add only; omit them to remove a link.",Ic="covered and coverage_percent count a requirement's own linked test cases (its verified_by, or a test case's verifies; a link to another requirement or any item that is not a live test case does not count), whatever their result. A hazard, failure mode or risk row that has no test case of its own but at least one live mitigating requirement is listed in uncovered, as always, and the app reads it as covered through its mitigation: covered_via_mitigation is { count, ids } for those rows, and each such row in uncovered_items carries mitigated_by, the ids of its live mitigating requirements. It does not change covered or coverage_percent.",xc="coverage.covered and coverage.percent count a requirement's own linked test cases. coverage.via_mitigation counts the requirements with no test case of their own that are hazard, failure mode or risk rows with at least one live mitigating requirement, which the app reads as covered through its mitigation; it is not part of covered or percent."}});function Nc(e,t){return t>0?Math.round(e/t*1e3)/10:Hc}var Lc,Fc,Wc,Vc,Bc,Jc,Qc,Gc,Kc,Yc=D({"src/core/project-summary.ts"(){Ql(),Hc=100,Uc="test_status counts each test case by the verdict of its newest run, whatever Release that run is bound to, as the Matrix does. It is not the status of any one Release: for a Release, use atoms_verification_status."}});function Zc(e){return Math.min(Math.max(e??5,1),10)}var Xc,ed,td=D({"src/core/trace-graph.ts"(){Lc=200,Fc=new Set(["parent","verifies","mitigated_by"]),Wc=new Set(["child","verified_by","mitigates"]),Vc={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related"},Bc=["parent","verifies","mitigated_by","traces_to","allocated_from","decomposed_from"],Jc=["child","verified_by","mitigates","allocated_to","decomposes_to","traced_by"],Qc={...Vc,traces_to:"traced_by",traced_by:"traces_to",allocated_to:"allocated_from",allocated_from:"allocated_to",decomposes_to:"decomposed_from",decomposed_from:"decomposes_to"},Gc="downstream follows child, verified_by and mitigates links: an item's children, its test cases, and the hazards, failure modes or risks a risk control mitigates. upstream follows parent, verifies and mitigated_by links: an item's parents, the requirements a test case verifies, and the risk control of a hazard. The link table's trace, allocation and decomposition links are followed too: traces_to, allocated_from and decomposed_from upstream, traced_by, allocated_to and decomposes_to downstream. related links are followed both ways. Links are read from the link table and from each item's own relationship lists. affects and affected_by links are not followed yet.",Kc="upstream follows parent, verifies and mitigated_by links; downstream follows child, verified_by and mitigates links. A hazard's risk control is upstream of the hazard and the hazards a control mitigates are downstream of it, so downstream from a hazard does not reach its control: use direction both for the hazard, its control and the control's tests in one call. related links are followed both ways. affects and affected_by links are not followed yet, so a relationship_types filter of only those returns just the starting item."}}),nd=D({"src/core/tool-descriptions.ts"(){Ql(),Pc(),Yc(),td(),P(),Xc={atoms_status:'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 exist and are valid,\nprobes the data tier with a cheap query so an expired JWT is detected here instead of surfacing\nas a confusing \'JWT expired\' from atoms_list_projects, and tells the user exactly what to do if not.\n\nArgs: None\n\nReturns:\n { status: "authenticated"|"not_authenticated"|"expired"|"suspended"|"pending"|"unavailable"|"error", email, message, next_steps?, org_suspended? }\n\nExamples:\n - "Is ATOMS MCP working?" → atoms_status()\n - "Why are atoms tools failing?" → atoms_status()',atoms_list_projects:'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, org_name, 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)',atoms_list_items:'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 - after (string, optional): meta.next_cursor of the previous page; use it instead of offset to page through a project that is being edited\n - baseline_id (string, UUID, optional): list items as they were at that baseline\'s moment\n - as_of (string ISO 8601, optional): list items as they were at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n { status: "success", data: [{ id, title, type, status, domains, level }], meta: { total_count, limit, offset, has_more, next_cursor? } }\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',atoms_get_item:`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 - baseline_id (string, UUID, optional): return the item as it was at that baseline\n - as_of (string ISO 8601, optional): return the item as it was at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\n${Il}\n\nOn projects that save one field at a time, a live read also returns base_token, seq (the project's change number\nwhen it was read), editing_now and presence. Send base_token with a later atoms_update_item. ${k}\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")`,atoms_search:'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 - baseline_id (string, UUID, optional): search the project as it was at that baseline\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")',atoms_semantic_search:'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")',atoms_get_coverage:`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, covered_via_mitigation: { count, ids }, uncovered_items: [...] }\n\n${Ic}\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="...")`,atoms_get_history:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_<client>) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",atoms_export_mermaid:"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: string, node_count, edge_count }",atoms_create_item:`Create a new requirement, test case, or note in a project.\n\nFor a hazard analysis, HARA, DFMEA or FMEA, use atoms_create_analysis instead (it creates the analysis parent and its rows). This tool does not create analysis items; do not model a hazard analysis as notes with custom fields.\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 - req_type (string, optional): requirement classification (functional|interface|performance|safety)\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 (a tag flagged as a function is not a domain and is rejected)\n - level (string, optional): System|Subsystem|Component\n - parent_ids (string[], optional): Parent item IDs to link\n - fields (object, optional): Project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field first and values must match each field type.\n - echo (boolean, optional, default true): false gives a lean {id, type} answer and skips the full-item echo, saving about 580 tokens per call on large passes\n\nReturns:\n Created item with generated ID (e.g., "REQ-058")\n\nSide effects:\n - Logs to change_history with actor='mcp_<client>'\n - Creates relationships if parent_ids provided\n\nOn projects that save one field at a time: the answer carries the new item's base_token. ${S} ${E}`,atoms_update_item:`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\nSingle-item form:\n - project_id, item_id, title?, body?, summary?, domains? (a tag flagged as a function is not a domain and is rejected), level?, status?, req_type?, fields?, steps?, params?, expected_updated_at?\n - ${ql}\n - fields? (object): project-field values, e.g. {"Verification Method": "Design Review"}. Keys must be defined via atoms_create_field; merged per key, "" clears a key\n - steps? (array): test-case script [{id, instruction, test_data?, expected}], max 50 (DB-enforced)\n - params? (array): matrix parameters [{name, unit, values[]}], matrix points capped at 64 (DB-enforced)\n - expected_updated_at may be metadata.updated_at from atoms_get_item to reject stale writes\n - echo? (bool, default true): false gives a lean {id, updated_fields} response, saves ~580 tokens\n - reason? (string): change rationale persisted in audit history\n\nArray form (batch updates, same tool, much faster):\n - project_id, updates: [{item_id, title?, body?, summary?, domains?, level?, status?, fields?, steps?, params?, expected_updated_at?}]\n - echo? false recommended for large passes\n - reason?: applied to all history rows in the batch\n - idempotency_key?: safe to retry with same key within 24h\n - continue_on_error? (bool, default false): allow partial success\n\nbase_token: ${k}\nidempotency_key: ${S}\n${E}`,atoms_delete_item:'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 confirmation is required (an org policy, or ATOMS_MCP_REQUIRE_CONFIRMATION on the npm 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.',atoms_bulk_import:`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 (500 on a project that saves one field at a time), 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 (a tag flagged as a function is not a domain and is rejected)\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 (500 on a project that saves one field at a time)\n - If any item fails, others still succeed — errors reported separately\n\nSide effects:\n - Logs to change_history with actor='mcp_<client>' for each created item\n - Creates parent relationships for items with parent_id\n\nOn projects that save one field at a time: the items are created in parts of at most 50, each part all or nothing. ${S} ${E}`,atoms_record_test_result:`Record a pass/fail/blocked result for a test case.\n\nAppends to canonical items.data.runs and projects test_results from that\nhistory. Use atoms_get_item to see all results.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., "TC-001")\n - result (string): passed|failed|blocked|not-run\n - note (string, optional): Reason or comment for this result\n - asset (string, optional): Asset identifier this run was executed against\n (VIN, module ID, lot number, serial number, etc). Max 200 chars.\n Auto-trimmed; empty/whitespace is treated as omitted. If the asset\n name does not yet exist in the project, it is auto-registered.\n - point, release_id, build, environment, tooling, steps_rev (optional):\n run metadata.\n - evidence_url (string, optional): link to the evidence for the whole run,\n such as a design review record or a report kept in your own tools.\n - step_results (array, optional): per-step outcomes for a stepped run.\n When provided, the verdict is derived server-side from the steps.\n - date (string, optional): IGNORED, reported in the response warning.\n\nReturns:\n Recorded result with the stored run_at (server time at microsecond\n precision, never the caller's clock). When asset is provided, also returns\n asset_id and asset_created. A warning when a date was sent.\n\n${vl}\n\n${bl}\n\n${wl}\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts into assets table if asset name is new in this project\n - Logs to change_history with actor='mcp_<client>'`,atoms_record_test_results:`Record many runs on one test case in a single atomic call.\n\nOptimized for multi-asset campaigns. Each entry can have its own asset and\nresult. Asset lookup-or-create happens per entry; new asset names are\nauto-registered. Runs are appended to canonical items.data.runs, then\ntest_results is projected from that history. The whole call is one DB\ntransaction; any entry failure rolls back the rest.\n\nUse the singular atoms_record_test_result for one-off runs.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., "TC-001")\n - results (array, 1-100 entries): Each entry has:\n - asset (string, optional): Asset identifier (VIN, module ID, lot)\n - result (string, required): passed|failed|blocked|not-run\n - note (string, optional): Run note\n - date (string, optional): IGNORED. Every run is stamped with server time\n when it is recorded; a supplied date is reported in the\n response warning, never stored. The entries of one call are stamped\n one microsecond apart in the order sent and stored newest-first, so\n the LAST entry is the newest run.\n - point, release_id, build, environment, tooling, steps_rev (optional):\n run metadata.\n - evidence_url (string, optional): link to the evidence for the whole\n run, such as a design review record or a report kept in your own tools.\n - step_results (array, optional): per-step outcomes; when present the\n verdict is derived server-side from the steps.\n\nReturns:\n Per-entry outcomes with asset_id, asset_created, run_at (the stored server\n time), ok flags, and a warning (with ignored_date_entries) when any entry\n supplied a date.\n\n${vl}\n\n${bl}\n\n${wl}\n\nSide effects:\n - Appends to items.data.runs through save_item_with_revision\n - Projects public.test_results from items.data.runs\n - Inserts new rows into assets for any asset name not already registered\n - Logs a single change_history entry summarizing the batch`,atoms_trace:`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/mitigated_by links (dependencies)\n - downstream: follow child/verified_by/mitigates links (dependents)\n - both: trace in both directions\n - depth (number, optional): Max traversal depth (default 5, max 10)\n - relationship_types (string[], optional): Filter to specific types (parent, child, related, verifies, verified_by, mitigated_by, mitigates)\n\n${Kc}\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")`,atoms_list_assets:"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 }",atoms_list_variables:"List all parameterized variables defined in a project.\n\nVariables are shared values (e.g., backup_camera_latency = 2s) that can be\nreferenced in requirement bodies as {variable_name}.\n\nArgs:\n - project_id (string, UUID): Project to list variables for\n - baseline_id (string, UUID, optional): list variables as they were at that baseline\n - as_of (string ISO 8601, optional): list variables as they were at that moment\n - limit (number, optional): max results (default 50, max 200)\n - offset (number, optional): pagination offset (default 0)\n\nReturns:\n { variables: [{ id, name, value, unit, description }], total }, meta: { total_count, limit, offset, has_more }",atoms_get_variable:'Get a specific variable by name, including which items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name (e.g., "backup_camera_latency")\n - baseline_id (string, UUID, optional): get the variable as it was at that baseline\n - as_of (string ISO 8601, optional): get the variable as it was at that moment\n\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',atoms_update_variable:"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 - echo (boolean, optional, default true): false gives a lean { name, updated: true } answer\n\nReturns:\n { variable }",atoms_create_variable:'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 }',atoms_delete_variable:"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? }",atoms_list_levels:"List the project's level taxonomy in order, with each level's L# (positional index) and item count.\n\nArgs:\n - project_id (string, UUID): Project to list levels for\n\nReturns:\n { levels: [{ name, prefix, item_count }], total }",atoms_create_level:'Register a new level in the project taxonomy so items can be tagged with it and it shows in the Strata view. Appended to the ordered level list; its L# is the next index. Names are user-defined labels (lowercased automatically); matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID): Project to add the level to\n - name (string): Level name, e.g. "feature", "system", "subsystem"\n\nReturns:\n { level: { name, prefix }, message }',atoms_delete_level:"Delete an UNUSED level from the project taxonomy. Refuses if any item still uses the level (re-tag those items with atoms_update_item first). A level is positional, so deleting one shifts every later level's L# down by one. Matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID)\n - name (string): the level to delete\n - confirmation_token (string, optional): from the first call, when confirmation is required\n\nReturns:\n { level: { name }, remaining_levels, message } — or a confirmation_required payload",atoms_reorder_levels:"Reorder the project's levels. Provide every existing level name exactly once, in the order you want them (any casing). L# is positional, so this changes every level's L# wherever it renders (Strata, sidebar, exports). Touches no item.\n\nArgs:\n - project_id (string, UUID)\n - names (string[]): every existing level name, in the new order\n\nReturns:\n { levels: [{ name, prefix }], message }",atoms_create_field:'Define a project custom field so items can carry a value for it (shown as a Matrix column, e.g. "Verification Method").\n\nThe name keeps its casing; uniqueness is case-insensitive. Type is one of text, long, bool, date, person, select, number, link. Select fields require options. Field definitions never carry visibility rules, permissions, or workflow logic. A definition applies to every item type unless appliesTo restricts it (requirement|test-case|note|table).\n\nArgs:\n - project_id (string, UUID): Project to define the field in\n - name (string): Field name, 1-60 characters (e.g. "Verification Method", "Essential Output?")\n - type (string, optional): Defaults to text\n - options (string[], optional): Required when type=select\n - scope (string, optional): project (default) or organization (org admin only)\n - appliesTo (string[], optional): item types the field shows on (requirement|test-case|note|table); omit for all types\n\nReturns:\n { field: { name, type, options }, message }',atoms_project_summary:`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\n${xc}\n\n${Uc}\n\nExamples:\n - "Give me a compliance snapshot" → atoms_project_summary(project_id)\n - "How's our test coverage?" → atoms_project_summary(project_id)`,atoms_browse:'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")',atoms_impact_analysis:`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, mitigates)\n - upstream: what affects this item (parents, verifies, mitigated_by)\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\n${Gc}\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`,atoms_list_baselines:"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.\n\nArgs:\n - project_id (string, UUID)\n - limit (number, optional, default 50, max 100)\n - offset (number, optional, default 0)",atoms_create_baseline:"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).\n\nArgs:\n - project_id (string, UUID)\n - name (string, 1-200 chars, unique per project)\n - description (string, optional, max 2000)",atoms_lock_baseline:"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.\n\nArgs:\n - baseline_id (string, UUID)",atoms_diff_baselines:"Compute the diff between two baselines: which items were added, removed, or modified.\n\nReturns a summary plus a paginated items array. Each modified item lists the\nnames of the fields that changed in fields_changed. An item counts as modified exactly when the app's snapshot Compare lists it as Modified, so a difference only in metadata timestamps, the change-control review state, an empty versus an absent value or key order is not a change. With detail=true each modified item also carries a diff object keyed by every name in fields_changed, each with the from and to values. Under data, a list such as steps or runs holds only the entries that differ, keyed by the entry id (by position when entries have no id), with order giving each side's id sequence when it changed. A detail=true page is bounded to 20000 characters of items: when items are left out, page_info carries truncated: true and next_offset, so call again with that offset for the rest. Slower for large projects.\n\nArgs:\n - baseline_a_id (string, UUID)\n - baseline_b_id (string, UUID)\n - detail (boolean, optional, default false)\n - limit (number, optional, default 50, max 200)\n - offset (number, optional, default 0)",atoms_restore_baseline:"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,\nitems_to_trash and variables_to_archive, with a summary in plain words.\nCall with confirm=true to execute: each item present at the baseline gets a new\nrevision matching its historical state, event_source='restore'. The restore is\nexact: items added AFTER the baseline are moved to Trash (restorable from Trash)\nand variables added after it are archived; the answer counts items_trashed and\nvariables_archived. Every revision is kept, so a later baseline still holds them.\n\nArgs:\n - baseline_id (string, UUID)\n - confirm (boolean, optional, default false)\n\nWith confirm=false: returns { preview: true, items_to_restore: N, items_to_trash: T, variables_to_archive: V, summary }\nWith confirm=true: executes; returns { ok: true, items_restored: N, items_trashed: T, variables_archived: V, summary }",atoms_list_scenario_catalogs:'List a project\'s operational scenario catalogs: the situational analysis written\nand accepted before a HARA (ISO 26262) starts. Each catalog is a list of entries (operational\nscenarios), each tagged with the functions it applies to.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): The project to list catalogs from\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, name, entries: [{id, text, function_tags}], acceptance }],\n meta: { total_count, limit, offset, has_more } }',atoms_mutate_scenario_catalog:"Create/rename/delete a catalog, or add/edit/remove/tag one of its entries, or accept\na catalog. Every op goes through a row-locked database function and returns the STORED list, so a\nwrite can never report success for an entry the row did not retain.\n\nRequires editor or admin role.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID)\n - op: create_catalog | rename_catalog | delete_catalog | add_entry | edit_entry | remove_entry |\n tag_entry | accept_catalog\n - catalog_id (string, optional for create_catalog, which generates one when omitted; required for every other op)\n - name (string): the catalog name (create_catalog, rename_catalog)\n - entry_id (string, required for add_entry/edit_entry/remove_entry/tag_entry; caller-generated)\n - text (string): the entry's operational scenario text (add_entry, optional on edit_entry)\n - function_tags (string[]): the functions this entry applies to; [] = every function\n (add_entry, edit_entry, tag_entry)\n - by (string): the accepter's name (accept_catalog)\n - on (string): the acceptance date (accept_catalog)\n\nReturns:\n { status: \"success\", data: { scenario_catalogs: [...] } }\n\nSide effects:\n - add_entry/edit_entry/remove_entry return an ACCEPTED catalog to draft, keeping the prior\n acceptance in history. tag_entry and rename_catalog do not."}}});var rd,ad=D({"src/apps/register.ts"(){ed={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function id(e,t){const n=new Set(e.map(e=>e.id)),r=new Set,a=[],i=(e,t,i)=>{if(e===t)return;if(!n.has(e)||!n.has(t))return;const s=`${e}|${t}|${i}`;r.has(s)||(r.add(s),a.push({from_id:e,to_id:t,type:i}))};for(const e of t)i(e.from_id,e.to_id,e.type);for(const t of e){const e=t.data?.relationships??{};for(const[n,r]of rd){const a=e[n];if(Array.isArray(a))for(const e of a)"string"==typeof e&&i(t.id,e,r)}}return a}var sd=D({"src/core/relationship-sync.ts"(){rd=[["parents","parent"],["children","child"],["related","related"],["verifies","verifies"],["verified_by","verified_by"],["mitigated_by","mitigated_by"],["mitigates","mitigates"],["affects","affects"],["affected_by","affected_by"],["traces_to","traces_to"],["traced_by","traced_by"],["allocated_to","allocated_to"],["allocated_from","allocated_from"],["decomposes_to","decomposes_to"],["decomposed_from","decomposed_from"]]}});function od(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString().replace(/Z$/,"999Z")}var ld=D({"src/core/as-of.ts"(){}});async function cd(e,t,n){let r=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0}).order("id",{ascending:!0});const a=void 0!==n.after?function(e){try{const t=JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return(new TextDecoder).decode(Uint8Array.from(n,e=>e.charCodeAt(0)))}(e));if(Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&t[0].length>0&&"string"==typeof t[1]&&t[1].length>0)return{created_at:t[0],id:t[1]}}catch{}return null}(n.after):null;if(void 0!==n.after&&null===a)throw new uc;a&&(r=r.or(function(e){return fc(dc,e)}(a))),n.type&&(r=r.eq("type",n.type)),n.domain&&(r=r.filter("data->tags->>domains","ilike",Xl(n.domain))),n.level&&(r=r.filter("data->tags->>level","ilike",Zl(n.level))),r=a?r.range(0,n.limit):r.range(n.offset,n.offset+n.limit);const{data:i,error:s,count:o}=await ec(r);if(s)throw new Error(s.message);const l=i??[],c=l.slice(0,n.limit),d=l.length>n.limit;return{items:c,totalCount:o??0,hasMore:d,nextCursor:d?wc(c[c.length-1]):void 0}}async function dd(e,t,n){const{data:r,error:a}=await e.from("items").select("*").eq("id",n).eq("project_id",t).is("deleted_at",null).maybeSingle();if(a)throw new Error(a.message);return r}async function ud(e,t){if(t.baseline_id&&t.as_of)throw new lt("baseline_id and as_of are mutually exclusive");if(t.as_of)return oc(od(t.as_of));if(t.baseline_id){const{data:n,error:r}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",t.baseline_id).maybeSingle();if(r)throw new Error(`resolveReadMoment: ${r.message}`);if(!n||null!==n.deleted_at)throw new lt("Baseline not found");if(n.project_id!==t.project_id)throw new lt("Baseline does not belong to this project");return lc(t.baseline_id)}return null}async function pd(e,t){const{data:n,error:r}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, deleted_at, release_version, release_status").eq("id",t).maybeSingle();if(r)throw new Error(`getBaselineById: ${r.message}`);return n&&null===n.deleted_at?n:null}function md(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 _d(e,t,n){return function(e,t,n){return"baselineId"in n?mc(()=>e.rpc("baseline_state",{p_baseline_id:n.baselineId}),tc):hc(e,"project_state_at",t,n.at)}(e,t,n).catch(e=>{throw new Error(`projectStateAt: ${e.message}`)})}async function fd(e,t,n,r){const a=n.trim();if(!a)return{items:[],totalCount:0};const i=r.asset&&r.asset.trim()?await async function(e,t,n){const r=await mc(()=>e.from("test_results").select("id, item_id").eq("project_id",t).eq("asset",n),["id"]);return[...new Set(r.map(e=>e.item_id))]}(e,t,r.asset.trim()):null;if(i&&0===i.length)return{items:[],totalCount:0};const s=()=>{let n=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${Yl(a)},data->>body.ilike.${Yl(a)},data->>summary.ilike.${Yl(a)}`);return n=void 0===r.offset?n.limit(r.limit):n.order("id",{ascending:!0}).range(r.offset,r.offset+r.limit-1),r.type&&(n=n.eq("type",r.type)),r.domain&&(n=n.filter("data->tags->>domains","ilike",Xl(r.domain))),r.level&&(n=n.filter("data->tags->>level","ilike",Zl(r.level))),n};if(i)return async function(e,t,n){const r=[];let a=0;for(let t=0;t<e.length;t+=cc){const{data:i,error:s,count:o}=await n(e.slice(t,t+cc));if(s)throw new Error(s.message);a+=o??0,r.push(...i??[])}return{items:r.slice(0,t),totalCount:a}}(i,r.limit,e=>s().in("id",e));const{data:o,error:l,count:c}=await ec(s());if(l)throw new Error(l.message);return{items:o??[],totalCount:c??0}}var hd=D({"src/db/queries.ts"(){pc(),Oi(),Pc(),jc(),sd(),ld(),Xt()}}),yd={};async function gd(){try{const e=await mo(async()=>{const e=await co();return await async function(e){const{data:t,error:n}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(n)throw new Error(n.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=Zo(),n=Y,r=oe().project_scope,a=r?new Set(r):null;return Vs(ys(e.filter(e=>!n||e.org_id===n).filter(e=>!t||e.id===t).filter(e=>!a||a.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 Bs(Ds(e))}}H(yd,{listProjectsHandler:()=>gd});var wd=D({"src/tools/list-projects.ts"(){ko(),hd(),il(),ce(),Ks()}}),vd={};async function bd(e){try{const t=await co();let n,r,a=null;try{a=await ud(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Bs(Ds(e))}let i=null;if(a){const i=(await _d(t,e.project_id,a)).filter(t=>{if(e.type&&t.type!==e.type)return!1;const n=t.data??{};if(e.domain){const t=n?.tags?.domains??[];if(!Array.isArray(t)||!t.some(t=>ti(t)===ti(e.domain)))return!1}return!e.level||Pa(n?.tags?.level)===Pa(e.level)});r=i.length,n=i.slice(e.offset,e.offset+e.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}else i=await cd(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset,after:e.after}),n=i.items,r=i.totalCount;const s=n.map(e=>({id:e.id,title:e.title,type:e.type,status:Fl(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),o=gs(r,e.limit,void 0!==e.after?0:e.offset);return i&&"boolean"==typeof i.hasMore&&(o.has_more=i.hasMore,i.nextCursor&&(o.next_cursor=i.nextCursor)),Vs(ys(s,o))}catch(e){return e instanceof uc?Bs(Ss(e.message)):e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(vd,{listItemsHandler:()=>bd});var jd=D({"src/tools/list-items.ts"(){ko(),hd(),Ks(),jc(),Oi(),Ql()}});function kd(e,t){return lr(e,t)}function Sd(e){if(e instanceof Error)return e;const t=new Error(function(e){return e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??"")}(e)),n=e&&"object"==typeof e&&"code"in e?e.code:void 0;return"string"==typeof n&&(t.code=n),t}function Ad(e,t){if(t&&dr(e,t))throw Sd(t)}async function Id(e,t,n,r={}){const a=new Set(n.map(e=>e.item_id).filter(e=>"string"==typeof e)),i=r.mode??(a.size>1?"bulk":"single"),s="bulk"===i?r.bulkId??crypto.randomUUID():void 0,o=await async function(e){let t=null;try{t=await ho(e)}catch{t=null}return function(e){const t=function(e){const t=st(e);return"mcp_cursor"===t?"Cursor":"mcp_copilot"===t?"Copilot":"Claude"}(e.clientName);return{kind:"agent",user_id:e.userId,session_id:e.sessionId,label:pr(t,e.name,e.email),client:t}}({userId:_o(),sessionId:Yh(),name:t,email:fo(),clientName:Xh()})}(e),l=async n=>{const a=function(e,t){return function(e,t,n,r){const a={surface:"mcp",delivery:"npm",package_version:Rh,mode:n};return"bulk"===n&&(a.bulk={kind:"agent_bulk",bulk_id:r??crypto.randomUUID()}),a}(0,0,e,t)}(i,s),l=r.atomic&&a.bulk?{...a,bulk:{...a.bulk,atomic:!0}}:a,{data:c,error:d}=await e.rpc("apply_item_ops",{p_project_id:t,p_ops:n,p_author:o,p_client:l});if(d)throw Sd(d);return c??{answers:[]}};let c;if(!1===r.chunk)try{const e=await l([...n]);c={answers:e.answers??[],results:[e],notSent:[]}}catch(e){c={answers:[],results:[],notSent:[...n],error:e}}else c=await async function(e){const t=e.isTooManyItems??sr,n=function(e,t=Jt,n=Qt){return ar(rr(e),t,n)}(e.ops);let r=n.length;const a=[],i=new Map;let s,o=0,l=0,c=[],d=0;for(;d<n.length;){const u=n[d];try{const t=await e.send(u,l);l+=1,a.push(t),o+=1;for(const e of t.answers??[])e&&e.op_id&&i.set(e.op_id,e);d+=1}catch(e){l+=1;const a=rr(u);if(t(e)&&a.length>1){const e=Math.ceil(a.length/2),t=[ar(a.slice(0,e),1/0,1/0)[0],ar(a.slice(e),1/0,1/0)[0]];n.splice(d,1,...t),r+=1;continue}s=e,c=n.slice(d).flat();break}}const u=[];for(const t of e.ops){const e=i.get(t.op_id);e&&u.push(e)}return{answers:u,results:a,...r>1?{chunks:{total:r,committed:o}}:{},notSent:c,...void 0!==s?{error:s}:{}}}({ops:n,send:e=>l(e)});return void 0!==c.error&&0===c.results.length&&Ad("ops",c.error),c}function xd(e){const t=[];for(const n of e)for(const e of n.skipped_items??[]){if("string"==typeof e||!e){t.push(e);continue}const n=e.last_change;t.push(e.change||!n?e:{...e,change:{seq:n.seq??null,author:n.author??null,at:n.committed_at??n.at??null}})}return t}async function $d(e){const t=e.relooked?[...e.answers]:await _r(e.client,e.projectId,e.answers),n=[...new Set(t.filter(e=>"skipped"===e.status&&"chunk_not_sent"!==e.reason&&"string"==typeof e.item_id).map(e=>e.item_id))];let r;return n.length>0&&(r=await An(e.client,e.projectId,n)),zn({answers:t,ops:e.ops,skippedItems:xd(e.results??[]),openRevisions:r,labels:e.labels})}function Ed(e){const t=e.suggestion;return"number"==typeof t?.sg_number?t.sg_number:null}function qd(e,t){const n=e.captured.map(e=>({item_id:e.item_id??null,path:e.path??null,status:"captured",seq:e.seq??null,...null!==Ed(e)?{change:{sg_number:Ed(e)}}:{}})),r={...e,applied:[...e.applied,...n]},{isError:a,result:i}=Vn(r,t);return a?Bs(i):Vs(i)}async function Od(e,t,n,r,a,i={}){const s=[...new Set(n.map(e=>e.item_id).filter(e=>"string"==typeof e))];if(0===s.length)return;const o=s.map(e=>({item_id:e,project_id:t,changed_by:_o(),event_type:a,old_data:null,new_data:fr(n,r,e),actor:Zh(),session_id:Yh(),...i.batch_id?{batch_id:i.batch_id}:{},...i.reason?{reason:i.reason}:{}}));await e.from("change_history").insert(1===o.length?o[0]:o).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})}function Rd(e){return e&&0!==e.length?"tags"===e[0]?"level"===e[1]?"level":"domains"===e[1]?"domains":"tags":e[0]:null}function Td(e){return"set"===e.kind?e.path:[...e.path,e.kind,String(e.row_id??un(e.value??null))]}function Md(e){return null==e?[]:"string"==typeof e?[e]:[...e]}var zd,Cd=D({"src/tools/_agent-ops.ts"(){ko(),ey(),gr(),Ks()}}),Dd={};function Hd(e,t){if(!t)return e;const n={...e};for(const e of zd){const r=t[e];null!=r&&("evidence_url"===e&&"string"==typeof r&&""===r.trim()||(n[e]=r))}return n}async function Ud(e){try{const r=await co();let a=null;try{a=await ud(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Bs(Ds(e))}let i=null;if(!a&&!0===await kd(r,e.project_id)){i={head:await xn(r,e.project_id),revision:(await An(r,e.project_id,[e.item_id])).get(e.item_id)}}const s=a?await async function(e,t,n,r){const{data:a,error:i}=await function(e,t,n,r){return"baselineId"in r?e.rpc("baseline_item_state",{p_baseline_id:r.baselineId,p_item_id:n}):e.rpc("item_state_at",{p_item_id:n,p_project_id:t,p_snapshot_at:r.at})}(e,t,n,r);if(i)throw new Error(`itemStateAt: ${i.message}`);return(a??[])[0]??null}(r,e.project_id,e.item_id,a).then(e=>e?md(e):null):await dd(r,e.project_id,e.item_id);if(!s)return Bs(vs("Item",e.item_id));const o={parents:[],children:[],related:[],verified_by:[],verifies:[],mitigated_by:[],mitigates:[],affects:[],affected_by:[]};if(a){const e=s.data?.relationships??{};for(const t of Object.keys(o)){const n=e[t];Array.isArray(n)&&(o[t]=n.slice())}}else{const t=await async function(e,t,n){const{data:r,error:a}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${n},to_id.eq.${n}`);if(a)throw new Error(a.message);return r??[]}(r,e.project_id,e.item_id),n={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",mitigated_by:"mitigated_by",mitigates:"mitigates",affects:"affects",affected_by:"affected_by"},a={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related",affects:"affected_by",affected_by:"affects"},i=(e,t)=>{if(!(e in o))return;const n=o[e];n.includes(t)||n.push(t)},l=new Set([e.item_id]);for(const e of t)l.add(e.from_id),l.add(e.to_id);const c=s.data?.relationships??{};for(const e of Object.keys(o)){const t=c[e];if(Array.isArray(t))for(const e of t)"string"==typeof e&&l.add(e)}let d=new Set([e.item_id]);const u=Array.from(l);if(u.length>0){const{data:t,error:n}=await r.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",u);if(n)throw new Error(n.message);d=new Set((t??[]).map(e=>e.id)),d.add(e.item_id)}const p=e=>d.has(e);for(const r of t)if(r.from_id===e.item_id){if(!p(r.to_id))continue;i(n[r.type]??r.type,r.to_id)}else{if(!p(r.from_id))continue;i(a[r.type]??r.type,r.from_id)}for(const t of Object.keys(o)){const n=c[t];if(Array.isArray(n))for(const r of n)"string"==typeof r&&r!==e.item_id&&p(r)&&i(t,r)}}let l=[];if("test-case"===s.type)if(a)l=(s.data?.runs??[]).map(e=>({base:{result:e.result??"not-run",run_by:e.by??e.run_by??null,run_at:e.date??e.run_at??"",note:e.note??null,..."string"==typeof e.asset?{asset:e.asset}:{}},canonical:e})).filter(e=>"string"==typeof e.base.run_at&&e.base.run_at.length>0).sort((e,t)=>zl(String(e.base.run_at),String(t.base.run_at))).slice(0,20).map(e=>Hd(e.base,e.canonical));else{const{data:t,error:n}=await r.from("test_results").select("result, run_by, run_at, note, asset").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);if(!n&&t){const e=new Map;for(const t of s.data?.runs??[])"string"==typeof t?.date&&e.set(t.date,t);l=t.map(t=>Hd(t,e.get(String(t.run_at))))}}const c=i&&function(e){return"requirement"===e.type&&null!==zo(e.data)}(s)?await async function(e,t,n){try{const{data:r,error:a}=await e.from("project_changes").select("seq, path, committed_at").eq("project_id",t).eq("item_id",n).filter("path","eq",'["asil_pending_lower"]').order("seq",{ascending:!1}).limit(1);if(a||!Array.isArray(r))return null;const i=r.find(e=>Array.isArray(e.path)&&1===e.path.length&&"asil_pending_lower"===e.path[0]);return"string"==typeof i?.committed_at?i.committed_at:null}catch{return null}}(r,e.project_id,e.item_id):null,d={id:s.id,type:s.type,req_type:s.data?.req_type,title:s.title,summary:s.data?.summary,body:s.data?.body,domains:s.data?.tags?.domains??[],level:s.data?.tags?.level,tags:s.data?.tags??{domains:[]},ownership:s.data?.ownership??{primary:null,additional:[]},relationships:o,links:s.data?.links??[],fields:(n=s.data?.fields,!n||"object"!=typeof n||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(e=>"string"==typeof e[1]))),status:Fl(s),...Co(s,{live:null!==i,since:c}),..."test-case"===s.type?{...Ul(s.data),latest_result:l[0]?.result??"not-run",test_results:l}:{},metadata:{created_at:s.created_at,created_by:s.created_by,updated_at:s.updated_at,updated_by:s.updated_by,source_id:s.data?.metadata?.source_id}};if(i){const n=s.data?.steps,a=Array.isArray(n)?n:[],o=(await $n(r,e.project_id,[e.item_id],{stepNumber:e=>{const t=a.findIndex(t=>t?.id===e);return t>=0?t+1:null}})).get(e.item_id)??[],l=0===(t=o).length?null:t.map(e=>`${e.person.name} is editing ${e.field_label} now.`).join(" ");return Vs(ys({...d,...i.revision?{base_token:await vn(i.revision,"item")}:{},seq:i.head,editing_now:o,...l?{presence:l}:{}}))}return Vs(ys(d))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}var t,n}H(Dd,{getItemHandler:()=>Ud});var Pd,Nd,Ld=D({"src/tools/get-item.ts"(){Lo(),ko(),Ql(),hd(),Ks(),gr(),Cd(),zd=["point","release_id","build","environment","tooling","evidence_url","step_results"]}}),Fd={};function Wd(e){const t=e.author??{},n=String(t.kind??"unknown"),r=!0===e.value_omitted;return{seq:Number(e.seq),item_id:e.item_id??null,path:e.path??null,field_label:En(e.path??null),kind:e.kind,old_value:e.summary?.old??null,...r?{}:{new_value:e.value??null},value_omitted:r,author:{kind:n,name:("agent"===n?t.label??t.name:t.name)??null},at:e.committed_at??null}}async function Vd(e){try{const t=await co(),n=await kd(t,e.project_id);if(null===n)return Bs(cr());if(!n)return Bs(Ss(Nd));if(void 0===e.since_seq){const n=await xn(t,e.project_id);return Vs(ys({project_id:e.project_id,changes:[],last_seq:n,has_more:!1}))}const{data:r,error:a}=await t.rpc("changes_since",{p_project_id:e.project_id,p_after_seq:e.since_seq,p_limit:e.limit??Pd});if(a)throw a;const i=r??{};return Vs(ys({project_id:e.project_id,changes:(i.changes??[]).map(Wd),last_seq:Number(i.last_seq??e.since_seq),has_more:!0===i.more}))}catch(e){return Bs(Ds(e))}}H(Fd,{LIST_CHANGES_DEFAULT_LIMIT:()=>Pd,LIST_CHANGES_NOT_NUMBERED:()=>Nd,listChangesHandler:()=>Vd,listedChange:()=>Wd});var Bd=D({"src/tools/list-changes.ts"(){ko(),gr(),Ks(),Cd(),Pd=100,Nd="This project does not number its changes yet. Use atoms_get_history for one item."}}),Jd=D({"src/core/snapshot-search.ts"(){}}),Qd={};async function Gd(e){try{const t=await co();let n,r,a=null;try{a=await ud(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return Bs(Ds(e))}if(a){const i=function(e,t,n){const r=t.trim().toLowerCase(),a=0===r.length?[]:e.filter(e=>{if(n.type&&e.type!==n.type)return!1;const t=e.data??{};return[e.title,t.body,t.summary].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(r))});return{totalCount:a.length,items:a.slice(0,n.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}}(await _d(t,e.project_id,a),e.query,{type:e.type,limit:e.limit});r=i.totalCount,n=i.items}else{const a=await fd(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});n=a.items,r=a.totalCount}return Vs(ys(n.map(e=>({id:e.id,title:e.title,type:e.type,status:Fl(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),gs(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(Qd,{searchHandler:()=>Gd});var Kd=D({"src/tools/search.ts"(){ko(),hd(),Jd(),Ks(),Ql()}}),Yd={};async function Zd(e){try{const t=await co(),{access_token:n}=await tt(),{items:r,totalCount:a}=await async function(e,t,n,r){const{ATOMS_SUPABASE_URL:a,ATOMS_SUPABASE_ANON_KEY:i}=await Promise.resolve().then(()=>(Je(),Pe)),s=await fetch(`${a}/functions/v1/embed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`,apikey:i},body:JSON.stringify({input:n})});if(!s.ok)throw new Error(`Embed function failed: ${s.status}`);const{embedding:o}=await s.json(),{data:l,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:l??[],totalCount:(l??[]).length,method:"semantic"}}(t,e.project_id,e.query,{type:e.type,limit:e.limit,accessToken:n});return Vs(ys(r.map(e=>({id:e.id,title:e.title,type:e.type,status:Fl(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),gs(a,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(Yd,{semanticSearchHandler:()=>Zd});var Xd=D({"src/tools/semantic-search.ts"(){ko(),at(),hd(),Ks(),Ql()}}),eu={};async function tu(e){try{if(e.baseline_id&&e.as_of)return Bs(Ss("baseline_id and as_of are mutually exclusive"));const t=await co();let n;if(e.baseline_id){const r=await pd(t,e.baseline_id);if(!r)return Bs(Ss("Baseline not found"));if(r.project_id!==e.project_id)return Bs(Ss("Baseline does not belong to this project"));n=lc(e.baseline_id)}else e.as_of&&(n=oc(od(e.as_of)));const{covered:r,uncovered:a,total:i,mitigators:s}=await async function(e,t,n){let r,a,i;if(n.moment){const s=(await _d(e,t,n.moment)).map(md);r=s.filter(e=>"requirement"===e.type),a=s.map(e=>({id:e.id,type:e.type,data:e.data})),i=[]}else r=await mc(()=>e.from("items").select("*").eq("project_id",t).eq("type","requirement").is("deleted_at",null),tc),a=await mc(()=>e.from("items").select("id, type, data").eq("project_id",t).is("deleted_at",null),tc),i=await mc(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t),nc);const s=r.filter(e=>!(n.domain&&!(e.data?.tags?.domains??[]).some(e=>ti(e)===ti(n.domain))||n.level&&Pa(e.data?.tags?.level)!==Pa(n.level))),o=id(a,i),l=qc(a,o),c=s.filter(e=>l.has(e.id)),d=s.filter(e=>!l.has(e.id)),u=Oc(a,o);return{covered:c,uncovered:d,total:s.length,mitigators:u}}(t,e.project_id,{domain:e.domain,level:e.level,moment:n}),o=a.map(e=>{const t=function(e,t){if(Ec(e))return[...t?.get(e.id)??[]]}(e,s);return{id:e.id,title:e.title,type:e.type,status:Fl(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,...t?{mitigated_by:t}:{}}});return Vs(ys({covered:r.length,uncovered:a.length,total:i,coverage_percent:Nc(r.length,i),covered_via_mitigation:Cc(a,s),uncovered_items:o}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(eu,{getCoverageHandler:()=>tu});var nu,ru,au=D({"src/tools/get-coverage.ts"(){ko(),hd(),ld(),jc(),Ks(),Ql(),Yc(),Pc()}}),iu={};async function su(e,t,n){const r=await mc(()=>e.from("items").select("id").eq("project_id",t).eq("type","requirement").is("deleted_at",null),tc);return(await gc(r.map(e=>e.id),r=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:n,p_requirement_ids:r}))).sort(ru)}async function ou(e){try{const t=await co();let n=null;if(e.release_id){const r=await pd(t,e.release_id);if(!r)return Bs(Ss(`Release ${e.release_id} not found`));if(r.project_id!==e.project_id)return Bs(Ss("Release does not belong to this project"));if(null===r.release_version)return Bs(ws(`Baseline "${r.name}" is not a formal Release.`,["Promote the baseline to a Release first (Snapshots view in the app)","Use atoms_list_baselines to see which baselines carry a release_version"]));n=r}else{const{data:r,error:a}=await t.from("baselines").select("id, release_version, release_status").eq("project_id",e.project_id).eq("release_status","released").is("deleted_at",null).maybeSingle();if(a)return Bs(Ps(a.message));n=r}if(!n)return Vs(ys({release:null,rerun:await su(t,e.project_id,null),hint:nu}),{complete:!0});const{data:r,error:a}=await t.rpc("verification_readiness",{p_project_id:e.project_id,p_release_id:n.id});if(a)return Bs(Ds(a));const i=n.id,s=(await mc(()=>t.from("verification_status").select("requirement_id, state, stale, points_total, points_run").eq("project_id",e.project_id).eq("release_id",i),["requirement_id"])).slice().sort(ru),o={release:{id:n.id,version:n.release_version,status:n.release_status},readiness:r??{},requirements:s,rerun:await su(t,e.project_id,i),...0===s.length?{hint:"projection empty; an admin may need to run rebuild_verification_from_runs for this project"}:{}};return e.include_gaps&&(o.gaps=await mc(()=>t.rpc("verification_notrun_points",{p_project_id:e.project_id,p_release_id:i}),["tc_id","asset","point_key"])),Vs(ys(o),{complete:!0})}catch(e){return Bs(Ds(e))}}H(iu,{verificationStatusHandler:()=>ou});var lu=D({"src/tools/verification-status.ts"(){ko(),hd(),jc(),Ks(),nu="This project has no current formal Release, so only the rerun list is returned, judged on every recorded run as the Matrix judges it. The readiness counts, the per-requirement states and the not-run points need a formal Release: promote a locked baseline in the Snapshots view, or pass release_id (atoms_list_baselines lists them).",ru=(e,t)=>e.requirement_id<t.requirement_id?-1:e.requirement_id>t.requirement_id?1:0}});function cu(e){if(!e||"object"!=typeof e)return{};const t=e,n=t.data,r=n&&"object"==typeof n?{...n}:{};return"title"in t&&(r.title=t.title),"type"in t&&(r.type=t.type),r}var du=D({"src/core/history.ts"(){}}),uu={};async function pu(e){try{const t=await co(),n=await async function(e,t,n,r){const{data:a,error:i}=await e.from("item_revisions").select("id, revision_number, fields_snapshot, valid_from, changed_by, event_source, event_session_id").eq("item_id",n).eq("project_id",t).order("revision_number",{ascending:!1}).limit(r);if(i)throw new Error(i.message);return a??[]}(t,e.project_id,e.item_id,e.limit);if(n.length>0){const t=function(e){return e.map((t,n)=>{const r=e[n+1]??null,a=1===t.revision_number||null===r,i="system"===t.event_source?"system_normalization":1===t.revision_number?"created":"updated",s=a?["(created)"]:function(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]),r=[];for(const a of n)JSON.stringify(e[a])!==JSON.stringify(t[a])&&r.push(a);return r}(cu(r?.fields_snapshot),cu(t.fields_snapshot));return{id:t.id,event_type:i,changed_by:t.changed_by??null,changed_at:t.valid_from,actor:"mcp"===t.event_source?"mcp_claude":"user",session_id:t.event_session_id??null,fields_changed:s}})}(n);return Vs(ys(t,gs(t.length,e.limit,0)))}const r=await async function(e,t,n,r){const{data:a,error:i}=await e.from("change_history").select("*").eq("item_id",n).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r);if(i)throw new Error(i.message);return a??[]}(t,e.project_id,e.item_id,e.limit),a=r.map(e=>{const t=[],n=e.old_data,r=e.new_data;if(n&&r){const e=new Set([...Object.keys(n),...Object.keys(r)]);for(const a of e)JSON.stringify(n[a])!==JSON.stringify(r[a])&&t.push(a)}else r?t.push("(created)"):n&&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 Vs(ys(a,gs(a.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(uu,{getHistoryHandler:()=>pu});var mu=D({"src/tools/get-history.ts"(){ko(),hd(),du(),Ks()}});function _u(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function fu(e){const t=yu(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:`["${t}"]`}function hu(e){const t=_u(e.from_id),n=_u(e.to_id);return"child"===e.type?`${t} --\x3e ${n}`:"verified_by"===e.type?`${t} -.-> ${n}`:"related"===e.type?`${t} -.- ${n}`:null}function yu(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var gu=D({"src/core/mermaid.ts"(){}}),wu={};async function vu(e){try{if(e.baseline_id&&e.as_of)return Bs(Ss("baseline_id and as_of are mutually exclusive"));const t=await co();let n,r,a;if(e.baseline_id){const r=await pd(t,e.baseline_id);if(!r)return Bs(Ss("Baseline not found"));if(r.project_id!==e.project_id)return Bs(Ss("Baseline does not belong to this project"));n=lc(e.baseline_id)}else e.as_of&&(n=oc(od(e.as_of)));if(n){r=(await _d(t,e.project_id,n)).map(md).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),a=id(r,[])}else r=await mc(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),tc),a=id(r,await mc(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),nc));return Vs(ys(function(e){const t=e.items,n=e.relationships??[],r=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${yu(e.emptyLabel??"No items in project")}]`,node_count:0,edge_count:0};const a=new Map(t.map(e=>[e.id,e])),i=function(e,t,n,r){if(n)return[n];const a=new Set(t.filter(e=>"child"===e.type).map(e=>e.to_id));return e.filter(e=>!a.has(e.id)).filter(e=>r||"test-case"!==e.type).map(e=>e.id)}(t,n,e.rootItemId,e.includeTests),s=i.map(e=>({id:e,depth:0})),o=new Set,l=new Set,c=[],d=[];for(;s.length>0;){const{id:t,depth:i}=s.shift();if(o.has(t)||i>r)continue;const u=a.get(t);if(u&&(e.includeTests||"test-case"!==u.type)){o.add(t),c.push(` ${_u(t)}${fu(u)}`);for(const c of n){if(c.from_id!==t)continue;const n=a.get(c.to_id);if(!n)continue;if(!e.includeTests&&"test-case"===n.type)continue;if(i+1>r)continue;const u=hu(c);if(!u)continue;const p=`${c.from_id}:${c.type}:${c.to_id}`;l.has(p)||(l.add(p),d.push(` ${u}`),o.has(c.to_id)||s.push({id:c.to_id,depth:i+1}))}}}return{mermaid:["graph TD",...c,...d].join("\n"),node_count:o.size,edge_count:l.size}}({items:r,relationships:a,rootItemId:e.root_item_id,depth:e.depth,includeTests:e.include_tests,emptyLabel:"No items in project"})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(wu,{exportMermaidHandler:()=>vu});var bu,ju=D({"src/tools/export-mermaid.ts"(){ko(),hd(),Ks(),gu(),ld(),jc()}});function ku(e){return"requirement"===e?"REQ":"test-case"===e?"TC":"note"===e?"NOTE":"TABLE"}function Su(e){const t={};return n=>{const r=e[n]??[],a=t[n]??0;if(a>=r.length)throw new Error(`ID generation failed: no reserved id left for ${n}`);return t[n]=a+1,r[a]}}async function Au(e,t,n){const r={};let a=0;for(const[e,t]of Object.entries(n)){if(!Number.isInteger(t)||t<0)throw new Error(`ID generation failed: invalid count for ${e}`);0!==t&&(r[e]=t,a+=t)}if(0===a)return{};if(a>bu)throw new Error(`ID generation failed: at most ${bu} ids per call, ${a} asked`);const{data:i,error:s}=await e.rpc("reserve_item_ids",{p_project_id:t,p_counts:r});if(s){if(function(e){return!!e&&("PGRST202"===e.code||"42883"===e.code||/Could not find the function public\.reserve_item_ids/i.test(String(e.message??"")))}(s))return async function(e,t,n){const r={};for(const a of Object.keys(n)){const{data:i,error:s}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:a});if(s)throw new Error(`ID generation failed: ${s.message}`);const o=/^([A-Z]+)-(\d+)$/.exec(String(i??""));if(!o||o[1]!==a)throw new Error(`ID generation failed: unexpected id from next_item_id: ${String(i)}`);const l=Number(o[2]);r[a]=Array.from({length:n[a]},(e,t)=>{return`${a}-${n=l+t,String(n).padStart(3,"0")}`;var n})}return r}(e,t,r);throw new Error(`ID generation failed: ${s.message}`)}const o={};for(const[e,t]of Object.entries(r)){const n=i&&"object"==typeof i?i[e]:void 0;if(!Array.isArray(n)||n.length!==t||!n.every(t=>"string"==typeof t&&new RegExp(`^${e}-[0-9]{3,}$`).test(t)))throw new Error(`ID generation failed: reserve_item_ids answered an unexpected shape for ${e}`);o[e]=n}return o}var Iu=D({"src/core/item-id-reservation.ts"(){bu=1e3}});async function xu(e,t){const n=await lr(e,t);return null===n?"unreadable":n?"ops":"main"}function $u(){return Bs(cr())}async function Eu(e){const t=[...e.ops];let n=e.preFound??new Map;!e.preFound&&e.deterministic&&t.length>0&&(n=await mr(e.client,e.projectId,t.map(e=>e.op_id)));const r=t.filter(e=>!n.has(e.op_id));let a={answers:[],results:[],notSent:[]};if(r.length>0&&(a=await async function(e,t,n,r={}){return Id(e,t,n,r)}(e.client,e.projectId,r,e.send),void 0!==a.error&&0===a.results.length))throw a.error;const i=await _r(e.client,e.projectId,a.answers),s=function(e,t,n){const r=new Map(t.map(e=>[e.op_id,e]));return e.map(e=>{if(null!==e.item_id&&void 0!==e.item_id)return e;if("string"==typeof e.name&&e.name.length>0)return e;const t=r.get(e.op_id);if(!t||null!==t.item_id)return e;let a;if("taxonomy"===t.path[0])a="rename"===t.kind?String(t.base??""):"move_row"===t.kind?String(t.row_id??""):t.path[2]&&"is_function"===t.path[3]?t.path[2]:"string"==typeof t.value?t.value:void 0;else if("variables"===t.path[0]){const e=t.path[1]??("string"==typeof t.row_id?t.row_id:void 0);a="add"===t.kind?String(t.value?.name??""):e?n?.get(e):void 0}return a?{...e,name:a}:e})}([...e.refusals??[],...n.values(),...i,...or(a.notSent)],t,e.variableNames),o=a.results.flatMap(e=>e.skipped_items??[]),l=o.map(e=>"string"==typeof e?e:e.item_id).filter(Boolean);let c;return l.length>0&&(c=await An(e.client,e.projectId,l)),{outcome:await zn({answers:s,ops:t,skippedItems:o,...c?{openRevisions:c}:{},...e.labels?{labels:e.labels}:{}}),answers:s,results:a.results,chunks:a.chunks,found:n}}function qu(e,t,n,r){if(0===e.not_applied.length)return Vs(ys({...t,...r??{},...Bn(e),...n?{chunks:n}:{}}));const{isError:a,result:i}=Vn(e,{...r??{},...n?{chunks:n}:{}});return a?Bs(i):Vs(i)}function Ou(e,t,n){return e&&!t?dr(e,n):null}function Ru(e){return null==e?[]:(Array.isArray(e)?[...e]:[e]).filter(e=>"string"==typeof e&&e.length>0)}function Tu(e){return e.some(e=>void 0!==e.acceptance_revoked&&null!==e.acceptance_revoked&&!1!==e.acceptance_revoked)}async function Mu(e){const t=await On({client:e.client,projectId:e.projectId,requests:[{itemId:e.itemId,tokens:e.tokens,paths:e.cells.map(e=>e.path),values:e.cells.map(e=>e.value)}],mode:"single"}),n=t.items.get(e.itemId),r=[];for(const t of e.cells){const a=n?.bases.get(qn(t.path));a&&r.push(Tn({op_id:Qn(),kind:"set",item_id:e.itemId,path:[...t.path],value:t.value},a))}return{ops:r,refusals:t.refusals}}async function zu(e){const t=_o(),n=Yh(),r=er(e.contents),a=[],i=[];for(let s=0;s<e.contents.length;s+=1)a.push(await Jn(e.key?Kn({userId:t,projectId:e.projectId,family:Xn(e.tool),key:e.key,itemIdOrK:s}):Gn({userId:t,projectId:e.projectId,content:e.contents[s],k:r[s],sessionId:n}))),i.push(await Jn(e.key?Kn({userId:t,projectId:e.projectId,family:Xn(e.tool),key:e.key,itemIdOrK:`link:${s}`,path:["relationships","children"]}):[t,e.projectId,"create_link",a[s]]));return{create:a,link:i}}async function Cu(e,t,n){const r=n.filter(e=>e.item_id&&"string"==typeof e.revision_id&&e.revision_id.length>0),a=new Map;if(0===r.length)return a;const i=await In(e,t,r.map(e=>e.revision_id));for(const e of r){const t=i.get(e.revision_id);t&&a.set(e.item_id,await vn(t,"all"))}return a}async function Du(e){let t=0,n=0;for(;;){let r;try{r=await Eu({client:e.client,projectId:e.projectId,ops:[e.op],labels:e.labels})}catch(e){throw t>0&&e instanceof Error&&(e.message=`${e.message} (${t} items were already updated: call again to finish)`),e}n+=1;const a=r.answers.find(t=>t.op_id===e.op.op_id);if("number"==typeof a?.retagged&&(t+=a.retagged),!(!0===e.repeat&&"applied"===a?.status&&"number"==typeof a.remaining&&a.remaining>0)||n>=2e3)return{run:r,retagged:t,calls:n}}}function Hu(e,t,n){return e.answers.find(e=>e.status===t&&(void 0===n||e.reason===n))}var Uu,Pu,Nu=D({"src/tools/_ops.ts"(){ko(),ey(),gr(),Ks(),Cd()}});function Lu(e){const t=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(t){const n=t.toLowerCase();if("1"===n||"true"===n||"all"===n)return!0;if(t.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!oe().require_confirmation_for.includes(e)}function Fu(e,t=Uu){const n=Date.now()+t,r={...e,exp:n},a=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${a}.${M.default.createHmac("sha256",Pu).update(a).digest("base64url")}`,expires_at:new Date(n).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function Wu(e,t){if("string"!=typeof e||!e.includes("."))return{valid:!1,reason:"Token format invalid"};const[n,r]=e.split(".");if(!n||!r)return{valid:!1,reason:"Token format invalid"};const a=M.default.createHmac("sha256",Pu).update(n).digest("base64url"),i=Buffer.from(r,"utf8"),s=Buffer.from(a,"utf8");if(i.length!==s.length||!M.default.timingSafeEqual(i,s))return{valid:!1,reason:"Token signature invalid"};let o;try{o=JSON.parse(Buffer.from(n,"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 Vu(e){if(Array.isArray(e))return e.map(Vu);if(null!==e&&"object"==typeof e){const t={};for(const n of Object.keys(e).sort())t[n]=Vu(e[n]);return t}return e}function Bu(e){const t=JSON.stringify(Vu(e));return M.default.createHash("sha256").update(t).digest("base64url").slice(0,16)}var Ju,Qu=D({"src/middleware/confirmation.ts"(){ce(),Uu=6e4,Pu=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:M.default.randomBytes(32).toString("base64url")})()}});function Gu(e,t,n,r){const a=r(t);if(!a)return t;const i=e.trim(),s=n.filter(e=>"string"==typeof e);return s.find(e=>e===i)??s.find(e=>Pa(e)===Pa(i))??s.find(e=>r(e)===a)??t}function Ku(e,t){return"locked"===t?`Level "${e}" is not in the project's level list, and your org's MCP policy does not let this session add levels, so the app's Strata view and level filter place this item on no level until an admin adds it. Or set a listed level (atoms_list_levels) with atoms_update_item.`:"failed"===t?`Level "${e}" could not be added to the project's level list, so the app's Strata view and level filter place this item on no level yet. Add it with atoms_create_level, or set a listed level (atoms_list_levels) with atoms_update_item.`:null}var Yu=D({"src/core/levels.ts"(){Oi(),Bi(),Ju="items_not_shown counts the items, among item_count, whose level is spelled differently from the listed name (for example with hyphens for spaces), so the app's Strata view and level filter place them on no level. Find them with atoms_list_items level=<the spelling> and set their level to the listed name with atoms_update_item."}}),Zu={};function Xu(e){const t=hs(e??"");return"sub-system"===t?"subsystem":t}async function ep(e,t){const{data:n,error:r}=await e.from("metadata").select("levels").eq("project_id",t).maybeSingle();if(r)throw new Error(`metadata read failed: ${r.message}`);return Array.isArray(n?.levels)?n.levels.filter(e=>"string"==typeof e):[]}async function tp(e,t){return{levels:await ep(e,t)}}async function np(e,t){return(await mc(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),tc)).map(e=>e.data?.tags?.level)}async function rp(e,t,n){const r=hs(n);return r?Gu(n,r,await ep(e,t),Xu):r}async function ap(e,t,n){const r=hs(n??""),a=Xu(r);if(!r)return"none";try{const{levels:n}=await tp(e,t);if(n.some(e=>Xu(e)===a))return"present";if(!L(oe(),"atoms_create_level"))return"locked";if(!0===await lr(e,t)){const n={op_id:Qn(),kind:"add",item_id:null,path:["taxonomy","levels"],value:r},{run:a}=await Du({client:e,projectId:t,op:n});return a.outcome.not_applied.length>0?"failed":"registered"}const i=async()=>{const{error:n}=await e.rpc("mutate_project_levels",{p_project_id:t,p_action:"add",p_values:[r]});return n?"failed":"registered"};return await i()}catch{return"failed"}}function ip(e,t){const n=[...e],r=[];return t.forEach((e,a)=>{if(n[a]===e)return;const i=n.indexOf(e);i<0||(n.splice(i,1),n.splice(a,0,e),r.push({level:e,after:0===a?null:t[a-1]}))}),r}async function sp(e){try{const t=await co(),{levels:n}=await tp(t,e.project_id),r=function(e,t,n){const r=new Set(e.map(e=>Pa(e))),a=new Map,i=new Map;for(const e of t){const t="string"==typeof e?e:"",s=n(t);if(!s)continue;if(a.set(s,(a.get(s)??0)+1),r.has(Pa(t)))continue;const o=i.get(s)??new Map;o.set(t,(o.get(t)??0)+1),i.set(s,o)}const s=new Set;return e.map(e=>{const t=n(e),r={item_count:a.get(t)??0},o=i.get(t);return o&&!s.has(t)&&(s.add(t),r.items_not_shown=[...o.values()].reduce((e,t)=>e+t,0),r.not_shown_spellings=[...o.keys()].sort()),r})}(n,await np(t,e.project_id),Xu),a=r.some(e=>void 0!==e.items_not_shown);return Vs(ys({levels:n.map((e,t)=>({name:e,prefix:`L${t}`,...r[t]})),total:n.length,note:"L# is the level's position in this list (0-based). Names are user-defined."+(a?` ${Ju}`:"")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}async function op(e,t){let n;try{const r=await co();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const a=t??await xu(r,e.project_id);if("unreadable"===a)return $u();n=a;const{levels:i}=await tp(r,e.project_id),s=hs(e.name),o=Xu(s);if(!s)return Bs(Ss("Level name cannot be empty."));if(i.some(e=>Xu(e)===o))return Bs(Ss(`Level "${s}" already exists in this project.`));if("ops"===a){const t={op_id:Qn(),kind:"add",item_id:null,path:["taxonomy","levels"],value:s},{run:n}=await Du({client:r,projectId:e.project_id,op:t});if(n.answers.some(e=>"noop"===e.status))return Bs(Ss(`Level "${s}" already exists in this project.`));if(n.outcome.not_applied.length>0)return qu(n.outcome,{},n.chunks);const a=(await ep(r,e.project_id)).findIndex(e=>Xu(e)===o),l=`L${a>=0?a:i.length}`;return qu(n.outcome,{level:{name:s,prefix:l},message:`Level "${s}" registered as ${l}. Tag items with level="${s}".`},n.chunks)}const l=async()=>{const{data:t,error:n}=await r.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"add",p_values:[s]});if(n)throw new Error(n.message);const a=t?.levels??[...i,s],l=a.includes(s)?void 0:a.find(e=>Xu(e)===o);if(void 0!==l){const e=`L${a.indexOf(l)}`;return Vs(ys({level:{name:l,prefix:e},message:`Level "${l}" is already present as ${e} (another writer added it with this spelling); nothing was added. Tag items with level="${l}".`}))}const c=a.indexOf(s),d=`L${c>=0?c:i.length}`;return Vs(ys({level:{name:s,prefix:d},message:`Level "${s}" registered as ${d}. Tag items with level="${s}".`}))};return await l()}catch(r){const a=Ou(n,t,r);return a?op(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}async function lp(e,t){let n;try{const r=await co();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const a=t??await xu(r,e.project_id);if("unreadable"===a)return $u();n=a;const i=Xu(Ls(e.name));if(!i)return Bs(Ss("Level name cannot be empty."));const{levels:s}=await tp(r,e.project_id),o=s.filter(e=>Xu(e)===i),l="ops"===a?0:(await np(r,e.project_id)).filter(e=>Xu(e)===i).length;if(0===o.length&&0===l&&"ops"!==a)return Bs(vs("Level",e.name));const c=o[0]??e.name;if(l>0)return Bs(Ss(`Level "${c}" is used by ${l} item${l>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`));if(Lu("atoms_delete_level")){const t={tool:"atoms_delete_level",project_id:e.project_id,target:i};if(!e.confirmation_token){const e=Fu(t);return Vs(ys({status:"confirmation_required",preview:{level_name:c,items_using_count:0},confirmation_token:e.token,expires_at:e.expires_at,expires_in_seconds:e.expires_in_seconds,message:`Re-call atoms_delete_level with the same project_id, name, and confirmation_token within ${e.expires_in_seconds}s to execute.`}))}const n=Wu(e.confirmation_token,t);if(!n.valid)return Bs(Ss(`confirmation_token rejected: ${n.reason}`))}if("ops"===a){const t={op_id:Qn(),kind:"remove",item_id:null,path:["taxonomy","levels"],value:c},{run:n}=await Du({client:r,projectId:e.project_id,op:t}),a=Hu(n,"invalid","level_in_use");if(a){const e="number"==typeof a.count?a.count:1;return Bs(Ss(`Level "${c}" is used by ${e} item${e>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`))}if(Hu(n,"deleted"))return Bs(vs("Level",e.name));if(n.outcome.not_applied.length>0)return qu(n.outcome,{},n.chunks);const i=await ep(r,e.project_id),o=Na(s,i);return qu(n.outcome,{level:{name:c},remaining_levels:i,message:`Level "${c}" deleted. Every later level's L# shifts down by one.`+(o?" "+o:"")},n.chunks)}const d=async()=>{const{data:t,error:n}=await r.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"remove",p_values:o});if(n)throw new Error(n.message);const a=t?.levels??[],i=Na(s,a);return Vs(ys({level:{name:c},remaining_levels:a,message:`Level "${c}" deleted. Every later level's L# shifts down by one.`+(i?" "+i:"")}))};return await d()}catch(r){const a=Ou(n,t,r);return a?lp(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}async function cp(e,t){let n;try{const r=await co();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const a=t??await xu(r,e.project_id);if("unreadable"===a)return $u();n=a;const i=Array.isArray(e.names)?e.names.map(e=>Ls(String(e??"")).trim()).filter(e=>e.length>0):[];if(0===i.length)return Bs(Ss("names must be a non-empty array of the project's existing levels, in the order you want them."));const{levels:s}=await tp(r,e.project_id),o=function(e,t,n){if(t.length!==e.length)return null;const r=new Array(e.length).fill(!1),a=t=>{const n=e.findIndex((e,n)=>!r[n]&&t(e));return n<0?null:(r[n]=!0,e[n])},i=[];for(const e of t){const t=a(t=>t===e)??a(t=>Pa(t)===Pa(e))??a(t=>""!==n(t)&&n(t)===n(e));if(null===t)return null;i.push(t)}return i}(s,i,Xu);if(!o)return Bs(Ss(`names must list every existing level exactly once. Levels: ${s.length>0?s.join(", "):"(none)"}`));if("ops"===a){const t=ip(s,o);if(t.length>0){const n=t.map(e=>({op_id:Qn(),kind:"move_row",item_id:null,path:["taxonomy","levels"],row_id:e.level,value:{after:e.after}})),a=await Eu({client:r,projectId:e.project_id,ops:n});if(Hu(a,"deleted"))return Bs(vs("Level",e.names.join(", ")));if(a.outcome.not_applied.length>0)return qu(a.outcome,{},a.chunks)}const n=await ep(r,e.project_id),a=Na(s,n);return Vs(ys({levels:n.map((e,t)=>({name:e,prefix:`L${t}`})),message:"Levels reordered. L# now follows this order everywhere it renders (Strata, sidebar, exports)."+(a?" "+a:"")}))}const l=async()=>{const{data:t,error:n}=await r.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"reorder",p_values:o});if(n)throw new Error(n.message);const a=t?.levels??o,i=Na(s,a);return Vs(ys({levels:a.map((e,t)=>({name:e,prefix:`L${t}`})),message:"Levels reordered. L# now follows this order everywhere it renders (Strata, sidebar, exports)."+(i?" "+i:"")}))};return await l()}catch(r){const a=Ou(n,t,r);return a?cp(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}H(Zu,{createLevelHandler:()=>op,deleteLevelHandler:()=>lp,ensureLevelRegistered:()=>ap,getProjectLevels:()=>ep,levelKey:()=>Xu,levelMoves:()=>ip,listLevelsHandler:()=>sp,reorderLevelsHandler:()=>cp,storedLevelSpelling:()=>rp});var dp,up,pp=D({"src/tools/levels.ts"(){ko(),gr(),Nu(),Qu(),Ks(),Oi(),B(),ce(),jc(),Yu()}});function mp(e){if(!e)return!1;const t=String(e.code??""),n=String(e.message??"");return"55P03"===t||"40P01"===t||/item_save_busy|deadlock detected/i.test(n)}async function _p(e,t=dp){let n=await e();for(const r of t){if(!mp(n.error))return n;await up.sleep(Math.round(r*up.jitter())),n=await e()}return n}var fp,hp,yp,gp=D({"src/core/busy-retry.ts"(){dp=[50,100,200,400,800],up={sleep:e=>new Promise(t=>setTimeout(t,e)),jitter:()=>.5+Math.random()}}}),wp=D({"src/core/project-field-counts.ts"(){jc()}});function vp(e){if(!Array.isArray(e))return;const t=new Set(e.filter(e=>"string"==typeof e&&hp.has(e)));return 0!==t.size?fp.filter(e=>t.has(e)):void 0}var bp,jp,kp=D({"src/core/field-scope.ts"(){fp=["requirement","test-case","note","table"],hp=new Set(fp),yp=e=>JSON.stringify({type:e.type,options:e.options??[],appliesTo:e.appliesTo??null})}}),Sp={};async function Ap(e,t){const{data:n,error:r}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(r)throw r;return Ip(n?.fields)}function Ip(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||"object"!=typeof r)continue;const e=r,a="string"==typeof e.name?e.name.trim():"";if(!a)continue;const i=a.toLowerCase();if(n.has(i))continue;n.add(i);const s=void 0===e.type?"text":"string"==typeof e.type&&jp.has(e.type)?e.type:"text",o=Array.isArray(e.options)?Cp(e.options):[],l=vp(e.appliesTo??e.applies_to);t.push({name:a,type:s,..."select"===s?{options:o}:{},...l?{appliesTo:l}:{}})}return t}function xp(e,t){const n=e.name.trim();if(!n)return"Field name cannot be empty.";if(n.length>60)return"Field name must be 60 characters or fewer.";if(!jp.has(e.type))return"Field type is not supported.";const r=t.find(e=>e.name.toLowerCase()===n.toLowerCase());if(r)return`Field "${r.name}" already exists.`;if("select"===e.type){const t=Cp(e.options??[]);if(0===t.length)return"Select fields need at least one option.";if(t.length>100)return"Select fields support at most 100 options.";if(t.some(e=>e.length>120))return"Select options must be 120 characters or fewer."}return null}function $p(e,t){const n=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!n.has(e.toLowerCase()))}function Ep(e,t){const n=new Map(e.map(e=>[e.name.toLowerCase(),e.name])),r={};for(const[e,a]of Object.entries(t))r[n.get(e.toLowerCase())??e]=a;return r}function qp(e,t,n){if("string"!=typeof n||!e||"object"!=typeof e||Array.isArray(e))return!1;const r=t.toLowerCase();return Object.entries(e).some(([e,t])=>e.toLowerCase()===r&&t===n)}function Op(e,t,n=new Set,r){const a=$p(e,t);if(a.length>0)return{error:`Unknown field${a.length>1?"s":""}: ${a.join(", ")}. Defined: ${e.length>0?e.map(e=>e.name).join(", "):"(none)"}. Define fields first with atoms_create_field.`};const i={},s=new Map(e.map(e=>[e.name.toLowerCase(),e]));for(const[e,a]of Object.entries(t)){const t=s.get(e.toLowerCase());if(!t)continue;if(qp(r,e,a)){a.trim()&&(i[t.name]=a);continue}const o=Rp(t,a,n);if(o.error)return{error:o.error};o.value&&(i[t.name]=o.value)}return{fields:i}}function Rp(e,t,n){const r=t.trim();if(!r)return{value:""};if(r.length>1e4)return{error:`${e.name} is too long.`};switch(e.type){case"text":case"long":return{value:r};case"bool":{const t=r.toLowerCase();return"yes"===t?{value:"yes"}:"no"===t?{value:"no"}:{error:`${e.name} must be yes or no.`}}case"date":return function(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;const t=new Date(`${e}T00:00:00.000Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}(r)?{value:r}:{error:`${e.name} must be an ISO date.`};case"person":return zp(r)&&n.has(r)?{value:r}:{error:`${e.name} must be an active project member ID.`};case"select":return(e.options??[]).includes(r)?{value:r}:{error:`${e.name} must be one of: ${(e.options??[]).join(", ")}.`};case"number":return Number.isFinite(Number(r))?{value:r}:{error:`${e.name} must be numeric.`};case"link":{const t=function(e){if(!e)return{label:"",url:""};try{const t=JSON.parse(e);if(t&&"object"==typeof t&&"string"==typeof t.url){const e=t.label;return{label:"string"==typeof e?e:"",url:t.url}}}catch{}return{label:"",url:e}}(r);return function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(t.url)?{value:Tp(t.label,t.url)}:{error:`${e.name} must be an http(s) URL.`}}}}function Tp(e,t){const n=t.trim();return n?JSON.stringify({label:e.trim(),url:n}):""}async function Mp(e,t,n,r,a){const i=new Map(n.map(e=>[e.name.toLowerCase(),e])),s=new Map;for(const[e,t]of Object.entries(r)){if(qp(a,e,t))continue;const n=i.get(e.toLowerCase());"person"===n?.type&&t.trim()&&s.set(t.trim(),n)}const o=new Set;for(const[n,r]of s){if(!zp(n))return{error:`${r.name} must be an active project member ID.`};const{data:a,error:i}=await e.rpc("is_active_project_member_for_field",{p_project_id:t,p_person_user_id:n,p_actor_user_id:_o()});if(i)return{error:i.message};!0===a&&o.add(n)}return Op(n,r,o,a)}function zp(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function Cp(e){const t=[],n=new Set;for(const r of e){if("string"!=typeof r)continue;const e=r.trim();if(!e)continue;const a=e.toLowerCase();n.has(a)||(n.add(a),t.push(e))}return t}async function Dp(e){try{const t=await co(),n=await Ap(t,e.project_id),r=await async function(e,t,n){const r=Object.fromEntries(n.map(e=>[e.name,0])),a=new Map(n.map(e=>[e.name.toLowerCase(),e.name])),i=await mc(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),tc);for(const e of i){const t=e.data?.fields;if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,n]of Object.entries(t)){const t=a.get(e.toLowerCase());t&&"string"==typeof n&&n.length>0&&(r[t]+=1)}}return r}(t,e.project_id,n);return Vs(ys({fields:n.map(e=>({name:e.name,type:e.type,options:e.options??[],...e.appliesTo?{appliesTo:e.appliesTo}:{},item_count:r[e.name]??0})),total:n.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ds(e))}}async function Hp(e,t){let n;try{const r=await co();try{await vo(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Bs(ht("project"));throw e}const a=t??await xu(r,e.project_id);if("unreadable"===a)return $u();n=a;const{data:i}=await r.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),s=Ip(i?.fields),o=vp(e.appliesTo),l={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:Cp(e.options??[])}:{},...o?{appliesTo:o}:{}},c=xp(l,function(e,t,n){if(!n)return e;const r=t.name.toLowerCase();return e.some(e=>e.name.toLowerCase()===r&&yp(e)===yp(t))?e.filter(e=>e.name.toLowerCase()!==r):e}(s,l,"ops"===a));if(c)return Bs(Ss(c));const d=function(e,t){return"organization"!==e?null:t&&0!==t.length?t.length>=fp.length?null:'An organization-scoped field cannot be restricted to specific item types (appliesTo is a project-scoped-field feature only; the org field library has no per-type scope column). Omit appliesTo, list all item types, or use scope="project".':null}(e.scope,o);if(d)return Bs(Ss(d));const{data:u,error:p}="organization"===e.scope?await r.rpc("create_org_project_field_definition",{p_project_id:e.project_id,p_field:l,p_actor_user_id:_o()}):await r.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"create",p_field:"ops"===a?{...l,op_id:Qn()}:l,p_field_name:null,p_actor_user_id:_o()});if(p)throw p;return Vs(ys({field:u?.field??l,..."organization"===e.scope?{created_projects:u?.created_projects??[],skipped_projects:u?.skipped_projects??[]}:{},message:`Field "${l.name}" defined. Set values with atoms_update_item fields={"${l.name}": "<value>"}.`}))}catch(r){const a=Ou(n,t,r);return a?Hp(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ds(r))}}async function Up(e,t){let n;try{const r=await co();try{await vo(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Bs(ht("project"));throw e}const a=t??await xu(r,e.project_id);if("unreadable"===a)return $u();n=a;const i=e.name.trim(),{data:s,error:o}=await r.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"delete",p_field:"ops"===a?{op_id:Qn()}:null,p_field_name:i,p_actor_user_id:_o()});if(o)throw o;return function(e){const t=e?.answers?.[0];if("noop"===t?.status)throw Object.assign(new Error("project_field_not_found"),{code:"P0002"})}(s),Vs(ys({deleted:s?.deleted??i}))}catch(r){const a=Ou(n,t,r);return a?Up(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ds(r))}}async function Pp(e){try{const t=await co();try{await vo(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Bs(ht("project"));throw e}const n=Array.isArray(e.names)?e.names.map(e=>String(e??"").trim()).filter(e=>e.length>0):[];if(0===n.length)return Bs(Ss("names must be a non-empty array of existing field names, in the order you want them"));const r=await Ap(t,e.project_id),a=r.map(e=>e.name.toLowerCase()).sort(),i=n.map(e=>e.toLowerCase()).sort();if(a.length!==i.length||a.some((e,t)=>e!==i[t]))return Bs(Ss(`names must list every existing field exactly once. Defined: ${r.length>0?r.map(e=>e.name).join(", "):"(none)"}`));const{data:s,error:o}=await t.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"reorder",p_field:n,p_field_name:null,p_actor_user_id:_o()});if(o)throw o;return Vs(ys({fields:Ip(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ds(e))}}H(Sp,{PROJECT_FIELD_TYPES:()=>bp,canonicalizeFieldKeys:()=>Ep,createFieldHandler:()=>Hp,deleteFieldHandler:()=>Up,findUnknownFieldNames:()=>$p,getProjectFields:()=>Ap,isStoredFieldValue:()=>qp,listFieldsHandler:()=>Dp,normalizeProjectFields:()=>Ip,reorderFieldsHandler:()=>Pp,validateAndCanonicalizeFieldValues:()=>Op,validateProjectFieldDefinition:()=>xp,validateProjectFieldValuesForWrite:()=>Mp});var Np=D({"src/tools/fields.ts"(){ko(),Ks(),wp(),Xt(),gr(),Nu(),kp(),bp=["text","long","bool","date","person","select","number","link"],jp=new Set(bp)}}),Lp={};async function Fp(e){try{const t=await co();try{await wo(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const n=await kd(t,e.project_id);if(null===n)return Bs(cr());e.title=Ls(e.title),void 0!==e.body&&(e.body=Ls(e.body)),void 0!==e.summary&&(e.summary=Ls(e.summary)),void 0!==e.level&&(e.level=Ls(e.level)),e.domains&&(e.domains=e.domains.map(e=>Ls(e)));const r=(e.domains??[]).map(hs).filter(e=>e.length>0),a=void 0!==e.level?await rp(t,e.project_id,e.level):void 0;if(r.length>0){const{data:n,error:a}=await t.from("metadata").select("domains, function_tags").eq("project_id",e.project_id).maybeSingle();if(a)throw new Error(`metadata read failed: ${a.message}`);const i=n?.domains??[],s=Ai(r,Si(n?.function_tags),hs);if(s.length>0)return Bs(Ss(Ii(s),os));if(i.length>0){const e=new Set(i.map(hs).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return Bs(Ss(`Unknown domain${t.length>1?"s":""}: ${t.join(", ")}. Registered: ${i.join(", ")}. Add new domains via Taxonomy Management in the ATOMS web app first.`))}}let i;if(e.fields&&Object.keys(e.fields).length>0){const{getProjectFields:n,validateProjectFieldValuesForWrite:r}=await Promise.resolve().then(()=>(Np(),Sp)),a=await n(t,e.project_id),s=await r(t,e.project_id,a,e.fields);if(s.error)return Bs(Ss(s.error));i=s.fields}if(void 0!==e.req_type){const t=kc(e.req_type,e.type);if(t)return Bs(Ss(t))}const s={sanitizedDomains:r,sanitizedLevel:a,canonicalFields:i};return await ur(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=_o(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n,o=[...new Set(t.parent_ids??[])],l=nr({type:t.type,title:t.title,body:t.body,summary:t.summary,req_type:t.req_type,domains:a,level:i,parent_ids:o,fields:s}),c=t.idempotency_key,d=Xn("atoms_create_item"),u=await Jn(c?Kn({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:[]}):Gn({userId:r,projectId:t.project_id,content:l,k:0,sessionId:Yh()})),p=(await mr(e,t.project_id,[u])).get(u);if(p&&("applied"===p.status||"noop"===p.status)&&p.item_id)return Vs(ys({id:p.item_id,type:t.type,title:t.title,project_id:t.project_id,replayed:!0,message:Yt,seq:p.seq??null}));const m=(await Au(e,t.project_id,{[ku(t.type)]:1}))[ku(t.type)][0],_={summary:t.summary,body:t.body,...t.req_type?{req_type:t.req_type}:{},tags:{domains:a,level:i??""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],...s?{fields:s}:{}},f=[{op_id:u,kind:"create_item",item_id:m,path:[],value:{type:t.type,title:t.title,data:_}}];for(const e of o)f.push({op_id:c?await Jn(Kn({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:["relationships","parents","add",e]})):Qn(),kind:"add",item_id:m,path:["relationships","parents"],value:e});const h=await Id(e,t.project_id,f,{mode:"single"});if(void 0!==h.error&&0===h.results.length)throw h.error;const y=await _r(e,t.project_id,h.answers),g=await $d({client:e,projectId:t.project_id,answers:y,ops:f,results:h.results,relooked:!0});await Od(e,t.project_id,f,y,"created");const w=y.find(e=>e.op_id===u);if("invalid"===w?.status&&"op_id_reused"===w.reason)return Bs(ws(Kt,["Send the call again with a new idempotency_key, or without one"],{code:"op_id_reused",retryable:!1}));if(g.not_applied.length>0)return qd(g,{id:m,type:t.type});const v=w?.item_id??m,b=!0===w?.replayed,j=w?.revision_id??null;let k;if(j){const n=(await In(e,t.project_id,[j])).get(j);n&&(k=await vn(n,"all"))}const S={id:v,type:t.type},A={...k?{base_token:k}:{},...Bn(g),...b?{replayed:!0,message:Yt}:{}};return!1===t.echo?Vs(ys({...S,...A})):Vs(ys({...S,title:t.title,summary:t.summary??"",body:t.body??"",...t.req_type?{req_type:t.req_type}:{},domains:a,level:i??"",project_id:t.project_id,...A}))}(t,e,s):async function(e,t,n){const r=_o(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n;{const n=ku(t.type),l=async()=>(await Au(e,t.project_id,{[n]:1}))[n][0],c=(new Date).toISOString(),d=e=>({id:e,type:t.type,title:t.title,summary:t.summary,body:t.body,...t.req_type?{req_type:t.req_type}:{},tags:{domains:a,level:i??""},ownership:{primary:null,additional:[]},relationships:{parents:t.parent_ids??[],children:[],related:[],verifies:[],verified_by:[]},links:[],...s?{fields:s}:{},metadata:{created_at:c,created_by:r,updated_at:c,updated_by:r}}),u=n=>e.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:t.project_id,p_type:t.type,p_title:t.title,p_data:n,p_user_id:r,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null});let p=await l(),m=d(p),{error:_}=await u(m);if(_&&(o=_)&&/^item_exists\b/.test(String(o.message??"").trim())&&(p=await l(),m=d(p),({error:_}=await u(m))),Ad("main",_),_)throw new Error(_.message);const f=i?Ku(i,await ap(e,t.project_id,i)):null,h=[];if(t.parent_ids&&t.parent_ids.length>0)for(const n of t.parent_ids){const{error:a}=await _p(()=>e.rpc("apply_link_change",{p_project_id:t.project_id,p_from_id:p,p_to_id:n,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"}));a&&(process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${n}: ${a.message}\n`),h.push({parent_id:n,message:a.message}))}const y=h.length>0?{link_warnings:h,warning:`${p} was created but could not be attached to ${h.map(e=>e.parent_id).join(", ")}. Repair: call atoms_link_items with type 'parent', from_id=${p}, to_id=<parent id>. Do not create the item again.`}:{};return await e.from("change_history").insert({item_id:p,project_id:t.project_id,changed_by:r,event_type:"created",old_data:null,new_data:m,actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===t.echo?Vs(ys({id:p,type:t.type,...f?{level_note:f}:{},...y})):Vs(ys({id:p,type:t.type,title:t.title,summary:t.summary??"",body:t.body??"",...t.req_type?{req_type:t.req_type}:{},domains:a,level:i??"",project_id:t.project_id,...f?{level_note:f}:{},...y}))}var o}(t,e,s))}catch(e){const t=Hs(e);return Bs(t||Ds(e))}}H(Lp,{createItemHandler:()=>Fp});var Wp=D({"src/tools/create-item.ts"(){ko(),Iu(),ey(),Ks(),pp(),Yu(),Oi(),$c(),gp(),gr(),Cd(),Ks()}});function Vp(e,t){const n=function(e){return`SG-${e}`}(t);return{id:e,outcome:"captured_as_change",change:{id:n,sg_number:t,status:"open"},message:`Captured as change ${n}, awaiting approval. This requirement stays at its approved revision until a human approver approves the change; no MCP tool can approve, dismiss, or apply it.`}}function Bp(e){return{id:e,outcome:"under_review",message:"This requirement is under change control. Your edit was submitted; if it changed the requirement's meaning it is now a change awaiting a human approver, otherwise it wrote through live. Reload the item to confirm. No MCP tool can approve, dismiss, or apply a change."}}var Jp,Qp=D({"src/core/change-control.ts"(){}});var Gp,Kp,Yp=D({"src/core/content-ids.ts"(){Jp={row:"r",column:"c",step:"st",param:"p"}}});function Zp(e,t){const n=Gp[0];if(null!==t&&e>=t)throw new Error(`${e} >= ${t}`);if(e.slice(-1)===n||t&&t.slice(-1)===n)throw new Error("trailing zero");if(t){let r=0;for(;(e[r]||n)===t[r];)r+=1;if(r>0)return t.slice(0,r)+Zp(e.slice(r),t.slice(r))}const r=e?Gp.indexOf(e[0]):0,a=null!==t?Gp.indexOf(t[0]):Gp.length;return a-r>1?Gp[Math.round(.5*(r+a))]:t&&t.length>1?t.slice(0,1):Gp[r]+Zp(e.slice(1),null)}function Xp(e){if(e>="a"&&e<="z")return e.charCodeAt(0)-"a".charCodeAt(0)+2;if(e>="A"&&e<="Z")return"Z".charCodeAt(0)-e.charCodeAt(0)+2;throw new Error(`invalid order key head: ${e}`)}function em(e){if(e.length!==Xp(e[0]))throw new Error(`invalid integer part of order key: ${e}`)}function tm(e){const t=Xp(e[0]);if(t>e.length)throw new Error(`invalid order key: ${e}`);return e.slice(0,t)}function nm(e){if(e===Kp)throw new Error(`invalid order key: ${e}`);const t=tm(e);if(e.slice(t.length).slice(-1)===Gp[0])throw new Error(`invalid order key: ${e}`)}function rm(e){em(e);const t=e[0],n=e.slice(1).split("");let r=!0;for(let e=n.length-1;r&&e>=0;e-=1){const t=Gp.indexOf(n[e])+1;t===Gp.length?n[e]=Gp[0]:(n[e]=Gp[t],r=!1)}if(r){if("Z"===t)return`a${Gp[0]}`;if("z"===t)return null;const e=String.fromCharCode(t.charCodeAt(0)+1);return e>"a"?n.push(Gp[0]):n.pop(),e+n.join("")}return t+n.join("")}function am(e,t){if(null!==e&&nm(e),null!==t&&nm(t),null!==e&&null!==t&&e>=t)throw new Error(`${e} >= ${t}`);if(null===e){if(null===t)return`a${Gp[0]}`;const e=tm(t),n=t.slice(e.length);if(e===Kp)return e+Zp("",n);if(e<t)return e;const r=function(e){em(e);const t=e[0],n=e.slice(1).split(""),r=Gp[Gp.length-1];let a=!0;for(let e=n.length-1;a&&e>=0;e-=1){const t=Gp.indexOf(n[e])-1;-1===t?n[e]=r:(n[e]=Gp[t],a=!1)}if(a){if("a"===t)return`Z${r}`;if("A"===t)return null;const e=String.fromCharCode(t.charCodeAt(0)-1);return e<"Z"?n.push(r):n.pop(),e+n.join("")}return t+n.join("")}(e);if(null===r)throw new Error("cannot decrement any more");return r}if(null===t){const t=tm(e),n=e.slice(t.length),r=rm(t);return null===r?t+Zp(n,null):r}const n=tm(e),r=e.slice(n.length),a=tm(t),i=t.slice(a.length);if(n===a)return n+Zp(r,i);const s=rm(n);if(null===s)throw new Error("cannot increment any more");return s<t?s:n+Zp(r,null)}function im(e,t,n){return am(t,null===t||null===n||t<n?n:function(e,t){let n=null;for(const r of e)r>t&&(null===n||r<n)&&(n=r);return n}(e,t))}var sm,om,lm=D({"src/core/order-key.ts"(){Yp(),Gp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Kp=`A${"0".repeat(26)}`}});function cm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dm(e,t){return e<t?-1:e>t?1:0}function um(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)&&e.every((e,n)=>um(e,t[n]));if(cm(e)&&cm(t)){const n=Object.keys(e).filter(t=>void 0!==e[t]),r=Object.keys(t).filter(e=>void 0!==t[e]);return n.length===r.length&&n.every(n=>um(e[n],t[n]))}return!1}function pm(e){return cm(e)&&"string"==typeof e.id?`id:${e.id}`:`json:${mm(e)}`}function mm(e){return Array.isArray(e)?`[${e.map(mm).join(",")}]`:cm(e)?`{${Object.keys(e).filter(t=>void 0!==e[t]).sort(dm).map(t=>`${JSON.stringify(t)}:${mm(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function _m(e,t,n,r={}){if(r.skip?.(e))return[];if(um(t,n))return[];if(function(e){const[t,n,r]=e;return 2===e.length&&"tags"===t&&"domains"===n||2===e.length&&"ownership"===t&&"additional"===n||2===e.length&&"relationships"===t||1===e.length&&("links"===t||"scoped_assets"===t)||3===e.length&&"rows"===t&&"traces_to"===r}(e)&&(Array.isArray(t)||Array.isArray(n)))return function(e,t,n){const r=Array.isArray(t)?t:[],a=Array.isArray(n)?n:[],i=new Set(r.map(pm)),s=new Set(a.map(pm)),o=[];for(const t of r)s.has(pm(t))||o.push({kind:"remove",path:[...e],value:t});for(const t of a)i.has(pm(t))||o.push({kind:"add",path:[...e],value:t});return o}(e,t,n);if(cm(t)&&cm(n)){const a=new Set([...Object.keys(t),...Object.keys(n)]),i=[];for(const s of[...a].sort(dm))0===e.length&&r.ignoreKeys?.has(s)||i.push(..._m([...e,s],t[s],n[s],r));return i}return[{kind:"set",path:[...e],base:void 0===t?null:t,value:void 0===n?null:n}]}function fm(e){const t={};for(const n of Object.keys(e))sm.has(n)||void 0===e[n]||(t[n]=e[n]);return t}function hm(e,t,n,r={}){const a=r.columns?"insert_column":"insert_row",i=r.columns?"move_column":"move_row",s=r.columns?"delete_column":"delete_row",o=function(e,t,n){if(0===n)return[];if(1===n)return[am(null,t)];{let e=am(null,t);const r=[e];for(let a=0;a<n-1;a+=1)e=am(e,t),r.push(e);return r}}(0,null,t.length),l=t.map((e,t)=>"string"==typeof e.order_key?e.order_key:o[t]),c=!0===r.implicitIds&&t.every(e=>"string"!=typeof e.id),d=t.map((e,t)=>"string"==typeof e.id?e.id:r.implicitIds?`p${t+1}`:""),u=new Map;d.forEach((e,t)=>{""===e||u.has(e)||u.set(e,t)});const p=new Set,m=n.map((t,n)=>{let r="string"==typeof t.id?t.id:"";return""===r&&c&&(r=`p${n+1}`),(""===r||p.has(r))&&(r=function(e){const t=function(){const e=globalThis.crypto;if(!e||"function"!=typeof e.getRandomValues)throw new Error("no secure random source");const t=new Uint8Array(8);return e.getRandomValues(t),t}();let n="";for(let e=0;e<t.length;e+=1)n+=t[e].toString(16).padStart(2,"0");return`${Jp[e]}_${n}`}(om[e])),p.add(r),r}),_=m.map(e=>u.get(e)??-1),f=_.flatMap((e,t)=>e>=0?[t]:[]),h=new Set(function(e){const t=[],n=new Array(e.length).fill(-1);for(let r=0;r<e.length;r+=1){let a=0,i=t.length;for(;a<i;){const n=a+i>>1;e[t[n]]<e[r]?a=n+1:i=n}a>0&&(n[r]=t[a-1]),t[a]=r}const r=[];for(let e=t.length?t[t.length-1]:-1;e>=0;e=n[e])r.push(e);return r.reverse()}(f.map(e=>_[e])).map(e=>f[e])),y=[],g=new Set(m);t.forEach((t,n)=>{""===d[n]||u.get(d[n])!==n||g.has(d[n])||y.push({kind:s,path:[e],base:t,row_id:d[n]})});const w=[...l],v=new Array(n.length).fill(null);for(let e=0;e<n.length;e+=1)h.has(e)&&(v[e]=l[_[e]]);for(let t=0;t<n.length;t+=1){if(null!==v[t])continue;const r=t>0?v[t-1]:null;let s=null;for(let e=t+1;e<n.length;e+=1)if(h.has(e)){s=v[e];break}const o=im(w,r,s);w.push(o),v[t]=o,_[t]<0?y.push({kind:a,path:[e],value:fm(n[t]),row_id:m[t],order_key:o}):y.push({kind:i,path:[e],base:l[_[t]],row_id:m[t],order_key:o})}for(let a=0;a<n.length;a+=1)_[a]<0||y.push(..._m([e,m[a]],fm(t[_[a]]),fm(n[a]),{skip:r.skip}));return y}var ym=D({"src/core/content-ops.ts"(){Yp(),lm(),sm=new Set(["id","order_key","created_seq"]),om={steps:"step",params:"param",rows:"row",columns:"column"}}}),gm={};async function wm(e){try{const n=await co();try{await wo(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const r=await kd(n,e.project_id);if(null===r)return Bs(cr());const a=function(e){return Array.isArray(e.updates)?e.updates.filter(e=>void 0!==e.asil_confirm_lower).map(e=>e.item_id):void 0!==e.asil_confirm_lower&&e.item_id?[e.item_id]:[]}(e);return!1===r&&a.length>0?Bs({status:"error",code:"forbidden",reason:"asil_lower_needs_person",message:(t=a[0]??"The item",`${t} ASIL not changed: lowering an ASIL needs a person. Ask them to review it in ATOMS. Nothing was saved.`),next_steps:["Tell the person that lowering an ASIL needs them, and ask them to review it in ATOMS."]}):await ur(r?"ops":"main",t=>"ops"===t?async function(e,t){const n=_o(),r=Array.isArray(t.updates);if(!r&&!t.item_id)return Bs(Ss("Provide either item_id (single) or updates[] (array form)."));const a=r?t.updates.map(e=>({itemId:e.item_id,patch:e})):[{itemId:t.item_id,patch:t}],i=!0===t.continue_on_error,s=function(e,t){let n=null;return{read:()=>(n??=(async()=>{const{data:n,error:r}=await e.from("metadata").select("domains, function_tags").eq("project_id",t).maybeSingle();if(r)throw new Error(`metadata read failed: ${r.message}`);return{domains:n?.domains??[],function_tags:n?.function_tags}})(),n)}}(e,t.project_id),o=[],l=[];for(const{itemId:n,patch:c}of a){void 0!==c.asil_confirm_lower&&l.push(Do(n));const a=await vm(e,t.project_id,n,c,s),d=Md(c.base_token??(r?t.base_token:void 0));if("entry"in a){o.push({itemId:n,tokens:d,intent:c.intent??t.intent??"edit",...a.entry});continue}const{message:u,path:p,notFound:m,long:_}=a.refusal;if(!r)return Bs(m?vs("Item",n):Ss(u,_?os:void 0));if(!i)return Bs(Ss(`Batch stopped at "${n}": ${u}. Nothing was saved.`,_?os:void 0));l.push(m?{op_id:"",status:"deleted",reason:"not_found",item_id:n,path:p,seq:null}:{op_id:"",status:"invalid",reason:"validation",item_id:n,path:p,seq:null,message:u})}const c=new Set(o.map(e=>e.itemId)).size>1?"bulk":"single",d=o.map(e=>({itemId:e.itemId,tokens:e.tokens,paths:e.paths,values:e.values})),{items:u,refusals:p}=await On({client:e,projectId:t.project_id,requests:d,mode:c}),m=[];for(const e of o){const t=u.get(e.itemId);t&&t.send&&e.paths.forEach((n,r)=>{const a=t.bases.get(qn(n));if(a)for(const t of bm(n,a.base,e.values[r])){const n={op_id:"",kind:t.kind,item_id:e.itemId,path:t.path};"value"in t&&(n.value=t.value),"base"in t&&(n.base=t.base,n.base_revision_id=a.base_revision_id,n.base_saves=a.base_saves),void 0!==t.row_id&&(n.row_id=t.row_id),void 0!==t.order_key&&(n.order_key=t.order_key),"apply_mine"===e.intent&&(n.intent="apply_mine"),m.push(n)}})}for(const e of m)e.op_id=t.idempotency_key?await Jn(Kn({userId:n,projectId:t.project_id,family:Xn("atoms_update_item"),key:t.idempotency_key,itemIdOrK:e.item_id??"",path:Td(e)})):Qn();let _={answers:[],results:[],notSent:[]};if(m.length>0&&(_=await Id(e,t.project_id,m,{mode:c}),void 0!==_.error&&0===_.results.length))throw _.error;const f=[...l,...p,..._.answers,...or(_.notSent)],h=new Map;for(const e of o)Array.isArray(e.steps)&&e.steps.forEach((e,t)=>{e?.id&&h.set(e.id,t+1)});const y=await $d({client:e,projectId:t.project_id,answers:f,ops:m,results:_.results,labels:{stepNumber:e=>h.get(e)}}),g=r?crypto.randomUUID():void 0;if(await Od(e,t.project_id,m,_.answers,"updated",{batch_id:g,reason:t.reason}),y.not_applied.length>0)return qd(y,r?{batch_id:g}:{id:t.item_id});const w=new Map;for(const e of[...y.applied]){if(!e.item_id)continue;const t=Rd(e.path),n=w.get(e.item_id)??[];t&&!n.includes(t)&&n.push(t),w.set(e.item_id,n)}const v=new Map;for(const e of y.captured)e.item_id&&v.set(e.item_id,Ed(e));if(r){const e=o.map(e=>v.has(e.itemId)?null!==v.get(e.itemId)?Vp(e.itemId,v.get(e.itemId)):Bp(e.itemId):{id:e.itemId,updated_fields:w.get(e.itemId)??[]});return Vs(ys({batch_id:g,updated:e.length,results:!1===t.echo?void 0:e,errors:[],...Bn(y)}))}const b=t.item_id;if(v.has(b)){const e=v.get(b);return Vs(ys(null!=e?Vp(b,e):Bp(b)))}const j=w.get(b)??[];if(!1===t.echo)return Vs(ys({id:b,updated_fields:j,...Bn(y)}));const k=(await An(e,t.project_id,[b])).get(b),S=k?.fields_snapshot??{},A=S.data??{};return Vs(ys({id:b,type:S.type??o[0]?.type,title:S.title??A.title??"",summary:A.summary??"",body:A.body??"",domains:A.tags?.domains??[],level:A.tags?.level??"",...A.req_type?{req_type:A.req_type}:{},updated_fields:j,...k?{base_token:await vn(k,"core")}:{},...Bn(y)}))}(n,e):async function(e,t){{const n=_o(),r=async(r,a,i,s)=>{const o=await dd(e,t.project_id,r);if(!o)return{updated_fields:[],error:`Item "${r}" not found`};const l="approved"===o.approval_state;if(void 0!==a.status&&Wl(o))return{updated_fields:[],error:Vl(r)};if(void 0!==a.status&&Bl(o,a.status))return{updated_fields:[],error:Jl(r)};void 0!==a.title&&(a.title=Ls(a.title)),void 0!==a.body&&(a.body=Ls(a.body)),void 0!==a.summary&&(a.summary=Ls(a.summary)),void 0!==a.level&&(a.level=Ls(a.level)),void 0!==a.domains&&(a.domains=a.domains.map(e=>Ls(e))),void 0!==a.steps&&(a.steps=Pl(a.steps,e=>Ls(e))),void 0!==a.params&&(a.params=Ll(Pl(a.params,e=>Ls(e)),o.data.params));const c=void 0!==a.domains?a.domains.map(hs).filter(e=>e.length>0):void 0,d=void 0!==a.level?await rp(e,t.project_id,a.level):void 0;if(void 0!==c&&c.length>0){const{data:n,error:r}=await e.from("metadata").select("domains, function_tags").eq("project_id",t.project_id).maybeSingle();if(r)throw new Error(`metadata read failed: ${r.message}`);const a=n?.domains??[],i=Ai(c,Si(n?.function_tags),hs);if(i.length>0)return{updated_fields:[],error:Ii(i)};if(a.length>0){const e=new Set(a.map(hs).filter(e=>e.length>0)),t=c.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const u={...o.data},p={...o.data},m=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==a.title&&_(o.data.title,a.title)&&(p.title=a.title,m.push("title")),void 0!==a.body&&_(o.data.body,a.body)&&(p.body=a.body,m.push("body")),void 0!==a.summary&&_(o.data.summary,a.summary)&&(p.summary=a.summary,m.push("summary")),void 0!==c&&_(o.data.tags?.domains??[],c)&&(p.tags={...p.tags,domains:c},m.push("domains")),void 0!==d&&_(o.data.tags?.level,d)&&(p.tags={...p.tags,level:d},m.push("level")),void 0!==a.status&&_(o.data.status,a.status)&&(p.status=a.status,m.push("status")),void 0!==a.req_type){const e=kc(a.req_type,o.type);if(e)return{updated_fields:[],error:e};_(o.data.req_type,a.req_type)&&(p.req_type=a.req_type,m.push("req_type"))}if(void 0!==a.steps&&_(o.data.steps,a.steps)&&(p.steps=a.steps,m.push("steps")),void 0!==a.params&&_(o.data.params,a.params)&&(p.params=a.params,m.push("params")),void 0!==a.fields&&Object.keys(a.fields).length>0){const{getProjectFields:n,validateProjectFieldValuesForWrite:r,canonicalizeFieldKeys:i}=await Promise.resolve().then(()=>(Np(),Sp)),s=await n(e,t.project_id),l=await r(e,t.project_id,s,a.fields,o.data.fields);if(l.error)return{updated_fields:[],error:l.error};const c=i(s,o.data.fields??{});for(const[e,t]of Object.entries({...i(s,a.fields),...l.fields??{}}))""===t?delete c[e]:c[e]=t;_(o.data.fields??{},c)&&(p.fields=c,m.push("fields"))}if(0===m.length)return{updated_fields:[],updatedData:o.data,itemType:o.type};p.metadata={...p.metadata,updated_at:(new Date).toISOString(),updated_by:n};const f=a.title??o.title,{data:h,error:y}=await e.rpc("save_item_with_revision",{p_item_id:r,p_project_id:t.project_id,p_type:o.type,p_title:f,p_data:p,p_user_id:n,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:a.expected_updated_at??o.updated_at});if(Ad("main",y),y)return{updated_fields:[],error:y};if(!h)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=m.includes("level")&&d?Ku(d,await ap(e,t.project_id,d)):null,w={item_id:r,project_id:t.project_id,changed_by:n,event_type:"updated",old_data:u,new_data:p,actor:Zh(),session_id:Yh()};if(i&&(w.batch_id=i),s&&(w.reason=s),await e.from("change_history").insert(w).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),l&&function(e){return e.some(e=>"title"===e||"body"===e||"type"===e)}(m)){const n=await async function(e,t,n){const{data:r,error:a}=await e.from("item_suggestions").select("sg_number").eq("project_id",t).eq("item_id",n).eq("status","open").maybeSingle();return a||!r?null:"number"==typeof r.sg_number?r.sg_number:null}(e,t.project_id,r);return null!==n?{updated_fields:m,updatedData:p,itemType:o.type,capturedSg:n}:{updated_fields:m,updatedData:p,itemType:o.type,capturedUnknown:!0}}return{updated_fields:m,updatedData:p,itemType:o.type,...g?{levelNote:g}:{}}};if(t.updates&&Array.isArray(t.updates)){const e=crypto.randomUUID(),n=!0===t.continue_on_error,a=[],i=[];for(const s of t.updates){const{updated_fields:o,capturedSg:l,capturedUnknown:c,error:d,levelNote:u}=await r(s.item_id,s,e,t.reason);if(d){if(Us(d))return Bs(Ds(d));if(!n){const e=d instanceof Error?d.message:String("object"==typeof d&&d&&"message"in d?d.message??"":d);return Bs(Ss(`Batch stopped at "${s.item_id}": ${e}. ${a.length} item(s) already updated.`,e.includes("Function-flagged tag")?os:void 0))}i.push({item_id:s.item_id,error:String(d)})}else void 0!==l?a.push(Vp(s.item_id,l)):c?a.push(Bp(s.item_id)):a.push({id:s.item_id,updated_fields:o,...u?{level_note:u}:{}})}const s=[...new Set(a.flatMap(e=>"level_note"in e&&e.level_note?[e.level_note]:[]))];return Vs(ys({batch_id:e,updated:a.length,results:!1===t.echo?void 0:a,...!1===t.echo&&s.length>0?{level_notes:s}:{},errors:i}))}if(!t.item_id)return Bs(Ss("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:a,updatedData:i,itemType:s,capturedSg:o,capturedUnknown:l,error:c,levelNote:d}=await r(t.item_id,{title:t.title,body:t.body,summary:t.summary,domains:t.domains,level:t.level,status:t.status,req_type:t.req_type,fields:t.fields,steps:t.steps,params:t.params,expected_updated_at:t.expected_updated_at},void 0,t.reason);if(c){const e=c instanceof Error?c.message:String("object"==typeof c&&c&&"message"in c?c.message??"":c);return e.includes("not found")?Bs(vs("Item",t.item_id)):e.includes("Unknown domain")||e.includes("Unknown field")||e.includes("Function-flagged tag")||e.includes("req_type")||function(e){return e.includes($l)||e.includes(El)}(e)?Bs(Ss(e,e.includes("Function-flagged tag")?os:void 0)):Os(e)||Us(c)?Bs(Ds(c)):Bs(Ps(e))}if(void 0!==o)return Vs(ys(Vp(t.item_id,o)));if(l)return Vs(ys(Bp(t.item_id)));if(!1===t.echo)return Vs(ys({id:t.item_id,updated_fields:a,...d?{level_note:d}:{}}));const u=i??{};return Vs(ys({id:t.item_id,type:s,title:u.title??"",summary:u.summary??"",body:u.body??"",domains:u.tags?.domains??[],level:u.tags?.level??"",...u.req_type?{req_type:u.req_type}:{},updated_fields:a,...d?{level_note:d}:{}}))}}(n,e))}catch(e){const t=Hs(e);return Bs(t||Ds(e))}var t}async function vm(e,t,n,r,a){const i=await dd(e,t,n);if(!i)return{refusal:{message:`Item "${n}" not found`,path:null,notFound:!0}};if(void 0!==r.status&&Wl(i))return{refusal:{message:Vl(n),path:["status"]}};if(void 0!==r.status&&Bl(i,r.status))return{refusal:{message:Jl(n),path:["status"]}};const s=[],o=[],l=(e,t)=>{s.push(e),o.push(t)};if(void 0!==r.title&&l(["title"],Ls(r.title)),void 0!==r.summary&&l(["summary"],Ls(r.summary)),void 0!==r.body&&l(["body"],Ls(r.body)),void 0!==r.req_type){const e=kc(r.req_type,i.type);if(e)return{refusal:{message:e,path:["req_type"]}};l(["req_type"],r.req_type)}if(void 0!==r.status&&l(["status"],r.status),void 0!==r.level&&l(["tags","level"],await rp(e,t,Ls(r.level))),void 0!==r.domains){const e=r.domains.map(e=>hs(Ls(e))).filter(e=>e.length>0);if(e.length>0){const t=await a.read(),n=Ai(e,Si(t.function_tags),hs);if(n.length>0)return{refusal:{message:Ii(n),path:["tags","domains"],long:!0}};if(t.domains.length>0){const n=new Set(t.domains.map(hs).filter(e=>e.length>0)),r=e.filter(e=>!n.has(e));if(r.length>0)return{refusal:{message:`Unknown domains: ${r.join(", ")}`,path:["tags","domains"]}}}}l(["tags","domains"],e)}if(void 0!==r.fields&&Object.keys(r.fields).length>0){const{getProjectFields:n,validateProjectFieldValuesForWrite:a,canonicalizeFieldKeys:s}=await Promise.resolve().then(()=>(Np(),Sp)),o=await n(e,t),c=await a(e,t,o,r.fields,i.data.fields);if(c.error)return{refusal:{message:c.error,path:["fields"]}};for(const[e,t]of Object.entries({...s(o,r.fields),...c.fields??{}}))l(["fields",e],""===t?null:t)}return void 0!==r.steps&&l(["steps"],Pl(r.steps,e=>Ls(e))),void 0!==r.params&&l(["params"],Pl(r.params,e=>Ls(e))),{entry:{paths:s,values:o,type:i.type,steps:i.data.steps}}}function bm(e,t,n){const r=e=>Array.isArray(e)?e:[];return 1===e.length&&"steps"===e[0]?function(e,t){return hm("steps",e??[],t??[])}(r(t),r(n)):1===e.length&&"params"===e[0]?function(e,t){return hm("params",e??[],t??[],{implicitIds:!0})}(r(t),r(Ll(n,t))):_m([...e],void 0===t?null:t,n)}H(gm,{updateItemHandler:()=>wm});var jm,km=D({"src/tools/update-item.ts"(){Lo(),ko(),hd(),ey(),$c(),Ql(),Ks(),pp(),Yu(),Qp(),Oi(),gr(),ym(),Cd(),Ks()}}),Sm={};async function Am(e){try{const t=await co();_o();try{await wo(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const n=await kd(t,e.project_id);if(null===n)return Bs(cr());const r=await async function(e,t,n){const{data:r,error:a}=await e.from("items").select("*").eq("id",n).eq("project_id",t).maybeSingle();if(a)throw new Error(a.message);return r}(t,e.project_id,e.item_id);if(!r)return Bs(vs("Item",e.item_id));if(r.deleted_at)return Bs(Ss(`Item ${e.item_id} is already deleted`));if(Lu(jm)){const t={tool:jm,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const n=Fu(t);return Vs(ys({status:"confirmation_required",preview:{id:e.item_id,title:r.title,type:r.type,would_soft_delete:!0},confirmation_token:n.token,expires_at:n.expires_at,expires_in_seconds:n.expires_in_seconds,message:`Re-call atoms_delete_item with the same project_id, item_id, and confirmation_token within ${n.expires_in_seconds}s to execute.`}))}const n=Wu(e.confirmation_token,t);if(!n.valid)return Bs(Ss(`confirmation_token rejected: ${n.reason}`))}const a={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.`};return await ur(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:Qn(),kind:"trash_item",item_id:t.item_id,path:[]}],a=await Id(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await $d({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await Od(e,t.project_id,r,a.answers,"deleted"),i.not_applied.length>0?qd(i,{id:t.item_id}):Vs(ys({...n,...Bn(i)}))}(t,e,a):async function(e,t,n,r){const a=_o(),{error:i}=await e.rpc("soft_delete_item_with_revision",{p_item_id:t.item_id,p_project_id:t.project_id,p_user_id:a,p_expected_updated_at:n.updated_at,p_event_source:"mcp",p_actor:Zh(),p_session_id:Yh()});if(Ad("main",i),i)throw new Error(i.message);const s=Dr(n.data);if(s){const n=await dd(e,t.project_id,s);if(n){const{revoked:r,parentProps:i}=Hr(n.data);if(r){const r={...n.data,analysis_props:i},{error:s}=await e.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:t.project_id,p_type:n.type,p_title:n.title,p_data:r,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at});s&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${n.id}': ${s.message}\n`)}}}return Vs(ys(r))}(t,e,r,a))}catch(e){const t=Hs(e);return Bs(t||Ds(e))}}H(Sm,{deleteItemHandler:()=>Am});var Im=D({"src/tools/delete-item.ts"(){ko(),hd(),ey(),za(),Qu(),Ks(),gr(),Cd(),Ks(),jm="atoms_delete_item"}}),xm={};async function $m(e){try{const t=await co(),n=_o();try{await wo(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const r=await kd(t,e.project_id);if(null===r)return Bs(cr());const{data:a,error:i}=await t.from("items").select("*").eq("id",e.item_id).eq("project_id",e.project_id).maybeSingle();if(i)throw new Error(i.message);if(!a)return Bs(vs("Item",e.item_id));if(!a.deleted_at)return Bs(ws(`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{data:s,error:o}=await t.rpc("item_trash_info",{p_project_id:e.project_id,p_item_id:e.item_id});if(o)throw o;const l={...s,item_id:e.item_id,title:a.title};if(!1===l.agent_may_restore)return Bs(es());if(!0!==e.confirm)return Vs(function(e){const t=e.days_in_trash??0;return{status:"needs_confirmation",message:`${e.item_id} "${e.title??""}" is in Trash. ${ts(e)} moved it there on ${ns(e)} (${n=t,n<=0?"today":1===n?"1 day ago":`${n} days ago`}). Tell the user this and ask them to confirm before restoring it.`,next_steps:[...Ki],id:e.item_id,title:e.title??"",restored:!1,trashed_by:ts(e),trashed_at:e.deleted_at??null,days_in_trash:t};var n}(l));const c={id:e.item_id,title:a.title,type:a.type,restored:!0,message:rs(l,n)};return await ur(r?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:Qn(),kind:"restore_item",item_id:t.item_id,path:[]}],a=await Id(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await $d({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await Od(e,t.project_id,r,a.answers,"restored"),i.not_applied.length>0?qd(i,{id:t.item_id}):Vs(ys({...n,...Bn(i)}))}(t,e,c):async function(e,t,n,r){const a=_o(),{error:i}=await e.rpc("save_item_with_revision",{p_item_id:t.item_id,p_project_id:t.project_id,p_type:n.type,p_title:n.title,p_data:n.data,p_user_id:a,p_event_source:"restore",p_event_session_id:Yh()??null,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:n.updated_at});if(Ad("main",i),i)throw i;const{error:s}=await e.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:t.project_id,p_item_id:t.item_id});if(s)throw new Error(`Relationship repair failed: ${s.message}`);const o=Dr(n.data);if(o){const n=await dd(e,t.project_id,o);if(n){const{revoked:r,parentProps:i}=Hr(n.data);if(r){const r={...n.data,analysis_props:i},{error:s}=await e.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:t.project_id,p_type:n.type,p_title:n.title,p_data:r,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at});s&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${n.id}': ${s.message}\n`)}}}return await e.from("change_history").insert({item_id:t.item_id,project_id:t.project_id,changed_by:a,event_type:"restored",old_data:null,new_data:n.data,actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Vs(ys(r))}(t,e,a,c))}catch(e){const t=Hs(e);return Bs(t||Ds(e))}}H(xm,{restoreItemHandler:()=>$m});var Em,qm,Om,Rm=D({"src/tools/restore-item.ts"(){ko(),hd(),ey(),za(),ms(),Ks(),gr(),Cd(),Ks()}}),Tm={};function Mm(e,t,n){const[r,a]="affects"===n?[e,t]:[t,e];return r.startsWith(Em)&&a.startsWith(qm)?null:`affects/affected_by links a security risk analysis row (${Em}n) to an ISO 14971 risk row (${qm}n) only: "${e}" -> "${t}" is not that pair.`}async function zm(e){try{const t=await co(),n=_o();try{await wo(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}let r;const a=async()=>void 0===r?r=await kd(t,e.project_id):r,i=async(r,a,i)=>{const s=await dd(t,e.project_id,r.from_id);if(!s)throw new Error(`Item "${r.from_id}" not found`);const o=await dd(t,e.project_id,r.to_id);if(!o)throw new Error(`Item "${r.to_id}" not found`);const{error:l}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r.from_id,p_to_id:r.to_id,p_type:r.type,p_action:r.action,p_user_id:n,p_event_source:"mcp",p_expected_from_updated_at:r.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:r.expected_to_updated_at??o.updated_at});if(Ad("main",l),l)throw new Error(l.message);if("affects"===r.type||"affected_by"===r.type)for(const r of[s,o]){const a=Dr(r.data);if(!a)continue;const i=await dd(t,e.project_id,a);if(!i)continue;const{revoked:s,parentProps:o}=Hr(i.data);if(!s)continue;const l={...i.data,analysis_props:o},{error:c}=await t.rpc("save_item_with_revision",{p_item_id:i.id,p_project_id:e.project_id,p_type:i.type,p_title:i.title,p_data:l,p_user_id:n,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});c&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${i.id}': ${c.message}\n`)}const c={item_id:r.from_id,project_id:e.project_id,changed_by:n,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:Zh(),session_id:Yh()};a&&(c.batch_id=a),i&&(c.reason=i),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 Bs(Ss(`Self-reference in batch: "${t.from_id}"`));if("affects"===t.type||"affected_by"===t.type){const e=Mm(t.from_id,t.to_id,t.type);if(e)return Bs(Ss(e))}}const n=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],r=await gc(n,n=>t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",n)),s=new Set(r.map(e=>e.id)),o=n.filter(e=>!s.has(e));if(o.length>0)return Bs(vs("Items",o.join(", ")));const l=await mc(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id).eq("type","parent"),nc),c=new Map;for(const e of l)"parent"===e.type&&(c.has(e.from_id)||c.set(e.from_id,new Set),c.get(e.from_id).add(e.to_id));for(const t of e.operations){if("parent"!==t.type&&"child"!==t.type)continue;const[e,n]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?c.get(e)?.delete(n):(c.has(e)||c.set(e,new Set),c.get(e).add(n))}const d=0,u=1,p=2,m=new Map,_=new Set;for(const[e,t]of c){_.add(e);for(const e of t)_.add(e)}const f=e=>{if((m.get(e)??d)!==d)return null;const t=[],n=[],r=e=>{m.set(e,u),n.push(e),t.push({node:e,parents:[...c.get(e)??[]],idx:0})};for(r(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){m.set(e.node,p),n.pop(),t.pop();continue}const a=e.parents[e.idx];e.idx++;const i=m.get(a)??d;if(i===u){const e=n.indexOf(a);return[...n.slice(e),a]}i!==p&&r(a)}return null};for(const e of _){const t=f(e);if(t)return Bs(Ss(`Batch would create a cycle: ${t.join(" -> ")}. No changes applied.`))}const h=e.operations,y=await a();return null===y?Bs(cr()):await ur(y?"ops":"main",async n=>{if("ops"===n)return Cm(t,e,h,!0);const r=crypto.randomUUID(),a=[...h.filter(e=>"remove"===e.action),...h.filter(e=>"add"===e.action)],s=[],o=e=>`${e.action} ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`;for(const t of a){try{await i(t,r,e.reason)}catch(e){if(dr("main",e))throw e;const n=Ds(e);return Bs({...n,message:`${n.message}\n\nThis batch is not atomic: its operations are applied one at a time. ${s.length} of ${a.length} operation(s) committed before this one failed and were NOT rolled back (batch ${r}). Committed: ${s.length?s.map(o).join("; "):"none"}. Failed: ${o(t)}.`,next_steps:[`Do not re-send the whole batch: the ${s.length} committed operation(s) would be applied again.`,"Reconcile from the committed list, then retry only the failed and any remaining operations.",...n.next_steps??[]]})}s.push(t)}return Vs(ys({batch_id:r,processed:h.length,operations:!1===e.echo?void 0:h}))})}if(!(e.from_id&&e.to_id&&e.type&&e.action))return Bs(Ss("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."));if(e.from_id===e.to_id)return Bs(Ss("Cannot create a relationship between an item and itself"));if("affects"===e.type||"affected_by"===e.type){const t=Mm(e.from_id,e.to_id,e.type);if(t)return Bs(Ss(t))}const s={action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type,expected_from_updated_at:e.expected_from_updated_at,expected_to_updated_at:e.expected_to_updated_at},o=await a();return null===o?Bs(cr()):await ur(o?"ops":"main",async n=>"ops"===n?Cm(t,e,[s],!1):(await i(s,void 0,e.reason),!1===e.echo?Vs(ys({action:s.action,from_id:s.from_id,to_id:s.to_id})):Vs(ys({action:s.action,type:s.type,from_id:s.from_id,to_id:s.to_id,message:`Relationship ${"add"===s.action?"added":"removed"}: ${s.from_id} --[${s.type}]--\x3e ${s.to_id}`}))))}catch(e){const t=Hs(e);return Bs(t||Ds(e))}}async function Cm(e,t,n,r){const a=_o(),i=[];for(const e of n){const n={op_id:"",kind:e.action,item_id:e.from_id,path:["relationships",Om[e.type]],value:e.to_id};n.op_id=t.idempotency_key?await Jn(Kn({userId:a,projectId:t.project_id,family:Xn("atoms_link_items"),key:t.idempotency_key,itemIdOrK:e.from_id,path:Td(n)})):Qn(),i.push(n)}const s=await Id(e,t.project_id,i);if(void 0!==s.error&&0===s.results.length)throw s.error;const o=await $d({client:e,projectId:t.project_id,answers:[...s.answers,...or(s.notSent)],ops:i,results:s.results}),l=r?crypto.randomUUID():void 0;if(await Od(e,t.project_id,i,s.answers,"updated",{batch_id:l,reason:t.reason}),o.not_applied.length>0)return qd(o,r?{batch_id:l}:{});if(r)return Vs(ys({batch_id:l,processed:n.length,operations:!1===t.echo?void 0:n,...Bn(o)}));const c=n[0];return!1===t.echo?Vs(ys({action:c.action,from_id:c.from_id,to_id:c.to_id,...Bn(o)})):Vs(ys({action:c.action,type:c.type,from_id:c.from_id,to_id:c.to_id,message:`Relationship ${"add"===c.action?"added":"removed"}: ${c.from_id} --[${c.type}]--\x3e ${c.to_id}`,...Bn(o)}))}H(Tm,{linkItemsHandler:()=>zm});var Dm,Hm,Um=D({"src/tools/link-items.ts"(){ko(),hd(),jc(),ey(),Oi(),za(),Ks(),gr(),Cd(),Ks(),Em=`${ua.security_tir57}-`,qm=`${ua.hazard_iso14971}-`,Om={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",affects:"affects",affected_by:"affected_by"}}}),Pm=D({"src/core/bulk-parent-links.ts"(){}}),Nm={};function Lm(e){return new Set(["22023","23503","23505","23514"]).has(e.code??"")}function Fm(e,t){return e.items.length>t?Bs(Ss(`Maximum ${t} items per call (received ${e.items.length}). Split into multiple calls.`)):null}async function Wm(e){try{if(!e.items||0===e.items.length)return Bs(Ss("items array must contain at least 1 item"));const t=Fm(e,Dm);if(t)return t;const n=await co();try{await wo(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const r=await kd(n,e.project_id);if(null===r)return Bs(cr());if(!r){const t=Fm(e,Hm);if(t)return t}const a=await async function(e,t,n){const{data:r,error:a}=await e.from("metadata").select("domains, function_tags").eq("project_id",t).maybeSingle();if(a)throw new Error(`metadata read failed: ${a.message}`);const i=r?.domains??[],s=Si(r?.function_tags),o=i.length>0?new Set(i.map(hs).filter(e=>e.length>0)):null,l=Bu(i.map(hs).filter(e=>e.length>0).sort()),c=[],d=new Set,u={};for(let e=0;e<n.length;e++){const t=n[e];u[t.type]=(u[t.type]??0)+1;const r=(t.domains??[]).map(hs).filter(e=>e.length>0);if(0===r.length)continue;const a=Ai(r,s,hs);if(a.length>0){d.add(e),c.push({index:e,title:t.title,error:Ii(a)});continue}if(!o)continue;const l=r.filter(e=>!o.has(e));l.length>0&&(d.add(e),c.push({index:e,title:t.title,error:`Unknown domain${l.length>1?"s":""}: ${l.join(", ")}. Registered: ${i.join(", ")}.`}))}return{registeredDomains:i,registeredDomainHash:l,invalidDomainIndexes:d,errors:c,typeBreakdown:u}}(n,e.project_id,e.items);if(Lu("atoms_bulk_import")){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:Bu({items:e.items,registered_domain_hash:a.registeredDomainHash})};if(!e.confirmation_token){const n=Fu(t);return Vs(ys({status:"confirmation_required",preview:{total_items:e.items.length,by_type:a.typeBreakdown,sample_titles:e.items.slice(0,5).map(e=>e.title),would_fail:a.errors.length>0,errors:a.errors,registered_domain_hash:a.registeredDomainHash},confirmation_token:n.token,expires_at:n.expires_at,expires_in_seconds:n.expires_in_seconds,message:`Re-call atoms_bulk_import with the same project_id, items array, and confirmation_token within ${n.expires_in_seconds}s to execute. Changing items or project domains will invalidate the token.`}))}const n=Wu(e.confirmation_token,t);if(!n.valid)return Bs(Ss(`confirmation_token rejected: ${n.reason}`))}return await ur(r?"ops":"main",t=>"ops"===t?async function(e,t,n){const r=_o(),a=t.idempotency_key,i=Xn("atoms_bulk_import"),s=t.items.some(e=>void 0!==e.level)?await ep(e,t.project_id):[],o=t.items.map((e,t)=>({input:e,index:t})).filter(({index:e})=>!n.invalidDomainIndexes.has(e)).map(({input:e,index:t})=>{const n=(e.domains??[]).map(hs).filter(e=>e.length>0),r=void 0!==e.level?Gu(e.level,hs(e.level),s,Xu):void 0;return{input:e,index:t,domains:n,level:r,content:nr({type:e.type,title:e.title,body:e.body,summary:e.summary,domains:n,level:r,parent_ids:e.parent_id?[e.parent_id]:[]})}}),l=er(o.map(e=>e.content)),c=[];for(let e=0;e<o.length;e+=1)c.push(await Jn(a?Kn({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:o[e].index,path:[]}):Gn({userId:r,projectId:t.project_id,content:o[e].content,k:l[e],sessionId:Yh()})));const d=await mr(e,t.project_id,c),u=[],p=[];o.forEach((e,t)=>{const n=d.get(c[t]);n&&("applied"===n.status||"noop"===n.status)&&n.item_id?u.push({id:n.item_id,title:e.input.title,type:e.input.type,replayed:!0}):p.push({v:e,createId:c[t]})});const m=[...n.errors],_=[],f=new Map;if(p.length>0){const n={};for(const{v:e}of p){const t=ku(e.input.type);n[t]=(n[t]??0)+1}const s=Su(await Au(e,t.project_id,n));for(const{v:e,createId:n}of p){const o=s(ku(e.input.type));f.set(o,{title:e.input.title,type:e.input.type});const l={summary:e.input.summary,body:e.input.body,tags:{domains:e.domains,level:e.level??""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[]},links:[]};_.push({op_id:n,kind:"create_item",item_id:o,path:[],value:{type:e.input.type,title:e.input.title,data:l}}),e.input.parent_id&&_.push({op_id:a?await Jn(Kn({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:e.index,path:["relationships","parents","add",e.input.parent_id]})):Qn(),kind:"add",item_id:o,path:["relationships","parents"],value:e.input.parent_id})}}let h={answers:[],results:[],notSent:[]};if(_.length>0&&(h=await Id(e,t.project_id,_,{mode:"bulk"}),void 0!==h.error&&0===h.results.length))throw h.error;const y=[...await _r(e,t.project_id,h.answers),...or(h.notSent)],g=await $d({client:e,projectId:t.project_id,answers:y,ops:_,results:h.results,relooked:!0});await Od(e,t.project_id,_,y,"created");const w=[...u];for(const e of y){if(!e.item_id||!e.path||0!==e.path.length)continue;if("applied"!==e.status&&"noop"!==e.status)continue;const t=f.get(e.item_id);t&&w.push({id:e.item_id,title:t.title,type:t.type,...e.replayed?{replayed:!0}:{}})}const v=w.length>0&&w.every(e=>e.replayed),b={created:w.length,items:w,errors:m,project_id:t.project_id,...h.chunks?{chunks:h.chunks}:{},...void 0!==h.error?{error:Ds(h.error).message}:{},...v?{replayed:!0,message:Yt}:{}};return g.not_applied.length>0?qd(w.length>0&&0===g.applied.length?{...g,applied:w.map(e=>({item_id:e.id,path:[],status:"applied",seq:null,replayed:!0}))}:g,b):Vs(ys({...b,...Bn(g)}))}(n,e,a):async function(e,t,n){const r=_o();{const a=(new Date).toISOString(),i=Yh(),s=[],o=[...n.errors],l=[],c=t.items.map((e,t)=>({input:e,index:t})).filter(({index:e})=>!n.invalidDomainIndexes.has(e)),d={};for(const{input:e}of c){const t=ku(e.type);d[t]=(d[t]??0)+1}let u=null,p=null;try{u=Su(await Au(e,t.project_id,d))}catch(e){p=(e instanceof Error?e.message:String(e)).replace(/^ID generation failed: /,"")}const m=async e=>{if(!u)throw new Error(p??"no id was reserved");return u(ku(e))},_=t.items.some(e=>void 0!==e.level)?await ep(e,t.project_id):[];for(let e=0;e<t.items.length;e++){const r=t.items[e];if(n.invalidDomainIndexes.has(e))continue;const a=(r.domains??[]).map(hs).filter(e=>e.length>0),i=void 0!==r.level?Gu(r.level,hs(r.level),_,Xu):void 0;try{const t=await m(r.type);l.push({itemId:t,input:r,sanitizedDomains:a,sanitizedLevel:i,index:e})}catch(t){o.push({index:e,title:r.title,error:`ID generation failed: ${t instanceof Error?t.message:String(t)}`})}}if(0===l.length)return Vs(ys({created:0,items:[],errors:o}));const f=[],h=new Map;for(const{itemId:e,input:n,sanitizedDomains:i,sanitizedLevel:s}of l){const o={id:e,type:n.type,title:n.title,summary:n.summary,body:n.body,tags:{domains:i,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:n.parent_id?[n.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:a,created_by:r,updated_at:a,updated_by:r}};h.set(e,o),f.push({id:e,project_id:t.project_id,type:n.type,title:n.title,data:o,created_by:r,updated_by:r})}const y=f.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:g}=await e.rpc("bulk_save_items_with_revisions",{p_project_id:t.project_id,p_items:y,p_user_id:r,p_event_source:"mcp"});if(Ad("main",g),g&&Lm(g))for(const{itemId:n,input:a,index:c}of l){const l=f.find(e=>e.id===n);if(!l)continue;const{error:d}=await e.rpc("save_item_with_revision",{p_item_id:l.id,p_project_id:t.project_id,p_type:l.type,p_title:l.title,p_data:l.data,p_user_id:r,p_event_source:"mcp",p_event_session_id:i,p_diff_summary:null});d?o.push({index:c,title:a.title,error:d.message}):s.push({id:n,title:a.title,type:a.type})}else{if(g)throw g;for(const{itemId:e,input:t}of l)s.push({id:e,title:t.title,type:t.type})}const w=l.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:e,input:n})=>({from_id:e,to_id:n.parent_id,type:"parent",project_id:t.project_id}));await async function(e){for(const t of e.links){const{error:n}=await e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:t.from,p_to_id:t.to,p_type:"parent",p_action:"add",p_user_id:e.userId,p_event_source:"mcp"});n&&e.warn(`bulk parent link sync failed for ${t.to}: ${n.message??"unknown error"}`)}}({client:e,projectId:t.project_id,links:w.map(e=>({from:e.from_id,to:e.to_id})),userId:r,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}),s.length>0&&await async function(e){try{const{data:t,error:n}=await e.client.rpc("repair_project_link_rows_unless_busy",{p_project_id:e.projectId});n?e.warn(`link repair after the import failed: ${n.message??"unknown error"}`):null==t&&e.warn("link repair after the import skipped: the project is being restored, moved to the Trash or relinked")}catch(t){e.warn(`link repair after the import failed: ${t instanceof Error?t.message:String(t)}`)}}({client:e,projectId:t.project_id,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const v=s.map(e=>({item_id:e.id,project_id:t.project_id,changed_by:r,event_type:"created",old_data:null,new_data:h.get(e.id)??null,actor:Zh(),session_id:i}));v.length>0&&await e.from("change_history").insert(v).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const b=new Set(s.map(e=>e.id)),j=new Set(l.filter(({itemId:e,sanitizedLevel:t})=>t&&b.has(e)).map(({sanitizedLevel:e})=>e)),k=[];for(const n of j){const r=Ku(n,await ap(e,t.project_id,n));r&&k.push(r)}return Vs(ys({created:s.length,items:s,errors:o.length>0?o:[],project_id:t.project_id,...k.length>0?{level_notes:k}:{}}))}}(n,e,a))}catch(e){const t=Hs(e);return Bs(t||Ds(e))}}H(Nm,{BULK_IMPORT_MAIN_MAX:()=>Hm,BULK_IMPORT_MAX:()=>Dm,bulkImportHandler:()=>Wm,canRetryBulkImportPerItem:()=>Lm});var Vm=D({"src/tools/bulk-import.ts"(){ko(),Iu(),ey(),Qu(),Ks(),Pm(),pp(),Yu(),Oi(),gr(),Cd(),Ks(),Dm=500,Hm=100}}),Bm={};async function Jm(e){const t=_o(),n=e.idempotencyKey??e.requestId??crypto.randomUUID(),r=await Promise.all(e.entries.map(e=>async function(e){return pn(un(tr(e)))}(e))),a=er(r),i=[];for(let s=0;s<e.entries.length;s+=1){const o=await Jn(e.idempotencyKey?Kn({userId:t,projectId:e.projectId,family:Xn(e.tool),key:e.idempotencyKey,itemIdOrK:e.itemId,path:["runs"],runHash:r[s],runK:a[s]}):Yn({userId:t,projectId:e.projectId,itemId:e.itemId,runHash:r[s],k:a[s],effectiveKey:n}));i.push({op_id:o,kind:"append_run",item_id:e.itemId,path:["runs"],value:e.entries[s]})}const s=await Eu({client:e.client,projectId:e.projectId,ops:i,deterministic:!0}),o=s.answers.find(e=>"invalid"===e.status&&"run_refused"===e.reason),l=new Map(s.answers.map(e=>[e.op_id,e]));return{run:s,runs:i.map((t,n)=>{const r=l.get(t.op_id);return{result:String(e.entries[n]?.result??""),run_at:"string"==typeof r?.run_at?r.run_at:null,asset_id:"string"==typeof r?.asset_id?r.asset_id:null,asset_created:!0===r?.asset_created}}),keyUsed:n,refusal:o?String(o.message??o.reason??"run refused"):null}}async function Qm(e,t){let n;try{const r=await co(),a=_o(),i=fo();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const s=t??await xu(r,e.project_id);if("unreadable"===s)return $u();n=s;const o=await dd(r,e.project_id,e.item_id);if(!o)return Bs(vs("Item",e.item_id));if("test-case"!==o.type)return Bs(Ss(`Item '${e.item_id}' is a ${o.type}, not a test-case`));const l=(e.asset??"").trim(),c=Nl({result:e.result,note:e.note,asset:l||void 0,point:e.point,release_id:e.release_id,build:e.build,environment:e.environment,tooling:e.tooling,steps_rev:e.steps_rev,evidence_url:e.evidence_url,step_results:e.step_results},e=>Ls(e));if("ops"===s){const t=await Jm({client:r,projectId:e.project_id,itemId:e.item_id,entries:[c],tool:"atoms_record_test_result",idempotencyKey:e.idempotency_key,requestId:e.request_id});if(t.refusal)return Bs(Ss(t.refusal,os));const n=t.runs[0],s=l?` (asset: ${l})`:"";return qu(t.run.outcome,{item_id:e.item_id,result:e.result,run_at:n.run_at,run_by:i||a,note:c.note??null,asset:l||null,asset_id:n.asset_id,asset_created:n.asset_created,message:t.run.outcome.replayed?Yt:`Test result '${e.result}' recorded for ${e.item_id}${s}`,...void 0!==e.date&&null!==e.date?{warning:yl}:{}},t.run.chunks,{idempotency_key_used:t.keyUsed})}const d=async()=>{const{data:t,error:n}=await r.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:i||a,p_actor_user_id:a,p_results:[c]});if(n)throw new Error(n.message);const s=Array.isArray(t)?t[0]:t?.[0],o="string"==typeof s?.run_at?s.run_at:null;await r.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:a,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:o,note:c.note,asset:l||null},actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const d=l?` (asset: ${l})`:"";return Vs(ys({item_id:e.item_id,result:e.result,run_at:o,run_by:i||a,note:c.note??null,asset:l||null,asset_id:s?.asset_id??null,asset_created:s?.asset_created??!1,message:`Test result '${e.result}' recorded for ${e.item_id}${d}`,...void 0!==e.date&&null!==e.date?{warning:yl}:{}}))};return await d()}catch(r){const a=Ou(n,t,r);return a?Qm(e,a):Bs(Ds(r))}}H(Bm,{recordRunsByOps:()=>Jm,recordTestResultHandler:()=>Qm});var Gm=D({"src/tools/record-test-result.ts"(){ko(),hd(),ey(),Ks(),Ql(),gr(),Nu(),gr()}}),Km={};async function Ym(e,t){let n;try{const r=await co(),a=_o(),i=fo();if(!Array.isArray(e.results)||0===e.results.length)return Bs(Ss("results must be a non-empty array"));if(e.results.length>100)return Bs(Ss(`results must have at most 100 entries (got ${e.results.length})`));const s=function(e){const t=[];let n=-1/0;return e.forEach((e,r)=>{const a="string"==typeof e?.date?Ml(e.date):NaN;Number.isNaN(a)||(a<n?t.push(r):n=a)}),t}(e.results);if(s.length>0)return Bs(Ss(function(e){const t=e.length>20?` and ${e.length-20} more`:"";return`Nothing was recorded: the dated entries are not oldest first. Runs are stamped with server time in the order sent, so the last entry becomes the newest run. Sort the entries by date, oldest first, and send them again. Dated before an earlier entry: results[${e.slice(0,20).join(", ")}]${t}.`}(s),os));try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const o=t??await xu(r,e.project_id);if("unreadable"===o)return $u();n=o;const l=await dd(r,e.project_id,e.item_id);if(!l)return Bs(vs("Item",e.item_id));if("test-case"!==l.type)return Bs(Ss(`Item '${e.item_id}' is a ${l.type}, not a test-case`));if("ops"===o){const t=e.results.map(e=>{const t=Nl(e,e=>Ls(e)),{date:n,...r}=t;return r}),n=await Jm({client:r,projectId:e.project_id,itemId:e.item_id,entries:t,tool:"atoms_record_test_results",idempotencyKey:e.idempotency_key,requestId:e.request_id});if(n.refusal)return Bs(Ss(n.refusal,os));const a=Dl(e.results);return qu(n.run.outcome,{item_id:e.item_id,count:e.results.length,results:n.runs,message:n.run.outcome.replayed?Yt:`Recorded ${e.results.length} test results for ${e.item_id}`,...a.length>0?{warning:Hl(a),ignored_date_entries:a}:{}},n.run.chunks,{idempotency_key_used:n.keyUsed})}const c=async()=>{const{data:t,error:n}=await r.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:i||a,p_actor_user_id:a,p_results:e.results.map(e=>Nl(e,e=>Ls(e)))});if(n)throw new Error(n.message);r.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:a,event_type:"test_result_recorded",old_data:null,new_data:{bulk:!0,count:e.results.length,results:t},actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const s=Dl(e.results);return Vs(ys({item_id:e.item_id,count:e.results.length,results:t,message:`Recorded ${e.results.length} test results for ${e.item_id}`,...s.length>0?{warning:Hl(s),ignored_date_entries:s}:{}}))};return await c()}catch(r){const a=Ou(n,t,r);return a?Ym(e,a):Bs(Ds(r))}}H(Km,{recordTestResultsBulkHandler:()=>Ym});var Zm=D({"src/tools/record-test-results-bulk.ts"(){ko(),hd(),ey(),Ks(),Gm(),gr(),Nu(),Ql()}}),Xm={};async function e_(e){try{const t=Zc(e.depth),n=await co(),r=await dd(n,e.project_id,e.item_id);if(!r)return Bs(vs("Item",e.item_id));const a=await mc(()=>n.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),tc),i=id(a,await mc(()=>n.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),nc));return Vs(ys(function(e){const t=Zc(e.depth),n=e.relationshipTypes?.length?new Set(e.relationshipTypes):null,r=new Map(e.items.map(e=>[e.id,e]));r.has(e.rootItemId)||r.set(e.rootItemId,e.rootItem);const a=new Map,i=(e,t,n)=>{a.has(e)||a.set(e,[]),a.get(e).push({neighbor:t,relType:n})};for(const t of e.relationships){const r=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(!Fc.has(r)||n&&!n.has(r)||i(t.from_id,t.to_id,r),Wc.has(r))){const e=Vc[r]??r;n&&!n.has(e)||i(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!Wc.has(r)||n&&!n.has(r)||i(t.from_id,t.to_id,r),Fc.has(r))){const e=Vc[r]??r;n&&!n.has(e)||i(t.to_id,t.from_id,e)}"related"!==r||n&&!n.has("related")||(i(t.from_id,t.to_id,"related"),i(t.to_id,t.from_id,"related"))}const s=new Set([e.rootItemId]),o=[],l=[],c=[];for(const t of a.get(e.rootItemId)??[])c.push({id:t.neighbor,depth:1,relType:t.relType,from:e.rootItemId});for(;c.length>0&&o.length<Lc;){const{id:e,depth:n,relType:i,from:d}=c.shift();if(s.has(e)||n>t)continue;s.add(e);const u=r.get(e);if(u&&(o.push({id:e,title:u.title,type:u.type,relationship:i,depth:n,from:d}),l.push({from:d,to:e,type:i}),n<t))for(const t of a.get(e)??[])s.has(t.neighbor)||c.push({id:t.neighbor,depth:n+1,relType:t.relType,from:e})}const d={id:e.rootItemId,title:e.rootItem.title,type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId};return{root:e.rootItemId,project_id:e.projectId,direction:e.direction,depth_limit:t,items:[d,...o],edges:l,total_count:o.length+1,...o.length>=Lc?{truncated:!0,truncation_message:`Results capped at ${Lc} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown"},items:a,relationships:i??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(Xm,{traceHandler:()=>e_});var t_=D({"src/tools/trace.ts"(){ko(),hd(),jc(),td(),Ks()}}),n_={};async function r_(e){try{const t=await co(),n=await mc(()=>{const n=t.from("assets").select("id, name, archived_at, created_at").eq("project_id",e.project_id);return e.include_archived?n:n.is("archived_at",null)},ac);return Vs(ys({assets:n,total:n.length}),{complete:!0})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(n_,{listAssetsHandler:()=>r_});var a_,i_=D({"src/tools/assets.ts"(){ko(),jc(),Ks()}}),s_={};async function o_(e,t,n,r){if(n&&r)throw new lt("baseline_id and as_of are mutually exclusive");if(r)return oc(od(r));if(!n)return null;const{data:a,error:i}=await e.from("baselines").select("project_id, snapshot_at, deleted_at").eq("id",n).maybeSingle();if(i)throw new Error(i.message);if(!a||a.project_id!==t||a.deleted_at)throw new lt("Baseline not found for this project");return lc(n)}async function l_(e,t,n){return n?yc(e,t,n):mc(()=>e.from("project_variables").select("*").eq("project_id",t),ic)}async function c_(e,t,n,r){const{data:a,error:i}=await e.rpc("save_variable_with_revision",{p_project_id:t.project_id,p_name:t.name,p_value:t.value,p_unit:t.unit??null,p_description:t.description??null,p_is_signal:t.is_signal??!1,p_range_min:t.range_min??null,p_range_max:t.range_max??null,p_rate_ms:t.rate_ms??null,p_user_id:n,p_event_source:r,p_variable_id:t.id??null});if(i)throw new Error(i.message);return a}async function d_(e,t,n){if(0===n.length||!0!==await lr(e,t))return n;const r=await An(e,t,n.map(e=>String(e.id)),"variable");return Promise.all(n.map(async e=>{const t=r.get(String(e.id));return t?{...e,base_token:await vn(t,"variable","variable")}:e}))}async function u_(e,t,n,r){const a=_o(),i=Xn("atoms_create_variable");return n?{rowId:await Jn(Kn({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables","row_id"]})),opId:await Jn(Kn({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables"]}))}:{rowId:await Jn(Zn({userId:a,projectId:e,name:t,what:"variable"})),opId:await Jn(Zn({userId:a,projectId:e,name:t,what:"create_variable"}))}}async function p_(e){try{const t=await co(),n=await o_(t,e.project_id,e.baseline_id,e.as_of),r=await l_(t,e.project_id,n),a=e.limit??50,i=e.offset??0,s=r.slice(i,i+a);return Vs(ys({variables:null===n?await d_(t,e.project_id,s):s,total:r.length},gs(r.length,a,i)))}catch(e){return Bs(Ds(e))}}async function m_(e){try{const t=await co(),n=await o_(t,e.project_id,e.baseline_id,e.as_of),r=(await l_(t,e.project_id,n)).find(t=>t.name===e.variable_name)??null;if(!r)return Bs(vs("Variable",e.variable_name));const a=await mc(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),tc),i=`{${e.variable_name}}`,s=a.filter(e=>(e.data?.body||"").includes(i)),[o]=null===n?await d_(t,e.project_id,[r]):[r];return Vs(ys({variable:o,referenced_by:s.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:s.length}))}catch(e){return Bs(Ds(e))}}async function __(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const s=await r.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(!s.data)return Bs(vs("Variable",e.variable_name));if("ops"===i){const t=String(s.data.id),n=[];void 0!==e.value&&n.push(["value",e.value]),void 0!==e.unit&&n.push(["unit",e.unit||null]),void 0!==e.description&&n.push(["description",e.description||null]);const a=n.map(([e])=>["variables",t,e]),i=await On({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:t,tokens:Ru(e.base_token),paths:a,values:n.map(([,e])=>e),name:e.variable_name}]}),o=i.items.get(t),l=[];n.forEach(([,e],t)=>{const n=o?.bases.get(qn(a[t]));n&&l.push(Tn({op_id:Qn(),kind:"set",item_id:null,path:a[t],value:e},n))});const c=await Eu({client:r,projectId:e.project_id,ops:l,refusals:i.refusals,variableNames:new Map([[t,e.variable_name]])}),d={...s.data};for(const[e,t]of n)d[e]=t;return qu(c.outcome,!1===e.echo?{name:e.variable_name,updated:!0}:{variable:d},c.chunks)}const o={updated_by:a,updated_at:(new Date).toISOString()};void 0!==e.value&&(o.value=e.value),void 0!==e.unit&&(o.unit=e.unit||null),void 0!==e.description&&(o.description=e.description||null);const l=await c_(r,{...s.data,...o,project_id:e.project_id,name:e.variable_name,value:o.value??s.data.value,unit:"unit"in o?o.unit:s.data.unit,description:"description"in o?o.description:s.data.description},a,"mcp");return!1===e.echo?Vs(ys({name:e.variable_name,updated:!0})):Vs(ys({variable:l}))}catch(r){const a=Ou(n,t,r);return a?__(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}async function f_(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const s=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const t=e.variables.filter(e=>!s.test(e.name));if(t.length>0)return Bs(Ss(`Invalid variable name(s): ${t.map(e=>e.name).join(", ")}. Use letters, digits, underscores; must start with letter or underscore.`));const n=e.variables.map(e=>e.name),o=n.map(e=>e.toLowerCase()),l=n.filter((e,t)=>o.indexOf(o[t])!==t);if(l.length>0)return Bs(Ss(`Duplicate names in batch (case-insensitive): ${[...new Set(l)].join(", ")}`));const c=await l_(r,e.project_id,null),d=new Set(c.map(e=>e.name.toLowerCase())),u=n.filter(e=>d.has(e.toLowerCase()));if(u.length>0)return Bs(Ss(`Variable(s) already exist (case-insensitive): ${u.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));if("ops"===i){const t=e.variables,n=await Promise.all(t.map((t,n)=>u_(e.project_id,t.name,e.idempotency_key,n))),a=t.map((e,t)=>a_(n[t],e)),i=crypto.randomUUID(),s=await Eu({client:r,projectId:e.project_id,ops:a,deterministic:!0,send:{mode:"bulk",atomic:!0,chunk:!1,bulkId:i}}),o=t.map((t,r)=>({id:n[r].rowId,project_id:e.project_id,name:t.name,value:t.value,unit:t.unit??null,description:t.description??null}));return qu(s.outcome,{batch_id:i,created:o.length,variables:!1===e.echo?o.map(e=>({name:e.name})):o,message:`${o.length} variable(s) created. Reference them as {name} in requirement bodies.`},s.chunks)}const p=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:a,updated_by:a})),m=await async function(e,t,n,r){const{data:a,error:i}=await e.rpc("bulk_save_variables_with_revisions",{p_project_id:t,p_variables:n,p_user_id:r,p_event_source:"mcp"});if(i)throw new Error(i.message);return a??[]}(r,e.project_id,p,a);return Vs(ys({batch_id:crypto.randomUUID(),created:(m??[]).length,variables:!1===e.echo?(m??[]).map(e=>({name:e.name})):m??[],message:`${(m??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`}))}if(!e.name||!e.value)return Bs(Ss("Provide either (name, value) for single variable or variables[] for batch."));if(!s.test(e.name))return Bs(Ss(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const o=(await l_(r,e.project_id,null)).find(t=>t.name.toLowerCase()===e.name.toLowerCase());if(o)return Bs(Ss(`Variable "${o.name}" already exists in this project (names are unique regardless of case).`));if("ops"===i){const t=await u_(e.project_id,e.name,e.idempotency_key,0),n=await Eu({client:r,projectId:e.project_id,ops:[a_(t,e)],deterministic:!0}),a={id:t.rowId,project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null};return qu(n.outcome,!1===e.echo?{name:e.name}:{variable:a,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`},n.chunks)}const l=await c_(r,{project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null},a,"mcp");return!1===e.echo?Vs(ys({name:e.name})):Vs(ys({variable:l,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(r){const a=Ou(n,t,r);return a?f_(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}async function h_(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const{data:s}=await r.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!s)return Bs(vs("Variable",e.name));const{count:o,error:l}=await r.from("items").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).is("deleted_at",null).filter("data->>body","ilike",`%{${e.name}}%`);if(l)throw new Error(l.message);const c=o??0;if(c>0&&!e.force)return Bs(Ss(`Variable "${e.name}" is referenced in ${c} item${c>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(Lu("atoms_delete_variable")){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const n=Fu(t);return Vs(ys({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:c,would_orphan_references:c>0},confirmation_token:n.token,expires_at:n.expires_at,expires_in_seconds:n.expires_in_seconds,message:`Re-call atoms_delete_variable with the same project_id, name, and confirmation_token within ${n.expires_in_seconds}s to execute.`}))}const n=Wu(e.confirmation_token,t);if(!n.valid)return Bs(Ss(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t=["variables",String(s.id)],n=await On({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:String(s.id),tokens:Ru(e.base_token),paths:[t],values:[null],name:e.name}]}),a=n.items.get(String(s.id))?.bases.get(qn(t)),i=a?[Tn({op_id:Qn(),kind:"remove",item_id:null,path:["variables"],row_id:String(s.id),value:null},a)]:[],o=await Eu({client:r,projectId:e.project_id,ops:i,refusals:n.refusals});return qu(o.outcome,{deleted:!0,name:e.name,referenced_by_items:c,warning:c>0?`${c} item${c>1?"s":""} still contain {${e.name}}. Those references are now unresolved.`:void 0},o.chunks)}const d=await async function(e,t,n,r){const{data:a,error:i}=await e.rpc("delete_variable_with_revision",{p_project_id:t,p_variable_id:n,p_user_id:r,p_event_source:"mcp"});if(i)throw new Error(i.message);return Boolean(a)}(r,e.project_id,s.id,a);return d?Vs(ys({deleted:!0,name:e.name,referenced_by_items:c,warning:c>0?`${c} item${c>1?"s":""} still contain {${e.name}} — those references are now unresolved.`:void 0})):Bs(vs("Variable",e.name))}catch(r){const a=Ou(n,t,r);return a?h_(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}H(s_,{createVariableHandler:()=>f_,deleteVariableHandler:()=>h_,getVariableHandler:()=>m_,listVariablesHandler:()=>p_,updateVariableHandler:()=>__});var y_,g_=D({"src/tools/variables.ts"(){ko(),gr(),Nu(),jc(),ld(),Xt(),Qu(),Ks(),a_=(e,t)=>({op_id:e.opId,kind:"add",item_id:null,path:["variables"],row_id:e.rowId,value:{name:t.name,value:t.value,unit:t.unit??null,description:t.description??null}})}}),w_={};async function v_(e,t,n,r,a){let i=0;for(;;){const{data:s,error:o}=await e.rpc("apply_domain_change",{p_project_id:t,p_old_domain:n,p_new_domain:r,p_user_id:a,p_event_source:"mcp",p_limit:y_});if(o)throw new Error(i>0?`${o.message} (${i} items were already updated and the registry is unchanged: call again to finish)`:o.message);const l="number"==typeof s?s:0;if(i+=l,l<y_)return i}}async function b_(e,t){const{data:n,error:r}=await e.from("metadata").select("domains, levels, function_tags").eq("project_id",t).maybeSingle();if(r)throw new Error(`metadata read failed: ${r.message}`);return{domains:n?.domains??[],levels:n?.levels??[],functionTags:Array.isArray(n?.function_tags)?n.function_tags.filter(e=>"string"==typeof e):[]}}async function j_(e){try{const t=await co(),{domains:n,functionTags:r}=await b_(t,e.project_id),a=Ai(n,r),i=new Set(a.map(ti)),s=new Set(r.map(ti)),o=n.filter(e=>!i.has(ti(e))),{counts:l,orphans:c}=await async function(e,t,n){const r=await mc(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),tc),a={};for(const e of n)a[e]=0;const i={};for(const e of r){const t=e.data?.tags?.domains??[];for(const e of t)i[e]=(i[e]??0)+1,e in a&&a[e]++}const s=new Set(n),o={};for(const[e,t]of Object.entries(i))s.has(e)||(o[e]=t);return{counts:a,orphans:o}}(t,e.project_id,o),d=o.map(e=>({name:e,registered:!0,item_count:l[e]??0})),u=Object.entries(c).filter(([e])=>!s.has(ti(e))).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),p=[...d,...u];return Vs(ys({domains:p,total:p.length,registered_count:d.length,unregistered_count:u.length,excluded_function_tags:a,note:u.length>0?`${u.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")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}async function k_(e,t){let n;try{const r=await co();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const a=t??await xu(r,e.project_id);if("unreadable"===a)return $u();n=a;const i=Ls(e.name).trim().toLowerCase();if(!i)return Bs(Ss("Domain name cannot be empty."));const s=await b_(r,e.project_id);if(null!==ni(i,s.functionTags))return Bs(Ss(Hi(i,!0),os));const o=ni(i,s.domains);if(null!==o)return Bs(Ss(Hi(o,!1),os));if("ops"===a){const t={op_id:Qn(),kind:"add",item_id:null,path:["taxonomy","domains"],value:i},{run:n}=await Du({client:r,projectId:e.project_id,op:t});return n.answers.some(e=>"noop"===e.status)?Bs(Ss(Hi(i,!1),os)):qu(n.outcome,{domain:{name:i},message:Di(i)},n.chunks)}const l=async()=>{const{data:t,error:n}=await r.rpc("append_project_domain",{p_project_id:e.project_id,p_domain:i});if(n)throw new Error(n.message);if(t&&!1===t.added){const{functionTags:t}=await b_(r,e.project_id),n=null!==ni(i,t);return Bs(Ss(Hi(i,n),os))}return Vs(ys({domain:{name:i},message:Di(i)}))};return await l()}catch(r){const a=Ou(n,t,r);return a?k_(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}async function S_(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const s=void 0!==e.new_name;if(s===(void 0!==e.is_function))return Bs(Ss(function(e){return e?"Pass either new_name (rename the domain) or is_function (flag it as a function, or unflag it back to a domain), not both. Make the two changes in separate calls.":"Pass new_name to rename the domain, or is_function to flag it as a function (true) or unflag it back to a domain (false)."}(s),os));if(void 0===e.new_name)return await async function(e,t,n,r,a,i=!1){const s=Ls(n).trim();if(!s)return Bs(Ss("name cannot be empty."));const{domains:o,functionTags:l}=await b_(e,t),c=ni(s,o),d=ni(s,l);if(r){if(null!==d)return Vs(ys({domain:{name:d},is_function:!0,changed:!1,message:Pi(d)}));if(null===c){const{data:n}=await e.from("items").select("id").eq("project_id",t).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([s.toLowerCase()])).limit(1);return n&&0!==n.length?Bs(Ss(function(e){return`Tag "${e}" is carried by items but is not registered in this project's taxonomy, so it cannot be flagged as a function. Register it first with atoms_create_domain.`}(s.toLowerCase()),os)):Bs(vs("Domain",s.toLowerCase()))}const{carried:n}=await Mi(e,t,c,o),r=await zi(e,t,n);if(a)return Vs(ys({dry_run:!0,domain:{name:c},is_function:!0,items_carrying_tag:r,message:Li(c,r,!0)}));if(i){const n={op_id:Qn(),kind:"set",item_id:null,path:["taxonomy","domains",c,"is_function"],value:!0,base:!1},{run:a}=await Du({client:e,projectId:t,op:n});return Hu(a,"deleted")?Bs(vs("Domain",c.toLowerCase())):a.outcome.not_applied.length>0?qu(a.outcome,{},a.chunks):Vs(ys({domain:{name:c},is_function:!0,changed:!a.answers.some(e=>"noop"===e.status),items_carrying_tag:r,message:Li(c,r,!1)}))}const l=async()=>{const{data:n,error:a}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"flag_function",p_values:[c]});if(a)throw new Error(a.message);return Array.isArray(n?.function_tags)&&null!==ni(c,n.function_tags)?Vs(ys({domain:{name:c},is_function:!0,changed:!0,items_carrying_tag:r,message:Li(c,r,!1)})):Bs(vs("Domain",c.toLowerCase()))};return await l()}if(null===d)return null!==c?Vs(ys({domain:{name:c},is_function:!1,changed:!1,message:Ni(c)})):Bs(vs("Domain",s.toLowerCase()));const u=await async function(e,t,n){const{count:r,error:a}=await e.from("items").select("id",{count:"exact",head:!0}).eq("project_id",t).is("deleted_at",null).filter("data->analysis_props->>source_function","ilike",Zl(n));if(a)throw new Error(a.message);return"number"==typeof r?r:0}(e,t,d);if(a)return Vs(ys({dry_run:!0,domain:{name:d},is_function:!1,analysis_rows_using_function:u,message:Fi(d,u,!0)}));if(i){const n={op_id:Qn(),kind:"set",item_id:null,path:["taxonomy","domains",d,"is_function"],value:!1,base:!0},{run:r}=await Du({client:e,projectId:t,op:n});if(Hu(r,"deleted"))return Bs(vs("Domain",d.toLowerCase()));if(r.outcome.not_applied.length>0)return qu(r.outcome,{},r.chunks)}else{const n=async()=>{const{error:n}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"unflag_function",p_values:[d]});if(n)throw new Error(n.message)};await n()}return Vs(ys({domain:{name:d},is_function:!1,changed:!0,analysis_rows_using_function:u,message:Fi(d,u,!1)}))}(r,e.project_id,e.name,!0===e.is_function,!0===e.dry_run,"ops"===i);const{domains:o,functionTags:l}=await b_(r,e.project_id),c=Ls(e.name).trim(),d=function(e,t){const n=e.trim();return"ops"===t?n:n.toLowerCase()}(Ls(e.new_name),"ops"===i?"ops":"main");if(!d)return Bs(Ss("new_name cannot be empty."));const{spelling:u,registered:p}=await Mi(r,e.project_id,c,o);if(null===u)return Bs(vs("Domain",c.toLowerCase()));if(null!==ni(d,[u]))return Bs(Ss(function(e,t){return`"${t}" is the same domain as "${e}" (only the case differs), so there is nothing to rename.`}(u,d)));const m=function(e,t,n,r){if(null!==ni(t,[e]))return null;const a=ni(t,r);if(null!==a)return{kind:"function",name:a};const i=ni(t,n);return null!==i?{kind:"domain",name:i}:null}(u,d,o,l);if("function"===m?.kind)return Bs(function(e,t,n){const r=`atoms_update_domain (name: "${n.trim().toLowerCase()}", is_function: false)`;return{status:"error",message:`Cannot rename "${e}" to "${t}": "${n}" is a function, and a tag is a domain or a function, never both, so a domain cannot take a function's name. Choose another name, or unflag the function first with ${r}.`,next_steps:["Choose a new_name that is not already a domain or a function",`Or unflag the function first: ${r}`],details:{code:Ei,functions:[n]}}}(u,d,m.name));if("domain"===m?.kind&&p)return Bs(Ss(Ui(m.name)));const _="domain"===m?.kind&&!p,f=_&&m?m.name:d,h=await zi(r,e.project_id,[u]);if(e.dry_run)return Vs(ys({dry_run:!0,rename:{from:u,to:f},items_affected:h,message:_?`Dry run: "${u}" is not registered and "${f}" is, so the ${h} item${1!==h?"s":""} carrying "${u}" would be merged into the registered domain "${f}" (the registry is not changed). Call again with dry_run=false to apply.`:`Dry run: renaming "${u}" → "${d}" would update ${h} item${1!==h?"s":""}. Call again with dry_run=false to apply.`}));if("ops"===i){const t={op_id:Qn(),kind:"rename",item_id:null,path:["taxonomy","domains"],value:f,base:u},{run:n,retagged:a}=await Du({client:r,projectId:e.project_id,op:t,repeat:!0});return Hu(n,"deleted")?Bs(vs("Domain",u.toLowerCase())):Hu(n,"invalid","name_taken")?Bs(Ss(Ui(f))):qu(n.outcome,{domain:{name:f},renamed_from:u,items_updated:a,message:_?`Domain "${u}" merged into the registered domain "${f}". ${a} item${1!==a?"s":""} updated.`:`Domain renamed "${u}" → "${d}". ${a} item${1!==a?"s":""} updated.`},n.chunks)}const y=async()=>{const t=await v_(r,e.project_id,u,f,a);return _?Vs(ys({domain:{name:f},renamed_from:u,items_updated:t,message:`Domain "${u}" merged into the registered domain "${f}". ${t} item${1!==t?"s":""} updated.`})):(await async function(e,t,n,r){const{data:a,error:i}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"rename",p_values:[n,r]});if(i)throw new Error(i.message);if(!(Array.isArray(a?.domains)?a.domains.filter(e=>"string"==typeof e):[]).includes(n))return;const{error:s}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"remove_domains",p_values:[n]});if(s)throw new Error(s.message)}(r,e.project_id,u,d),Vs(ys({domain:{name:d},renamed_from:u,items_updated:t,message:`Domain renamed "${u}" → "${d}". ${t} item${1!==t?"s":""} updated.`})))};return await y()}catch(r){const a=Ou(n,t,r);return a?S_(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}async function A_(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const{domains:s}=await b_(r,e.project_id),o=Ls(e.name).trim(),{spelling:l,registered:c}=await Mi(r,e.project_id,o,s),d=l??o.toLowerCase(),u=null===l?0:await zi(r,e.project_id,[l]);if(!c&&0===u)return Bs(vs("Domain",d));if(u>0&&!e.force)return Bs(Ss(function(e,t){return`Domain "${e}" is used by ${t} item${t>1?"s":""}. Use force=true to delete and strip the domain from all items, or re-tag them first.`}(d,u)));if(Lu("atoms_delete_domain")){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:d};if(!e.confirmation_token){const e=Fu(t);return Vs(ys({status:"confirmation_required",preview:{domain_name:d,items_using_count:u,items_affected:u,would_strip_from_items:u>0,registered:c},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, force flag, and confirmation_token within ${e.expires_in_seconds}s to execute.`}))}const n=Wu(e.confirmation_token,t);if(!n.valid)return Bs(Ss(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t={op_id:Qn(),kind:"remove",item_id:null,path:["taxonomy","domains"],value:d},{run:n,retagged:a}=await Du({client:r,projectId:e.project_id,op:t,repeat:!0});return Hu(n,"deleted")?Bs(vs("Domain",d)):qu(n.outcome,{deleted:!0,name:d,items_updated:a,message:u>0?`Domain "${d}" deleted and stripped from ${a} item${1!==a?"s":""}.`:`Domain "${d}" deleted.`},n.chunks)}const p=async()=>{const t=u>0?await v_(r,e.project_id,d,null,a):0;if(c){const{error:t}=await r.rpc("mutate_project_domains",{p_project_id:e.project_id,p_action:"remove_domains",p_values:[d]});if(t)throw new Error(t.message)}return Vs(ys({deleted:!0,name:d,items_updated:t,message:u>0?`Domain "${d}" deleted and stripped from ${t} item${1!==t?"s":""}.`:`Domain "${d}" deleted.`}))};return await p()}catch(r){const a=Ou(n,t,r);return a?A_(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Bs(As()):Bs(Ps(r instanceof Error?r.message:String(r)))}}H(w_,{DOMAIN_CHANGE_BATCH:()=>y_,createDomainHandler:()=>k_,deleteDomainHandler:()=>A_,listDomainsHandler:()=>j_,updateDomainHandler:()=>S_});var I_=D({"src/tools/domains.ts"(){ko(),jc(),Qu(),Ks(),Oi(),pc(),gr(),Nu(),Bi(),y_=200}}),x_={};async function $_(e){try{const t=await co(),{data:n,error:r}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle(),a=n?.name??null,i=r?.message??null,s=await mc(()=>t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null),tc);if(!a&&0===s.length){if(i)throw new Error(i);return Bs(vs("Project",e.project_id))}const o={requirements:0,test_cases:0,notes:0},l=[];for(const e of s)if("requirement"===e.type){o.requirements++;const t=e.data?.tags?.domains??[];l.push({id:e.id,domains:t})}else"test-case"===e.type?o.test_cases++:"note"===e.type&&o.notes++;const c=function(e){const t={passed:0,failed:0,blocked:0,not_run:0};for(const n of e){if("test-case"!==n.type)continue;const e=Fl(n);"passed"===e?t.passed++:"failed"===e?t.failed++:"blocked"===e?t.blocked++:t.not_run++}return t}(s),d=id(s,await mc(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),nc)),u=qc(s,d),p=l.filter(e=>u.has(e.id)).length,m=l.length,_={covered:p,uncovered:m-p,total:m,percent:Nc(p,m),via_mitigation:Dc(l.map(e=>e.id),u,Oc(s,d))},f=new Map;for(const e of l){const t=e.domains.length>0?e.domains:["(untagged)"],n=u.has(e.id);for(const e of t){f.has(e)||f.set(e,{covered:0,total:0});const t=f.get(e);t.total++,n&&t.covered++}}const h=Array.from(f.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:Nc(t.covered,t.total)})),y=new Date;y.setDate(y.getDate()-7);const g=!0===await kd(t,e.project_id),{count:w,error:v}=g?await t.from("project_changes").select("seq",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("committed_at",y.toISOString()):await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",y.toISOString());if(v)throw new Error(v.message);return Vs(ys({project_id:e.project_id,project_name:a??`Project ${e.project_id.slice(0,8)}`,counts:o,test_status:c,coverage:_,coverage_by_domain:h,recent_changes:w??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(x_,{projectSummaryHandler:()=>$_});var E_,q_=D({"src/tools/project-summary.ts"(){ko(),hd(),Yc(),Pc(),jc(),Ks(),Cd()}}),O_={};async function R_(e){try{const t=await co();let n,r;if(e.query&&e.query.trim().length>0){const a=await fd(t,e.project_id,e.query,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});n=a.items.map(e=>({id:e.id,title:e.title,type:e.type,status:Fl(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),r=a.totalCount}else{const a=await cd(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});n=a.items.map(e=>({id:e.id,title:e.title,type:e.type,status:Fl(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),r=a.totalCount}const a=await async function(e,t){const n=await mc(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),tc),r=new Set,a=new Set;for(const e of n){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)r.add(t);const n=t.level;n&&a.add(n)}}return{domains:[...r].sort(),levels:[...a].sort()}}(t,e.project_id);return Vs(ys({items:n,filters:{domains:a.domains,levels:a.levels,types:E_},project_id:e.project_id},gs(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(O_,{browseHandler:()=>R_});var T_,M_=D({"src/tools/browse.ts"(){ko(),hd(),Ks(),Ql(),E_=["requirement","test-case","note","table"]}}),z_={};async function C_(e){try{const t=e.direction??"downstream",n=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await co(),a=await dd(r,e.project_id,e.item_id);if(!a)return Bs(vs("Item",e.item_id));const i=await mc(()=>r.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),tc),s=id(i,await mc(()=>r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),nc)),o=new Map;for(const e of i)o.set(e.id,{title:e.title,type:e.type});const l=new Map,c=(e,t,n)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:n})};for(const e of s){const n=e.type;"upstream"!==t&&"both"!==t||(Bc.includes(n)&&c(e.from_id,e.to_id,n),Jc.includes(n)&&c(e.to_id,e.from_id,Qc[n]??n)),"downstream"!==t&&"both"!==t||(Jc.includes(n)&&c(e.from_id,e.to_id,n),Bc.includes(n)&&c(e.to_id,e.from_id,Qc[n]??n)),"related"===n&&(c(e.from_id,e.to_id,"related"),c(e.to_id,e.from_id,"related"))}const d=new Set;d.add(e.item_id);const u=[];let p=0;const m=[];for(const t of l.get(e.item_id)??[])m.push({id:t.neighbor,depth:1,path:[{from_id:e.item_id,to_id:t.neighbor,relationship_type:t.relType}]});for(;m.length>0&&u.length<T_;){const{id:e,depth:t,path:r}=m.shift();if(d.has(e))continue;if(null!==n&&t>n)continue;d.add(e);const a=o.get(e);if(a&&(u.push({item_id:e,title:a.title,type:a.type,depth:t,relationship_path:r}),t>p&&(p=t),null===n||t<n))for(const n of l.get(e)??[])d.has(n.neighbor)||m.push({id:n.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:n.neighbor,relationship_type:n.relType}]})}let _=0;if(e.include_variable_refs){const{data:t,error:n}=await r.from("variable_references").select("variable_id").eq("item_id",e.item_id).eq("project_id",e.project_id);if(n)throw new Error(n.message);const a=[...new Set((t??[]).map(e=>e.variable_id))];if(a.length>0){const{data:t,error:n}=await r.from("project_variables").select("id, name").in("id",a);if(n)throw new Error(n.message);const i=new Map((t??[]).map(e=>[e.id,e.name])),s=await mc(()=>r.from("variable_references").select("variable_id, item_id, field").in("variable_id",a).eq("project_id",e.project_id).neq("item_id",e.item_id),rc);for(const t of s){const n=t.item_id;if(d.has(n))continue;if(u.length>=T_)break;d.add(n);const r=o.get(n);if(!r)continue;const a=i.get(t.variable_id)??t.variable_id;u.push({item_id:n,title:r.title,type:r.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:n,relationship_type:`variable_ref:${a}`}]}),_++}}}const f={};for(const e of u)f[e.type]=(f[e.type]??0)+1;const h=o.get(e.item_id);return Vs(ys({root:{item_id:e.item_id,title:h?.title??a.title,type:h?.type??a.type},impacted_items:u,summary:{total_impacted:u.length,by_type:f,max_depth_reached:p,..._>0?{variable_impact_count:_}:{},...u.length>=T_?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}H(z_,{impactAnalysisHandler:()=>C_});var D_,H_,U_,P_,N_,L_,F_,W_,V_,B_,J_,Q_,G_=D({"src/tools/impact-analysis.ts"(){ko(),hd(),td(),jc(),Ks(),T_=200}});function K_(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function Y_(e){return null==e?"":String(e)}function Z_(e){if(null==e||""===e)return"null";if(Array.isArray(e))return 0===e.length?"null":`[${e.map(Z_).join(",")}]`;if("object"==typeof e){const t=e,n=Object.keys(t).filter(e=>"null"!==Z_(t[e])).sort();return 0===n.length?"null":`{${n.map(e=>`${JSON.stringify(e)}:${Z_(t[e])}`).join(",")}}`}return JSON.stringify(e)}function X_(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function ef(e){return null==e||""===e?null:e}function tf(e,t=!0){const n=ef(e);if(null===n)return"null";if("object"!=typeof n)return JSON.stringify(n);if(Array.isArray(n)){if(0===n.length)return"null";const e=n.map(e=>tf(e,t));return t&&n.every(e=>null===e||["string","number","boolean"].includes(typeof e))&&e.sort(),`[${e.join(",")}]`}const r=n,a=Object.keys(r).filter(e=>!function(e){return null==e||""===e||(Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length)}(r[e])).sort();return 0===a.length?"null":`{${a.map(e=>`${JSON.stringify(e)}:${tf(r[e],t)}`).join(",")}}`}function nf(e,t){return e.some(e=>!t.includes(e))||t.some(t=>!e.includes(t))}function rf(e){const t=Array.isArray(e)?e:null==e?[]:[e],n=[];for(const e of t){const t="string"==typeof e?e:null!==e&&"object"==typeof e?e.id:void 0;"string"==typeof t&&t.trim()&&n.push(t.trim())}return n}function af(e,t){const n=X_(e),r="parents"===t?n.parent:"children"===t?n.child:void 0;return Array.from(new Set([...rf(n[t]),...rf(r)])).sort()}function sf(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){const e=X_(n);if("string"!=typeof e.date||!e.date.trim())continue;const r={};for(const t of L_){const n=ef(e[t]);null!==n&&(r[t]=n)}t.set(e.date,r)}return t}function of(e,t){const n=sf(e),r=sf(t),a=Array.from(new Set([...n.keys(),...r.keys()])).sort().filter(e=>{const t=n.get(e),a=r.get(e);return!(t&&a&&L_.every(e=>tf(t[e])===tf(a[e])))});return[Object.fromEntries(a.map(e=>[e,n.get(e)??null])),Object.fromEntries(a.map(e=>[e,r.get(e)??null]))]}function lf(e,t){const n=[];ef(e.title)!==ef(t.title)&&n.push({path:"title"}),ef(e.type)!==ef(t.type)&&n.push({path:"type"});const r=e.data??{},a=t.data??{},i=(e,t)=>n.push({path:t?`data.${e}.${t}`:`data.${e}`,lane:e});for(const e of P_)ef(r[e])!==ef(a[e])&&i(e);const s=r.tags??{},o=a.tags??{};for(const e of new Set([...Object.keys(s),...Object.keys(o)])){const t=s[e],n=o[e];(Array.isArray(t)&&Array.isArray(n)?nf(t,n):tf(t)!==tf(n))&&i("tags",e)}const l=X_(r.analysis_props),c=X_(a.analysis_props);for(const e of Array.from(new Set([...Object.keys(l),...Object.keys(c)])).sort())!D_.has(e)&&K_(l[e])&&K_(c[e])&&Y_(l[e])!==Y_(c[e])&&i("analysis_props",e);tf(r.ownership)!==tf(a.ownership)&&i("ownership");for(const e of N_)nf(af(r.relationships,e),af(a.relationships,e))&&i("relationships",e);Object.keys(of(r.runs,a.runs)[0]).length>0&&i("runs");for(const e of Array.from(new Set([...Object.keys(r),...Object.keys(a)])).sort())F_.has(e)||tf(r[e],!1)!==tf(a[e],!1)&&i(e);return n}function cf(e,t){const n=lf(e,t),r=new Set(n.map(e=>e.path)),a=new Set(n.flatMap(e=>e.lane?[e.lane]:[])),i=["title","type"].filter(e=>r.has(e));return 0===a.size||(i.push("data"),r.has("data.status")&&i.push("status"),r.has("data.tags.level")&&i.push("tags.level"),r.has("data.tags.domains")&&i.push("tags.domains"),i.push(...function(e,t){const n=X_(e),r=X_(t),a=[],i=X_(n.analysis_props),s=X_(r.analysis_props),o=Array.from(new Set([...Object.keys(i),...Object.keys(s)])).sort();for(const e of o){if(D_.has(e))continue;const t=i[e],n=s[e];K_(t)&&K_(n)?Y_(t)!==Y_(n)&&a.push(`analysis_props.${e}`):Z_(t)!==Z_(n)&&a.push(`analysis_props.${e}`)}const l=e=>{const t=new Map;for(const[n,r]of Object.entries(e))"string"==typeof r&&t.set(n.toLowerCase(),{key:n,value:r});return t},c=l(X_(n.fields)),d=l(X_(r.fields)),u=Array.from(new Set([...c.keys(),...d.keys()])).sort();for(const e of u)if((c.get(e)?.value??"")!==(d.get(e)?.value??"")){const t=d.get(e)?.key??c.get(e)?.key??e;a.push(`fields.${t}`)}return a}(e.data,t.data).filter(e=>a.has(e.split(".")[0])))),i}function df(e,t){for(const[n,r]of Object.entries(e))if(n.toLowerCase()===t)return"string"==typeof r?r:null;return null}function uf(e,t,n){const r=X_(e.data),a=X_(t.data),i=new Set(n),s={};for(const o of n)if("title"===o)s[o]={from:e.title??null,to:t.title??null};else if("type"===o)s[o]={from:e.type??null,to:t.type??null};else if("status"===o)s[o]={from:r.status??null,to:a.status??null};else if("tags.level"===o)s[o]={from:X_(r.tags).level??null,to:X_(a.tags).level??null};else if("tags.domains"===o)s[o]={from:X_(r.tags).domains??null,to:X_(a.tags).domains??null};else if(o.startsWith("analysis_props.")){const e=o.slice(15);s[o]={from:X_(r.analysis_props)[e]??null,to:X_(a.analysis_props)[e]??null}}else if(o.startsWith("fields.")){const e=o.slice(7).toLowerCase();s[o]={from:df(X_(r.fields),e),to:df(X_(a.fields),e)}}else if("data"===o){const n=lf(e,t),l=new Set(n.map(e=>e.path)),c=Array.from(new Set(n.flatMap(e=>e.lane?[e.lane]:[]))).sort(),d={},u={};for(const e of c){const[t,n]=mf(e,r[e],a[e],i,l);Z_(t)!==Z_(n)&&(d[e]=t??null,u[e]=n??null)}s[o]={from:d,to:u}}else s[o]={from:null,to:null};return s}function pf(e,t){return null===e||"object"!=typeof e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).filter(([e])=>!t(e)))}function mf(e,t,n,r,a){if("status"===e)return r.has("status")?[null,null]:[t,n];if("tags"===e){const e=e=>!a.has(`data.tags.${e}`)||"level"===e&&r.has("tags.level")||"domains"===e&&r.has("tags.domains");return[pf(t,e),pf(n,e)]}if("relationships"===e){const e=N_.filter(e=>a.has(`data.relationships.${e}`)),r=t=>Object.fromEntries(e.map(e=>[e,af(t,e)]));return[r(t),r(n)]}if("runs"===e)return of(t,n);if("analysis_props"===e){const e=e=>r.has(`analysis_props.${e}`);return[pf(t,e),pf(n,e)]}if("fields"===e){const e=e=>function(e,t){const n=e.toLowerCase();for(const e of t)if(e.startsWith("fields.")&&e.slice(7).toLowerCase()===n)return!0;return!1}(e,r);return[pf(t,e),pf(n,e)]}return Array.isArray(t)&&Array.isArray(n)?function(e,t){const n={},r={},a=_f(e),i=_f(t);if(a&&i){const s=new Map(a.map((t,n)=>[t,e[n]])),o=new Map(i.map((e,n)=>[e,t[n]]));for(const e of new Set([...a,...i])){const t=s.get(e)??null,a=o.get(e)??null;Z_(t)!==Z_(a)&&(n[e]=t,r[e]=a)}return a.join("\n")!==i.join("\n")&&(n.order=a,r.order=i),[n,r]}for(let a=0;a<Math.max(e.length,t.length);a++)Z_(e[a])!==Z_(t[a])&&(n[a]=e[a]??null,r[a]=t[a]??null);return[n,r]}(t,n):[t,n]}function _f(e){const t=[];for(const n of e){const e=X_(n).id;if("string"!=typeof e||"order"===e)return null;t.push(e)}return new Set(t).size===t.length?t:null}function ff(e){return"string"==typeof e?1:Array.isArray(e)?e.reduce((e,t)=>e+ff(t),0):null!==e&&"object"==typeof e?Object.values(e).reduce((e,t)=>e+ff(t),0):0}function hf(e){const t=JSON.stringify(e,null,2),n=t.split("\n").length;return t.length+n*B_+V_*ff(e.diff)+2}function yf(e,t,n){if("string"==typeof e){if(e.length<=t+Q_)return e;n.n++;let r=t;const a=e.charCodeAt(r-1);return a>=55296&&a<=56319&&r--,`${e.slice(0,r)}... [clipped, ${e.length-r} more characters]`}return Array.isArray(e)?e.map(e=>yf(e,t,n)):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,yf(r,t,n)])):e}function gf(e,t){const n=e.diff??{};for(const r of J_){const a={n:0},i=yf(n,r,a),s={...e,diff:i,...a.n>0?{diff_clipped:!0}:{}};if(hf(s)<=t)return s}const r={n:0},a=yf(n,J_[J_.length-1],r),i=r.n>0?{diff_clipped:!0}:{},s=Object.keys(a);let o={},l={...e,diff:o,...i,diff_omitted:s.length};for(let n=0;n<s.length;n++){const r={...o,[s[n]]:a[s[n]]},c={...e,diff:r,...i,diff_omitted:s.length-n-1};if(hf(c)>t)break;o=r,l=c}return 0===l.diff_omitted&&delete l.diff_omitted,l}var wf=D({"src/core/baseline-diff.ts"(){D_=new Set(["field_source","approved","approved_at","approved_by","approved_note"]),H_=["approval_state","approver_user_id","rev_label","approved_at","requires_impacted_approval"],U_=["id","title","type","metadata","parent","child",...H_],P_=["body","summary","status","level","isLocked","lockedBy","lockedAt"],N_=["parents","children","related","verifies","verified_by","mitigated_by","mitigates","traces_to","traced_by","allocated_to","allocated_from","decomposes_to","decomposed_from","affects","affected_by"],L_=["result","by","note","asset"],F_=new Set(["tags","ownership","relationships","runs",...P_,...U_]),W_=2e4,V_=29,B_=6,J_=[1e3,400,160,60,20],Q_=40}});function vf(e){return`Restored ${e.items_restored??0} item(s). Moved ${e.items_trashed??0} item(s) created after the snapshot to Trash and archived ${e.variables_archived??0} variable(s) added after it.`}var bf,jf,kf,Sf,Af=D({"src/core/restore-preview.ts"(){}}),If={};function xf(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):null}async function $f(e,t){const{data:n,error:r}=await e.rpc("restore_baseline_state",{p_baseline_id:t.baselineId,p_project_id:t.projectId,p_items:[],p_variables:[],p_user_id:t.userId});if(r)throw new Error(r.message);return n}async function Ef(e,t,n){const{data:r,error:a}=await e.from("items").select("id, deleted_at").eq("project_id",t).eq("id",n).maybeSingle();if(a)throw new Error(a.message);if(i=r,!Boolean(i?.id&&null===i.deleted_at))return;var i;const{error:s}=await e.rpc("sync_item_relationships_from_jsonb",{p_project_id:t,p_item_id:n});if(s)throw new Error(s.message)}async function qf(e,t,n){const{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a)return Bs(Ps(a.message));if(!r)return Bs(vs("Project",t));if(r.deleted_at)return Bs(rn());const{data:i,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?Bs(Ps(s.message)):!0!==(i?.feature_flags??{})[n]?Bs(ws(`Feature '${n}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function Of(e){try{const t=await co(),n=await async function(e,t){const{data:n,error:r}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, release_version, release_status").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1}).order("id",{ascending:!1});if(r)throw new Error(`listBaselines: ${r.message}`);return n??[]}(t,e.project_id),r=Math.max(e.offset??0,0),a=Math.min(Math.max(e.limit??50,1),100);return Vs(ys({baselines:n.slice(r,r+a).map(e=>({id:e.id,name:e.name,description:e.description,field_definitions_snapshot:e.field_definitions_snapshot,snapshot_at:e.snapshot_at,created_at:e.created_at,created_by:e.created_by,locked:null!==e.locked_at,locked_at:e.locked_at,release_version:e.release_version,release_status:e.release_status})),total:n.length,offset:r,limit:a},gs(n.length,a,r)))}catch(e){return xf(e)??Bs(Ds(e))}}async function Rf(e){try{const t=await co(),n=await qf(t,e.project_id,"baselines_enabled");if(n)return n;const{data:r,error:a}=await t.rpc("create_baseline",{p_project_id:e.project_id,p_name:e.name.trim(),p_description:e.description??null});return a?"23505"===a.code?Bs(ws(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):Bs(Ds(a)):Vs(ys({id:r.id,name:r.name,description:r.description,field_definitions_snapshot:r.field_definitions_snapshot,snapshot_at:r.snapshot_at,created_at:r.created_at,locked:!1,..."number"==typeof r.change_seq?{change_seq:r.change_seq}:{}}))}catch(e){return xf(e)??Bs(Ds(e))}}async function Tf(e){try{const t=await co(),n=await pd(t,e.baseline_id);if(!n)return Bs(vs("Baseline",e.baseline_id));const r=await qf(t,n.project_id,"baselines_enabled");if(r)return r;if(null!==n.locked_at)return Bs(ws("Baseline is already locked",["Locks are one-way; nothing to do"]));const{data:a}=await t.from("projects").select("org_id").eq("id",n.project_id).maybeSingle();if(!a)return Bs(vs("Project",n.project_id));const{data:i,error:s}=await t.auth.getUser();if(Qe(s))return Bs(Ge());const o=i?.user?.id;if(!o)return Bs(As());const{data:l}=await t.from("org_members").select("role").eq("user_id",o).eq("org_id",a.org_id).maybeSingle();if(!l||"admin"!==l.role)return Bs(ws("Only admins can lock baselines",["Ask an org admin to lock this baseline"]));const{data:c,error:d}=await t.rpc("lock_baseline",{p_baseline_id:e.baseline_id});return d?Bs(Ds(d)):Vs(ys({id:c.id,locked_at:c.locked_at,locked_by:c.locked_by}))}catch(e){return xf(e)??Bs(Ds(e))}}async function Mf(e){try{const t=await co(),[n,r]=await Promise.all([pd(t,e.baseline_a_id),pd(t,e.baseline_b_id)]);if(!n||!r)return Bs(vs("Baseline","one of the baseline_ids"));if(n.project_id!==r.project_id)return Bs(ws("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[a,i]=await Promise.all([_d(t,n.project_id,lc(n.id)),_d(t,r.project_id,lc(r.id))]),s=new Map(a.map(e=>[e.id,e])),o=new Map(i.map(e=>[e.id,e])),l=Array.from(new Set([...s.keys(),...o.keys()])).sort(),c=[];let d=0,u=0,p=0;for(const e of l){const t=s.get(e),n=o.get(e);if(!t&&n)d++,c.push({item_id:e,change_type:"added"});else if(t&&!n)u++,c.push({item_id:e,change_type:"removed"});else if(t&&n){const r=cf(t,n);r.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:r}))}}const m=Math.max(e.offset??0,0),_=Math.min(Math.max(e.limit??50,1),200);let f=c.slice(m,m+_);const h={offset:m,limit:_,total:c.length};if(!0===e.detail){const e=function(e,t,n,r,a={}){const i=a.budget??W_,s=a.diffOf??uf,o=[];let l=0,c=!1,d=!1;for(const r of e){let e=r;if("modified"===r.change_type&&r.fields_changed){const a=t.get(r.item_id),i=n.get(r.item_id);a&&i&&(e={...r,diff:s(a,i,r.fields_changed)})}let a=hf(e);if(l+a>i){if(o.length>0)break;e=gf(e,i),a=hf(e)}e.diff_clipped&&(c=!0),e.diff_omitted&&(d=!0),o.push(e),l+=a}if(o.length===e.length&&!c&&!d)return{items:o,pageInfo:{}};const u={returned:o.length,truncated:!0},p=[];return o.length<e.length&&(u.next_offset=r+o.length,p.push(`Response bounded to ${i} characters of items: returned ${o.length} of the ${e.length} items on this page. Call again with offset=${u.next_offset} for the rest, or omit detail to get only the names of the changed fields.`)),c&&p.push('Long values in an item were clipped to fit, each marked "[clipped, N more characters]".'),d&&p.push("diff_omitted counts the changed fields of an item whose values did not fit; their names are still in fields_changed."),(c||d)&&p.push("Compare the two snapshots in the app to see every value in full."),u.truncation_message=p.join(" "),{items:o,pageInfo:u}}(f,s,o,m);f=e.items,Object.assign(h,e.pageInfo)}return Vs(ys({summary:{added:d,removed:u,modified:p,total_compared:l.length},items:f,page_info:h,baselines:{a:{id:n.id,name:n.name,snapshot_at:n.snapshot_at},b:{id:r.id,name:r.name,snapshot_at:r.snapshot_at}}}))}catch(e){return xf(e)??Bs(Ds(e))}}async function zf(e,t){let n;try{const i=await co(),s=await pd(i,e.baseline_id);if(!s)return Bs(vs("Baseline",e.baseline_id));const o=await qf(i,s.project_id,"baselines_enabled");if(o)return o;const{data:l}=await i.from("projects").select("org_id").eq("id",s.project_id).maybeSingle();if(!l)return Bs(vs("Project",s.project_id));const{data:c,error:d}=await i.auth.getUser();if(Qe(d))return Bs(Ge());const u=c?.user?.id;if(!u)return Bs(As());const{data:p}=await i.from("org_members").select("role").eq("user_id",u).eq("org_id",l.org_id).maybeSingle();if(!p||"admin"!==p.role)return Bs(ws("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const{data:m}=await i.rpc("cc_project_is_controlled",{p_project_id:s.project_id});if(!0===m)return Bs(ws("Change control is on for this project. Release review before restoring a baseline.",["Release review on the project, then run the restore"]));const _=t??await xu(i,s.project_id);if("unreadable"===_)return $u();n=_;const f=await _d(i,s.project_id,lc(s.id)),h=await gc(f.map(e=>e.id),e=>i.from("items").select("*").eq("project_id",s.project_id).in("id",e)),y=function(e,t){const n=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=n.get(e.id),r=[];var a,i;return t?(null!==t.deleted_at&&r.push("deleted_at"),t.type!==e.type&&r.push("type"),t.title!==e.title&&r.push("title"),a=t.data,i=e.data,JSON.stringify(a??{})!==JSON.stringify(i??{})&&r.push("data")):r.push("missing"),0===r.length?[]:[{id:e.id,type:e.type,title:e.title,data:e.data??{},diff_summary:{changed_fields:r,restored:!0},oldData:t?.data??null}]})}(f,h),g=await yc(i,s.project_id,lc(s.id));if(!0!==e.confirm){const e="ops"===_?await xn(i,s.project_id):null,t=function(e){if(e.error)throw new Error(`restore preview counts: ${e.error.message}`);const t=e.data;if(!t||!Number.isInteger(t.items_to_trash)||!Number.isInteger(t.variables_to_archive))throw new Error("restore preview counts: the database answered no counts");return{items_to_trash:t.items_to_trash,variables_to_archive:t.variables_to_archive}}(await i.rpc("restore_baseline_preview_counts",{p_baseline_id:s.id}));return Vs(ys({preview:!0,...null!==e?{source_seq:e,items:y.slice(0,bf).map(e=>({id:e.id,type:e.type,title:e.title,changed_fields:e.diff_summary?.changed_fields??[]})),...y.length>bf?{items_truncated:!0}:{}}:{},items_to_restore:y.length,variables_to_restore:g.length,field_definitions_to_restore:s.field_definitions_snapshot?.length??null,items_to_trash:t.items_to_trash,variables_to_archive:t.variables_to_archive,summary:(r=y.length,a=t,`${r} item(s) will be written back to this snapshot. ${a.items_to_trash} item(s) created after it will be moved to Trash, where they can be restored. ${a.variables_to_archive} variable(s) added after it will be archived. Every revision is kept.`)}))}if("ops"===_)return"number"!=typeof e.source_seq||!Number.isInteger(e.source_seq)||e.source_seq<0?Bs(Ss("source_seq is required to confirm a restore of this project. Run atoms_restore_baseline with confirm false, then send the source_seq it returns together with confirm true.",jf)):await async function(e,t){const n=Date.now();let r=t.bulkId??null,a=t.afterId??null,i=!1;const s={restored:0,trashed:0,variables:0,archived:0,fields:0,total:0},o=[],l=[],c=[];do{const{data:n,error:d}=await e.rpc("restore_baseline_by_ops",{p_baseline_id:t.baselineId,p_project_id:t.projectId,p_source_seq:t.sourceSeq,p_user_id:t.userId,p_bulk_id:r,p_after_id:a,p_batch_size:Sf});if(d)throw Object.assign(new Error(d.message),{code:d.code});const u=n??{};r=u.bulk_id??r,a=u.next_after_id??null,s.restored+=u.items_restored??0,s.trashed+=u.items_trashed??0,s.variables+=u.variables_restored??0,s.archived+=u.variables_archived??0,s.fields+=u.field_definitions_restored??0,s.total=Math.max(s.total,u.total??0),o.push(...u.items_skipped??[]),l.push(...u.variables_skipped??[]),c.push(...Array.isArray(u.not_restored)?u.not_restored:[]),i=!0===u.done}while(!i&&Date.now()-n<kf);const d=vf({items_restored:s.restored,items_trashed:s.trashed,variables_archived:s.archived}),u=o.length>0?` ${o.length} item(s) were left alone because someone changed them after the preview; they are listed in items_skipped.`:"",p=i?d+u:`Restore not finished. ${d}${u} Call atoms_restore_baseline again with confirm true, source_seq ${t.sourceSeq}, bulk_id ${r??""} and after_id ${a??""} to continue.`;return Vs(ys({ok:!0,complete:i,bulk_id:r,...i?{}:{next_after_id:a},items_restored:s.restored,variables_restored:s.variables,field_definitions_restored:s.fields,items_trashed:s.trashed,variables_archived:s.archived,items_skipped:o,...l.length>0?{variables_skipped:l}:{},not_restored:c,progress:{items_restored:s.restored,items_total:s.total||null},summary:p}))}(i,{baselineId:s.id,projectId:s.project_id,userId:u,sourceSeq:e.source_seq,bulkId:e.bulk_id,afterId:e.after_id});const w=await $f(i,{baselineId:s.id,projectId:s.project_id,userId:u});return Vs(ys({ok:!0,items_restored:w.items_restored,variables_restored:w.variables_restored,field_definitions_restored:w.field_definitions.length,items_trashed:w.items_trashed,variables_archived:w.variables_archived,summary:vf(w)}))}catch(r){const a=Ou(n,t,r);return a?zf(e,a):xf(r)??Bs(Ds(r))}var r,a}H(If,{RESTORE_CALL_BUDGET_MS:()=>kf,createBaselineHandler:()=>Rf,diffBaselinesHandler:()=>Mf,listBaselinesHandler:()=>Of,lockBaselineHandler:()=>Tf,restoreBaselineHandler:()=>zf,restoreBaselineStateAtomicallyViaMain:()=>$f,syncRestoredItemRelationships:()=>Ef});var Cf,Df,Hf,Uf,Pf=D({"src/tools/baselines.ts"(){ko(),gr(),Nu(),Ze(),ey(),Ks(),hd(),sd(),wf(),Af(),jc(),bf=200,jf=400,kf=2e4,Sf=200}});function Nf(e){return"string"==typeof e}function Lf(e,t){if(null==e)return{ok:!0,value:{state:"draft",by:null,on:null,count:0,history:[]}};if("object"!=typeof e||Array.isArray(e))return{ok:!1,error:`${t}.acceptance must be an object`};const n=e;return{ok:!0,value:{state:"accepted"===n.state?"accepted":"draft",by:Nf(n.by)?n.by:null,on:Nf(n.on)?n.on:null,count:"number"==typeof n.count&&Number.isFinite(n.count)?n.count:0,history:Array.isArray(n.history)?n.history.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({by:Nf(e.by)?e.by:"",on:Nf(e.on)?e.on:"",count:"number"==typeof e.count&&Number.isFinite(e.count)?e.count:0})):[]}}}function Ff(e){if(null==e)return{ok:!0,value:[]};if(!Array.isArray(e))return{ok:!1,error:"scenario_catalogs must be an array of catalogs"};if(e.length>Hf)return{ok:!1,error:`scenario_catalogs accepts at most ${Hf} catalogs`};const t=[],n=new Set;for(const r of e){if("object"!=typeof r||null===r||Array.isArray(r))return{ok:!1,error:"each catalog must be an object"};const e=r;if(!Nf(e.id)||!e.id.trim())return{ok:!1,error:"each catalog must carry a non-empty id"};if(n.has(e.id))return{ok:!1,error:`duplicate catalog id "${e.id}"`};if(n.add(e.id),!Nf(e.name)||!e.name.trim())return{ok:!1,error:`catalog "${e.id}" must carry a non-empty name`};if(e.name.length>Df)return{ok:!1,error:`catalog "${e.id}" name must be at most ${Df} characters`};if(!Array.isArray(e.entries))return{ok:!1,error:`catalog "${e.id}" entries must be an array`};if(e.entries.length>Cf)return{ok:!1,error:`catalog "${e.id}" accepts at most ${Cf} entries`};const a=[],i=new Set;for(const t of e.entries){if("object"!=typeof t||null===t||Array.isArray(t))return{ok:!1,error:`an entry of catalog "${e.id}" must be an object`};const n=t;if(!Nf(n.id)||!n.id.trim())return{ok:!1,error:`an entry of catalog "${e.id}" must carry a non-empty id`};if(i.has(n.id))return{ok:!1,error:`duplicate entry id "${n.id}" in catalog "${e.id}"`};i.add(n.id);const r=Nf(n.text)?n.text.trim():"";if(!r)return{ok:!1,error:`an entry of catalog "${e.id}" must carry non-empty text`};if(r.length>Df)return{ok:!1,error:`an entry of catalog "${e.id}" must be at most ${Df} characters`};const s=Array.isArray(n.function_tags)?n.function_tags.filter(Nf).map(e=>e.trim()).filter(Boolean):[];a.push({id:n.id,text:r,function_tags:s})}const s=Lf(e.acceptance,`catalog "${e.id}"`);if(!s.ok)return s;t.push({id:e.id,name:e.name.trim(),entries:a,acceptance:s.value})}return{ok:!0,value:t}}var Wf,Vf,Bf,Jf,Qf=D({"src/core/catalogs.ts"(){Cf=50,Df=100,Hf=200,Uf=["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]}});function Gf(e){const t=Wf[e];return[...t.top,...t.other]}var Kf,Yf=D({"src/core/analysis-industry.ts"(){Wf={automotive:{top:["iso26262","design"],other:[]},medical:{top:["iso14971","tir57","process"],other:["software","use"]}},Vf={iso26262:"HARA (ISO 26262)",iso14971:"Risk analysis (ISO 14971)",tir57:"Security risk analysis (AAMI TIR57)",design:"DFMEA",process:"PFMEA",software:"Software FMEA",use:"Use FMEA"},Bf={automotive:"Automotive (ISO 26262)",medical:"Medical device (ISO 14971)"},Jf=Object.keys(Vf)}}),Zf={};function Xf(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}function eh(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function th(e){const t=e?.relationships?.verified_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function nh(e){return JSON.parse(JSON.stringify(e??{}))}async function rh(e,t,n,r=!1){const a=[];for(const e of n){const t=(e??"").trim();t&&null===ni(t,a)&&a.push(t)}if(0===a.length)return{names:a,unregistered:[]};const{data:i,error:s}=await e.from("metadata").select("domains, function_tags").eq("project_id",t).maybeSingle();if(s)throw new Error(`metadata read failed: ${s.message}`);const o=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],l=o(i?.domains),c=o(i?.function_tags),d=a.filter(e=>null===ni(e,l)&&null===ni(e,c)),u=d.length>0?await async function(e,t,n){const r=[];for(const e of n){const t=(e??"").trim();t&&null===ni(t,r)&&r.push(t)}if(0===r.length)return[];const a=await Ri(e,t),i=[];for(const e of r){const t=ni(e,a);null!==t&&i.push(t)}return i}(e,t,d):[],p=function(e,t,n,r=[]){const a=[];for(const i of e){if(null!==ni(i,n))continue;const e=ni(i,t)??ni(i,r);null!==e&&null===ni(e,a)&&a.push(e)}return a}(a,l,c,u);if(p.length>0)throw new $i(p,p.filter(e=>null===ni(e,l)));const m=a.map(e=>ni(e,l)??e),_=m.filter(e=>null===ni(e,c));return r?async function(e,t,n,r){if(0===r.length)return{names:n,unregistered:[]};const a=r.map(e=>({op_id:Qn(),kind:"add",item_id:null,path:["taxonomy","functions"],value:e}));try{const i=await Eu({client:e,projectId:t,ops:a}),s=i.answers.find(e=>"invalid"===e.status&&"domain_not_function"===e.reason);if(s){const e=Array.isArray(s.names)?s.names.filter(e=>"string"==typeof e):r;throw new $i(e,[])}const o=new Map(i.answers.map(e=>[e.op_id,e]));return{names:n,unregistered:r.filter((e,t)=>{const n=o.get(a[t].op_id);return!n||!["applied","noop","replaced"].includes(n.status)})}}catch(e){if(null!==Ti(e))throw e;return process.stderr.write(`[atoms-mcp] Warning: function tag registration failed: ${e instanceof Error?e.message:String(e)}\n`),{names:n,unregistered:r}}}(e,t,m,_):await(async()=>{try{const{error:n}=await e.rpc("mutate_project_domains",{p_project_id:t,p_action:"add_functions",p_values:m});if(n){const e=function(e,t){const n=e;if(!n||"22023"!==n.code||n.hint!==xi)return null;let r=[];if("string"==typeof n.details)try{const e=JSON.parse(n.details);Array.isArray(e)&&(r=e.filter(e=>"string"==typeof e))}catch{}return new $i(r.length>0?r:t)}(n,m);if(e)throw e;return process.stderr.write(`[atoms-mcp] Warning: function tag registration failed: ${n.message}\n`),{names:m,unregistered:_}}return{names:m,unregistered:[]}}catch(e){if(null!==Ti(e))throw e;return process.stderr.write(`[atoms-mcp] Warning: function tag registration failed: ${e instanceof Error?e.message:String(e)}\n`),{names:m,unregistered:_}}})()}async function ah(e,t,n,r,a,i=!1){if("hara"!==n||"string"!=typeof a.source_function||!a.source_function.trim())return[];const s=r?.analysis_props?.source_function;if("string"==typeof s&&null!==ni(a.source_function,[s]))return a.source_function=s,[];const o=await rh(e,t,[a.source_function],i);return o.names[0]&&(a.source_function=o.names[0]),o.unregistered}async function ih(e,t){const{data:n,error:r}=await e.from("metadata").select("industry").eq("project_id",t).maybeSingle();if(r)throw new Error(r.message);return a=n,i=a?.industry,"automotive"===i||"medical"===i?a.industry:null;var a,i}function sh(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}async function oh(e,t,n,r){const a=function(e){const t=e?.analysis_props?.variant;return"iso26262"===(n=t)||"iso14971"===n||"tir57"===n||"design"===n||"process"===n||"software"===n||"use"===n?t:null;var n}(r);return{variant:a,schemeId:Ca(n,a,a?null:await ih(e,t))}}async function lh(e,t,n,r){const a=sh(r),i=a?await dd(e,t,a):null;return oh(e,t,n,i?.data)}function ch(e,t,n,r={}){const a=r.where?`${r.where}: `:"",i=new Set([...na[e],...r.extraKeys??[]]),s=Object.keys(n??{});if(0===s.length)return{ok:!1,message:`${a}fields must contain at least one key`};const o=s.filter(e=>xa.includes(e));if(o.length>0)return{ok:!1,message:`${a}${mi(e,o)}`};const l=_i(e);if(l&&s.includes(l.field))return{ok:!1,message:`${a}${fi(e)}`};const c=s.filter(e=>!i.has(e));if(c.length>0)return{ok:!1,message:`${a}Unknown field(s) for ${e}: ${c.join(", ")}. Allowed: ${[...i].sort().join(", ")}`};const d=ta[e],u={};for(const t of s){const r=n[t];if(d[t]){const n="number"==typeof r?String(r):r;if("string"!=typeof n||!d[t].includes(n))return{ok:!1,message:`${a}Invalid ${t} value ${JSON.stringify(r)} for ${e}. Allowed: ${d[t].join(", ")}`};u[t]=n}else{if("string"!=typeof r)return{ok:!1,message:`${a}Field '${t}' must be a string`};u[t]=r}}return{ok:!0,writes:u}}async function dh(e,t){let n;try{const a=await co(),i=_o();try{await wo(a,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const s=t??await xu(a,e.project_id);if("unreadable"===s)return $u();n=s;const o="string"==typeof(r=e.subtype)&&Object.prototype.hasOwnProperty.call(_a,r)?_a[r]:null;if(!o)return Bs(Ss(function(e){return`subtype must be one of: ${fa.join(", ")} (got ${JSON.stringify(e)})`}(e.subtype)));const l=e.source_req_ids??[],c=e.source_functions??[];if("hara"===o&&l.length>0)return Bs(Ss("A HARA is seeded from functions, never requirements (a requirement is an output of the analysis): pass source_functions and omit source_req_ids"));if("dfmea"===o&&c.length>0)return Bs(Ss("source_functions applies to hara only; seed a DFMEA with source_req_ids"));if(l.length>50)return Bs(Ss("source_req_ids supports at most 50 entries per call"));if(c.length>50)return Bs(Ss("source_functions supports at most 50 entries per call"));if(l.length>0){const{data:t,error:n}=await a.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null).in("id",l);if(n)throw new Error(n.message);const r=new Map((t??[]).map(e=>[e.id,e])),i=l.filter(e=>!r.has(e));if(i.length>0)return Bs(vs("Source requirement(s)",i.join(", ")));const s=l.filter(e=>{const t=r.get(e);return"requirement"!==t.type||Kf.has(t.data?.req_type)});if(s.length>0)return Bs(Ss(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${s.join(", ")}`))}if(void 0!==e.variant&&!Ka(e.subtype).includes(e.variant))return Bs(Ss(function(e,t){const n=Ka(e),r="risk_analysis"===e||"hazard_analysis"===e?"a risk analysis (ISO 14971)":"security_risk"===e?"a security risk analysis (AAMI TIR57)":"fmea"===e?"an fmea":`a ${e}`;return`variant must be ${1===n.length?"":"one of: "}${n.join(", ")} for ${r} (got ${JSON.stringify(t)}); the analysis carries its standard, so pick the variant that names it`}(e.subtype,e.variant)));const d=await ih(a,e.project_id),u=e.variant??function(e,t){return"medical"===t?ya[e]:ha[e]}(e.subtype,d),p=await async function(e,t,n,r){const a=n??"automotive";return Gf(a).includes(r)||"automotive"===a&&await async function(e,t,n){const r=function(e){const t=Gf(e);return Jf.filter(e=>!t.includes(e))}(n),{data:a,error:i}=await e.from("items").select("id, variant:data->analysis_props->>variant").eq("project_id",t).eq("type","analysis").is("deleted_at",null).filter("data->analysis_props->>variant","in",`(${r.join(",")})`).limit(1);if(i)throw new Error(`analysis variant read failed: ${i.message}`);return(a??[]).some(e=>"string"==typeof e.variant&&r.includes(e.variant))}(e,t,a)?null:function(e,t){return`Cannot create a ${Vf[t]}: this project's industry is ${Bf[e]}, which offers ${function(e){const t=e.map(e=>Vf[e]);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}(Gf(e))}. Analyses already in the project keep working. Create one of the offered analyses instead, or change the industry on the project settings page (allowed while no analysis in the project would end up outside the new industry).`}(a,r)}(a,e.project_id,d,u);if(p)return Bs(Ss(p,os));const m=Ca(o,u),_=Da(m),f=La(m),h={},y=[];for(const t of[...ra,...la]){const n=e[t];"string"==typeof n&&""!==n&&(y.push(t),f.includes(t)&&(h[t]=Ls(n)))}const g=y.filter(e=>!f.includes(e));if(g.length>0)return Bs(Ss(Qa(m,g)));const w="hara"===o?await rh(a,e.project_id,c,"ops"===s):null,v=w?w.names:l;if("ops"===s)return await async function(e){const{client:t,projectId:n,subtype:r,schemeId:a,seeds:i}=e,s=da[r],o=pa[a],l=ua[a],c={analysis:{subtype:r,scheme:a,revision:e.revision,...e.schemeStandard?{standard:e.schemeStandard}:{}},analysis_props:{variant:e.variant,...e.scopeInput}},d="hara"===r?"source_function":"source_req",u=[nr({type:"analysis",title:e.title,fields:c}),...i.map(e=>nr({type:"requirement",title:"",req_type:s,fields:{[d]:e}}))],p=await zu({projectId:n,tool:"atoms_create_analysis",key:e.key,contents:u}),m=await mr(t,n,[...p.create,...p.link.slice(1)]),_={};m.has(p.create[0])||(_[o]=1);const f=p.create.slice(1).filter(e=>!m.has(e)).length;f>0&&(_[l]=(_[l]??0)+f);const h=Object.keys(_).length>0?Su(await Au(t,n,_)):null,y=m.get(p.create[0])?.item_id??h(o),g=p.create.slice(1).map(e=>m.get(e)?.item_id??h(l)),w=[{op_id:p.create[0],kind:"create_item",item_id:y,path:[],value:{type:"analysis",title:e.title,data:{body:"",...c}}}];i.forEach((e,t)=>{w.push({op_id:p.create[t+1],kind:"create_item",item_id:g[t],path:[],value:{type:"requirement",title:"",data:{body:"",req_type:s,analysis_props:"hara"===r?{source_req:null,source_function:e,approved:!1,approved_at:null,field_source:{}}:{source_req:e,approved:!1,approved_at:null,field_source:{}}}}})}),g.forEach((e,t)=>{w.push({op_id:p.link[t+1],kind:"add",item_id:y,path:["relationships","children"],value:e})});const v=await Eu({client:t,projectId:n,ops:w,preFound:m,labels:ph(a)}),b=p.create.map(e=>v.answers.find(t=>t.op_id===e)),j=await Cu(t,n,b.filter(e=>!!e)),k=b[0]?.item_id??y,S=i.map((e,t)=>{const n=b[t+1]?.item_id??g[t];return{..."hara"===r?{id:n,source_function:e}:{id:n,source_req:e},...j.get(n)?{base_token:j.get(n)}:{}}});return qu(v.outcome,{id:k,subtype:r,title:e.title,revision:e.revision,scheme:a,variant:e.variant,labels:hi(a),...e.schemeStandard?{standard:e.schemeStandard}:{},...j.get(k)?{base_token:j.get(k)}:{},rows:S,...v.outcome.replayed?{message:Yt}:{},...Ci(e.unregistered)},v.chunks)}({client:a,projectId:e.project_id,userId:i,subtype:o,schemeId:m,variant:u,schemeStandard:_,scopeInput:h,seeds:v,title:e.title??`New ${hi(m).parent}`,revision:e.revision??"1.0",key:e.idempotency_key,unregistered:w?.unregistered??[]});const b=async()=>{const t=pa[m],n=ua[m],r={[t]:1};r[n]=(r[n]??0)+v.length;const s=Su(await Au(a,e.project_id,r)),l=s(t),c=`New ${hi(m).parent}`,d=e.title??c,p=e.revision??"1.0",f=da[o],y=(new Date).toISOString(),g={id:l,type:"analysis",title:d,body:"",tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis:{subtype:o,scheme:m,revision:p,..._?{standard:_}:{}},analysis_props:{variant:u,...h},metadata:{created_at:y,created_by:i,updated_at:y,updated_by:i}},{error:b}=await a.rpc("save_item_with_revision",{p_item_id:l,p_project_id:e.project_id,p_type:"analysis",p_title:d,p_data:g,p_user_id:i,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null});if(b)throw new Error(b.message);const j=(e,t)=>"hara"===o?{id:e,source_function:t}:{id:e,source_req:t},k=[],S=[];for(const t of v){const r=s(n),c={id:r,type:"requirement",title:"",body:"",req_type:f,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[l],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:"hara"===o?{source_req:null,source_function:t,approved:!1,approved_at:null,field_source:{}}:{source_req:t,approved:!1,approved_at:null,field_source:{}},metadata:{created_at:y,created_by:i,updated_at:y,updated_by:i}},{error:d}=await a.rpc("save_item_with_revision",{p_item_id:r,p_project_id:e.project_id,p_type:"requirement",p_title:"",p_data:c,p_user_id:i,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null});if(d)throw new Error(d.message);const{error:u}=await a.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r,p_to_id:l,p_type:"parent",p_action:"add",p_user_id:i,p_event_source:"mcp"});u&&(process.stderr.write(`[atoms-mcp] Warning: analysis row parent link sync failed for ${r}: ${u.message}\n`),S.push({row_id:r,..."hara"===o?{source_function:t}:{source_req:t},message:u.message})),await a.from("change_history").insert({item_id:r,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:c,actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),k.push(j(r,t))}return await a.from("change_history").insert({item_id:l,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:g,actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Vs(ys({id:l,subtype:o,title:d,revision:p,scheme:m,variant:u,labels:hi(m),..._?{standard:_}:{},rows:k,...Ci(w?.unregistered??[]),...S.length>0?{link_warnings:S,warning:`${S.length} row(s) were created but could not be attached to the analysis and will not appear in atoms_get_analysis. Repair: for each row in link_warnings, call atoms_link_items with type 'parent', from_id=<row id>, to_id=${l}.`}:{}}))};return await b()}catch(r){const a=Ou(n,t,r);return a?dh(e,a):Bs(Ds(r))}var r}function uh(e){for(const t of Object.keys(e)){const n=e[t];"string"==typeof n&&(e[t]=Ls(n))}}function ph(e){const t=new Map(Ya(e).map(e=>[e.key,e.label]));return{analysisLabel:e=>t.get(e)??null}}function mh(e,t){const n=[];for(const[r,a]of Object.entries(t))"effect"===r?n.push({path:["body"],value:a}):"title"===r?n.push({path:["title"],value:a}):(n.push({path:["analysis_props",r],value:a}),"failure_mode"!==r||"dfmea"!==e||"title"in t||n.push({path:["title"],value:a}));return n}async function _h(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const s=await dd(r,e.project_id,e.row_id);if(!s)return Bs(vs("Analysis row",e.row_id));const o=s.data;if("analysis"===s.type)return async function(e,t,n,r,a,i,s){const{schemeId:o}=await oh(e,n,function(e){return"dfmea"===e?.analysis?.subtype?"dfmea":"hara"}(a),a),l=function(e,t){const n=La(e),r=Object.keys(t??{});if(0===r.length)return{ok:!1,message:"fields must contain at least one key"};const a=r.filter(e=>{return t=e,qr.includes(t)||Or.includes(t);var t});if(a.length>0)return{ok:!1,message:Mr(a)};const i=r.filter(e=>!n.includes(e));if(i.length>0)return{ok:!1,message:Qa(e,i)};const s={};for(const n of r){const r=t[n];if("lifecycle_sources"===n){let e=r;if("string"==typeof r)try{e=JSON.parse(r)}catch{return{ok:!1,message:"Field 'lifecycle_sources' must be a JSON array of [name, considered, note] tuples"}}if(!Array.isArray(e)||!e.every(e=>Array.isArray(e)&&3===e.length&&"string"==typeof e[0]&&"boolean"==typeof e[1]&&"string"==typeof e[2]))return{ok:!1,message:"Field 'lifecycle_sources' must be an array of [name, considered, note] tuples"};s[n]=e;continue}if("string"!=typeof r)return{ok:!1,message:`Field '${n}' must be a string`};const a=Fa(e);if("overall_residual_risk"===n&&""!==r&&!a.includes(r))return{ok:!1,message:Ga(n,r,a)};if("software_safety_class"===n&&""!==r&&!oa.includes(r))return{ok:!1,message:Ga(n,r,oa)};s[n]=r}return{ok:!0,writes:s}}(o,i);if(!l.ok)return Bs(Ss(l.message));const c=l.writes;if(uh(c),s){const{ops:t,refusals:i}=await Mu({client:e,projectId:n,itemId:r.id,tokens:s.tokens,cells:Object.entries(c).map(([e,t])=>({path:["analysis_props",e],value:t}))}),l=await Eu({client:e,projectId:n,ops:t,refusals:i,labels:ph(o)}),d={...a.analysis_props??{},...c};return qu(l.outcome,{analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:Va(d),overall:Ba(d)},l.chunks)}return await(async()=>{const i=nh(a);i.analysis_props&&"object"==typeof i.analysis_props||(i.analysis_props={});const s=i.analysis_props;for(const[e,t]of Object.entries(c))s[e]=t;const l=(new Date).toISOString();i.metadata={...i.metadata??{},updated_at:l,updated_by:t};const{data:d,error:u}=await e.rpc("save_item_with_revision",{p_item_id:r.id,p_project_id:n,p_type:r.type,p_title:r.title,p_data:i,p_user_id:t,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:r.updated_at});if(u)throw new Error(u.message);return d?(await e.from("change_history").insert({item_id:r.id,project_id:n,changed_by:t,event_type:"updated",old_data:a,new_data:i,actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Vs(ys({analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:Va(s),overall:Ba(s)}))):Bs(ws(`Fill silently failed for '${r.id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]))})()}(r,a,e.project_id,s,o,e.fields??{},"ops"===i?{tokens:Ru(e.base_token)}:void 0);const l=Xf(o?.req_type);if(!l)return Bs(Ss(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const{schemeId:c}=await lh(r,e.project_id,l,o),d=ch(c,0,e.fields??{},{extraKeys:"hara"===l?["effect","title"]:["effect"]});if(!d.ok)return Bs(Ss(d.message));const u=d.writes;uh(u);const p=await ah(r,e.project_id,l,o,u,"ops"===i),m=o?.analysis_props??null;if("ops"===i){const{ops:t,refusals:n}=await Mu({client:r,projectId:e.project_id,itemId:s.id,tokens:Ru(e.base_token),cells:mh(l,u)}),a=await Eu({client:r,projectId:e.project_id,ops:t,refusals:n,labels:ph(c)}),i={...m??{}};for(const[e,t]of Object.entries(u))"effect"!==e&&"title"!==e&&(i[e]=t);const o=ki({...i}),d=di(c,i),_=0===a.outcome.not_applied.length&&"hara_iso26262"===c?await async function(e,t,n){const r=n.data,a=new Map;for(const n of eh(r)){const r=await dd(e,t,n);r&&a.set(n,r)}const i=await Mc(e,t,{id:n.id,type:n.type,data:r},[...a.values()]),s=[];for(const r of i){const a=await dd(e,t,r);a?.data?.asil_source===n.id&&s.push(r)}return s}(r,e.project_id,s):[];return qu(a.outcome,{row_id:s.id,subtype:l,written_fields:Object.keys(u),computed_level:d,..."hara_iso26262"===c?{asil_propagated_to:_}:{},...o?{approval_cleared:!0}:{},acceptance_revoked:Tu(a.answers),...Ci(p)},a.chunks)}const _=async()=>{const t=nh(o);t.analysis_props&&"object"==typeof t.analysis_props||(t.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const n=t.analysis_props;n.field_source&&"object"==typeof n.field_source||(n.field_source={});let i=s.title;for(const[e,r]of Object.entries(u))"effect"===e?t.body=r:"title"===e?(t.title=r,i=r):(n[e]=r,"failure_mode"===e&&"dfmea"===l&&(t.title=r,i=r)),n.field_source[e]="mcp";const d=ki(n),_=(new Date).toISOString();t.metadata={...t.metadata??{},updated_at:_,updated_by:a};const{data:f,error:h}=await r.rpc("save_item_with_revision",{p_item_id:s.id,p_project_id:e.project_id,p_type:s.type,p_title:i,p_data:t,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(h)throw new Error(h.message);if(!f)return Bs(ws(`Fill silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await r.from("change_history").insert({item_id:s.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:o,new_data:t,actor:Zh(),session_id:Yh(),...d?{reason:`${Object.keys(u).join(", ")} written through atoms_fill_row; approval cleared (a signature never covers content the approver did not see)`}:{}}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=sh(o),g=y?await Ur(y,"The row was",{readParent:()=>dd(r,e.project_id,y),saveParent:(t,n)=>_p(()=>r.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:n,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at})),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},w=g.revoked,v=di(c,n),b=[];if("hara_iso26262"===c){const n=di(c,m);if(v!==Br&&v!==n){const n=new Map;for(const a of eh(t)){const t=await dd(r,e.project_id,a);t&&n.set(a,t)}const i=await Mc(r,e.project_id,{id:s.id,type:s.type,data:t},[...n.values()]);for(const t of i){const i=n.get(t)??await dd(r,e.project_id,t);if(!i)continue;const o=i.data;if(o?.asil===v&&o?.asil_source===s.id)continue;const l=o?.asil??null,c=o?.asil_source??null,d=nh(o);d.asil=v,d.asil_source=s.id,d.metadata={...d.metadata??{},updated_at:_,updated_by:a};const{error:u}=await r.rpc("save_item_with_revision",{p_item_id:i.id,p_project_id:e.project_id,p_type:i.type,p_title:i.title,p_data:d,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});if(u)throw new Error(u.message);await r.from("change_history").insert({item_id:i.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{asil:l,asil_source:c},new_data:{asil:v,asil_source:s.id},actor:Zh(),session_id:Yh(),reason:`ASIL propagated from ${s.id} (rating change via atoms_fill_row)`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),b.push(t)}}}return Vs(ys({row_id:s.id,subtype:l,written_fields:Object.keys(u),computed_level:v,...b.length>0?{asil_propagated_to:b}:{},...d?{approval_cleared:!0}:{},acceptance_revoked:w,...g.warning?{warning:g.warning}:{},...Ci(p)}))};return await _()}catch(r){const a=Ou(n,t,r);return a?_h(e,a):Bs(Ds(r))}}function fh(e){const t=e??{},n=String(t.threat_model_method??"").trim(),r=e=>String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e),a=Array.isArray(t.lifecycle_sources)?t.lifecycle_sources.filter(e=>Array.isArray(e)&&3===e.length&&"string"==typeof e[0]&&"boolean"==typeof e[1]&&"string"==typeof e[2]).map(([e,t,n])=>({name:e,considered:t,note:n})):[];return{stated:""!==n,method:n,rationale:String(t.threat_model_rationale??"").trim(),environment_assumptions:r(t.environment_assumptions),attack_surfaces:r(t.attack_surfaces),lifecycle_sources:a,related_documents:String(t.related_documents??"").trim()}}async function hh(e,t,n,r=!1){const a=await dd(e,t,n);if(!a)return{ok:!1,result:Bs(vs("Analysis",n))};if("analysis"!==a.type)return{ok:!1,result:Bs(Ss(`Item ${n} is not an analysis (type='${a.type}')`))};const i=a.data,s=Xf("hara"===i?.analysis?.subtype?"safety-goal":"dfmea"===i?.analysis?.subtype?"failure-mode":null);if(!s)return{ok:!1,result:Bs(Ss(`Analysis ${n} is missing a valid analysis.subtype`))};const o=da[s],{variant:l,schemeId:c}=await oh(e,t,s,i),d=Array.isArray(i?.relationships?.children)?i.relationships.children.filter(e=>"string"==typeof e):[],u=r?await An(e,t,[a.id,...d]):new Map;let p=[];if(d.length>0){const{data:n,error:r}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",d);if(r)throw new Error(r.message);const a=new Map((n??[]).filter(e=>!e.deleted_at&&d.includes(e.id)&&e.data?.req_type===o).map(e=>[e.id,e]));p=d.map(e=>a.get(e)).filter(e=>Boolean(e))}const m=new Set;for(const e of p){const t=e.data?.analysis_props??{};"string"==typeof t.source_req&&t.source_req&&m.add(t.source_req);for(const t of eh(e.data))m.add(t);for(const t of th(e.data))m.add(t)}const _=new Map;let f=[];if(m.size>0){const{data:n,error:r}=await e.from("items").select(Sc).eq("project_id",t).is("deleted_at",null).in("id",[...m]);if(r)throw new Error(r.message);f=n??[];for(const e of f)_.set(e.id,e.updated_at)}const h=p.length>0?Tc(p,[...f,...await Rc(e,t)]):new Map,y=p.map(e=>{const t=e.data?.analysis_props??{},n=h.get(e.id)??[],r=eh(e.data).filter(e=>_.has(e)),a=th(e.data).filter(e=>_.has(e)),i=n.length>0,s=di(c,t),o=function(e,t,n){if(n)return null;if("hara_iso26262"===e){const e=ri(t);return"QM"!==e&&e!==Br?`asil ${e} unmitigated`:null}if("hazard_iso14971"===e){const e=si(t);return"Low"!==e&&e!==Br?`${e.toLowerCase()} risk uncontrolled`:null}if("security_tir57"===e){const e=li(t);return Er(e)?`${e.toLowerCase()} security risk uncontrolled`:null}const r=parseInt(di(e,t),10),a=parseInt(t?.severity||"",10);return!Number.isNaN(r)&&r>=100?"rpn >= 100":!Number.isNaN(a)&&a>=9?"severity >= 9":null}(c,t,i),l={id:e.id,title:"string"==typeof e.title?e.title:"",source_req:"string"==typeof t.source_req?t.source_req:null,effect:"string"==typeof e.data?.body?e.data.body:"",computed_level:s,computed_level_text:ei(c,s),is_gap:null!==o,gap_rule:o,is_critical:ui(c,t,i),is_stale:pi(t,r,e=>_.get(e)??null),mitigated_by:n,link_roles:t.link_roles??{},approved:!0===t.approved,approved_at:t.approved_at??null,approved_by:t.approved_by??null,approved_note:"string"==typeof t.approved_note?t.approved_note:"",verified_by:a,residual_level:"hazard_iso14971"===c?oi(t):"security_tir57"===c?ci(t):null,mitigation_types:t.mitigation_types??{},mcp_fields:Object.entries(t.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort()};for(const e of na[c])l[e]=t[e]??null;return l});return{ok:!0,analysis:{id:a.id,title:"string"==typeof a.title?a.title:"",subtype:s,scheme:c,revision:"string"==typeof i?.analysis?.revision?i.analysis.revision:"1.0",standard:"string"==typeof i?.analysis?.standard?i.analysis.standard:Da(c)??null,variant:l,labels:hi(c),acceptability:Xa(c),definitions:Za(c),control_types:gi(c),field_labels:Ya(c),scope:La(c).length>0?Va(i?.analysis_props):null,overall:La(c).length>0?Ba(i?.analysis_props,Fa(c)):null,threat_model:"security_tir57"===c?fh(i?.analysis_props):null,acceptance:Cr(i?.analysis_props)},schemeId:c,parentProps:i?.analysis_props??null,revisions:u,rows:y,counts:{rows:y.length,gaps:y.filter(e=>e.is_gap).length,critical:y.filter(e=>e.is_critical).length,stale:y.filter(e=>e.is_stale).length,approved:y.filter(e=>e.approved).length,linked:y.filter(e=>e.mitigated_by.length>0).length}}}async function yh(e){try{const t=await co(),n=!0===await lr(t,e.project_id),r=await hh(t,e.project_id,e.analysis_id,n);if(!r.ok)return r.result;if(!n)return Vs(ys({analysis:r.analysis,rows:r.rows,counts:r.counts}));const a=async e=>{const t=r.revisions.get(e);return t?vn(t,"analysis"):void 0},i=new Map(Ya(r.schemeId).map(e=>[e.key,e.label])),s=await $n(t,e.project_id,[r.analysis.id,...r.rows.map(e=>e.id)],{analysisLabel:e=>i.get(e)??null}),o=await a(r.analysis.id),l=await Promise.all(r.rows.map(async e=>{const t=await a(e.id);return{...e,...t?{base_token:t}:{},editing_now:s.get(e.id)??[]}}));return Vs(ys({analysis:{...r.analysis,...o?{base_token:o}:{},editing_now:s.get(r.analysis.id)??[]},rows:l,counts:r.counts}))}catch(e){return Bs(Ds(e))}}async function gh(e,t,n,r){const a=sh(n);if(!a)return;const i=await dd(e,t,a);if(!i)return;const{revoked:s,parentProps:o}=Hr(i.data);if(!s)return;const l={...i.data,analysis_props:o},{error:c}=await e.rpc("save_item_with_revision",{p_item_id:i.id,p_project_id:t,p_type:i.type,p_title:i.title,p_data:l,p_user_id:r,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});c&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${i.id}': ${c.message}\n`)}async function wh(e,t){let n;try{const i=await co(),s=_o();try{await wo(i,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const o=t??await xu(i,e.project_id);if("unreadable"===o)return $u();if(n=o,e.row_id===e.req_id)return Bs(Ss("row_id and req_id must be different items"));const l=await dd(i,e.project_id,e.row_id);if(!l)return Bs(vs("Analysis row",e.row_id));const c=l.data,d=Xf(c?.req_type);if(!d)return Bs(Ss(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const u=await dd(i,e.project_id,e.req_id);if(!u)return Bs(vs("Requirement",e.req_id));const p=u.data;if("remove"===e.action){if(void 0!==e.role||void 0!==e.control_type||void 0!==e.override)return Bs(Ss(Ac));if(!function(e,t,n,r){const a=(e,t)=>e?.relationships?.[t],i=(e,t)=>Array.isArray(e)&&e.includes(t);return i(a(t,"mitigated_by"),n)||i(a(r,"mitigates"),e)}(e.row_id,c,e.req_id,p))return Bs(Ss(`${r=e.row_id} is not linked to ${a=e.req_id}: neither ${r}'s mitigated_by nor ${a}'s mitigates names the other, so there is nothing to remove and nothing was changed.`,os));const{schemeId:t}=await lh(i,e.project_id,d,c);if("ops"===o){const n={op_id:Qn(),kind:"remove",item_id:e.row_id,path:["relationships","mitigated_by"],value:e.req_id},r=await Eu({client:i,projectId:e.project_id,ops:[n],labels:ph(t)});return qu(r.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,acceptance_revoked:Tu(r.answers)},r.chunks)}const n=async()=>{const{error:n}=await i.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:e.row_id,p_to_id:e.req_id,p_type:"mitigated_by",p_action:"remove",p_user_id:s,p_event_source:"mcp",p_expected_from_updated_at:l.updated_at,p_expected_to_updated_at:u.updated_at,p_role:null});if(n)throw new Error(n.message);await i.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:s,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"remove",type:"mitigated_by",from:e.row_id,to:e.req_id}},actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await gh(i,e.project_id,c,s);const r=await dd(i,e.project_id,e.row_id),a=r?.data,o=a?.analysis_props?.mitigation_types;if(r&&a&&o&&"object"==typeof o&&Object.prototype.hasOwnProperty.call(o,e.req_id)){const t=nh(a);delete t.analysis_props.mitigation_types[e.req_id],t.metadata={...t.metadata??{},updated_at:(new Date).toISOString(),updated_by:s};const{error:n}=await i.rpc("save_item_with_revision",{p_item_id:r.id,p_project_id:e.project_id,p_type:r.type,p_title:r.title,p_data:t,p_user_id:s,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:r.updated_at});if(n)throw new Error(n.message)}return Vs(ys({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t}))};return await n()}if("requirement"!==u.type||Kf.has(p?.req_type))return Bs(Ss(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));const{schemeId:m}=await lh(i,e.project_id,d,c);if(function(e){return"hara_iso26262"===e||"hazard_iso14971"===e||"security_tir57"===e}(m)&&p?.req_type!==Fr)return Bs(Ss(function(e,t){return`${e} is not a ${$a[t].mitigating_requirement}: a mitigation target must be a requirement of req_type '${Fr}'. Create or convert one, then link it.`}(e.req_id,m)));const _=yi(m);if(0===_.length&&void 0!==e.control_type)return Bs(Ss(function(e){return`control_type applies to the medical schemes only (ISO 14971 clause 7); ${$a[e].parent} links carry none, so omit it.`}(m)));if(_.length>0&&!e.control_type)return Bs(Ss(wi(m)));if(!(void 0===e.control_type||Ha(e.control_type)&&function(e,t){return yi(e).some(e=>e.id===t)}(m,e.control_type)))return Bs(Ss(wi(m)));if("dfmea"===d&&!e.role)return Bs(Ss(`role is required for dfmea mitigation links. Choose one of: ${Jr.join(", ")}`));if("hara"===d&&e.role)return Bs(Ss("role is not applicable to hara mitigation links; omit it (roles are a dfmea concept)"));if("ops"===o){const t="dfmea"===d?e.role:null,n=t||e.control_type?{id:e.req_id,...t?{role:t}:{},...e.control_type?{control_type:e.control_type}:{}}:e.req_id,r={op_id:Qn(),kind:"add",item_id:e.row_id,path:["relationships","mitigated_by"],value:n},a=await Eu({client:i,projectId:e.project_id,ops:[r],labels:ph(m)});return qu(a.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:t,scheme:m,...e.control_type?{control_type:e.control_type}:{},acceptance_revoked:Tu(a.answers)},a.chunks)}const f=async()=>{let t=Br;if("hara_iso26262"===m){t=di(m,c?.analysis_props);const i=p?.asil;if(t!==Br&&"string"==typeof i&&i.length>0&&i!==t&&!0!==e.override)return Bs((r=t,{...ws(`ASIL conflict: the target requirement already carries asil '${n=i}' but ${a=l.id} computes '${r}'.`,["Pass override=true to apply the HARA value; the override is history-logged like a dialog accept","Or align the row's S/E/C ratings with the existing ASIL before linking"]),details:{code:"asil_conflict",current_value:n,incoming_value:r,source_row:a,hint:"pass override=true to apply the HARA value; the override is history-logged like a dialog accept"}}))}var n,r,a;const o="dfmea"===d?e.role:null,{error:_}=await i.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:e.row_id,p_to_id:e.req_id,p_type:"mitigated_by",p_action:"add",p_user_id:s,p_event_source:"mcp",p_expected_from_updated_at:l.updated_at,p_expected_to_updated_at:u.updated_at,p_role:o});if(_)throw new Error(_.message);let f,h;if(await i.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:s,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"add",type:"mitigated_by",from:e.row_id,to:e.req_id,...o?{role:o}:{}}},actor:Zh(),session_id:Yh()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await gh(i,e.project_id,c,s),e.control_type&&Ha(e.control_type)){const t=await dd(i,e.project_id,e.row_id)??l,n=nh(t.data);n.analysis_props&&"object"==typeof n.analysis_props||(n.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const r=n.analysis_props;r.mitigation_types&&"object"==typeof r.mitigation_types||(r.mitigation_types={}),r.mitigation_types[e.req_id]=e.control_type;const a=(new Date).toISOString();n.metadata={...n.metadata??{},updated_at:a,updated_by:s};const{error:o}=await i.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:n,p_user_id:s,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});if(o)throw new Error(o.message);f=e.control_type}if("hara_iso26262"===m&&t!==Br){const n=await dd(i,e.project_id,e.req_id);if(n){const r=n.data,a=r?.asil??null,o=r?.asil_source??null,c=nh(r);c.asil=t,c.asil_source=l.id;const d=(new Date).toISOString();c.metadata={...c.metadata??{},updated_at:d,updated_by:s};const{error:u}=await i.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:e.project_id,p_type:n.type,p_title:n.title,p_data:c,p_user_id:s,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at});if(u)throw new Error(u.message);await i.from("change_history").insert({item_id:n.id,project_id:e.project_id,changed_by:s,event_type:"updated",old_data:{asil:a,asil_source:o},new_data:{asil:t,asil_source:l.id},actor:Zh(),session_id:Yh(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${a??"unset"}', now '${t}' from ${l.id})`:`ASIL set via atoms_link_mitigation from ${l.id}`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),h=t}}return Vs(ys({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:o,scheme:m,...f?{control_type:f}:{},...h?{asil_written:h}:{}}))};return await f()}catch(r){const a=Ou(n,t,r);return a?wh(e,a):Bs(Ds(r))}var r,a}async function vh(e){try{const n=await co(),r=await hh(n,e.project_id,e.analysis_id);if(!r.ok)return r.result;const a=r.rows.filter(e=>e.is_gap).map(e=>({id:e.id,title:e.title,source_req:e.source_req,source_function:"string"==typeof e.source_function?e.source_function:null,computed_level:e.computed_level,rule:e.gap_rule})),i=Ua(await async function(e,t){const{data:n,error:r}=await e.from("metadata").select("levels").eq("project_id",t).maybeSingle();if(r)throw new Error(r.message);const a=n?.levels;return Array.isArray(a)?a.filter(e=>"string"==typeof e):[]}(n,e.project_id)),s=ji(r.schemeId).some(e=>"requirement"===e.scope)?await async function(e,t,n){const r=(await mc(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null).eq("type","requirement"),tc)).filter(e=>e.data?.req_type===Fr&&function(e,t){const n=Pa(e);return n.length>0&&n===Pa(t)}(e.data?.tags?.level,n));if(0===r.length)return[];const a=e=>{const t=e.data?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]},i=await gc([...new Set(r.flatMap(a))],n=>e.from("items").select("id").eq("project_id",t).is("deleted_at",null).in("id",n)),s=new Set(i.map(e=>e.id));return r.filter(e=>!a(e).some(e=>s.has(e))).map(e=>e.id)}(n,e.project_id,i.level):[],o=r.rows.map(e=>({id:e.id,level:e.computed_level,linked:e.mitigated_by.length>0,verified:e.verified_by.length>0,residualLevel:e.residual_level??Br,severity:vi(e.severity)})),l="hara_iso26262"===r.schemeId&&function(e,t){const n=Array.isArray(e)?e:[];return 0!==n.length&&n.some(e=>{const n=t.find(t=>t.id===e);return!n||"accepted"!==n.acceptance.state})}(r.parentProps?.scenario_catalogs,await async function(e,t){const{data:n,error:r}=await e.from("metadata").select("scenario_catalogs").eq("project_id",t).maybeSingle();if(r)throw new Error(r.message);const a=Ff(n?.scenario_catalogs??[]);return a.ok?a.value:[]}(n,e.project_id)),c=function(e,t,n,r=!1){const a="security_tir57"===n,i=a?String(e?.threat_model_method??"").trim():void 0;return{hasRows:t.length>0,scopeStated:a?""!==i:Ja(e),overallJudged:""!==Ba(e,a?br:sa).residual_risk,everyRowSettled:t.every(e=>e.linked&&e.residualLevel!==Br),catalogsDraft:r,accepted:"accepted"===e?.acceptance_state}}(r.parentProps,o,r.schemeId,l),d=function(e,t,n,r){const a=[];for(const i of ji(e)){if("analysis"===i.scope){if(!r||!i.matchesAnalysis||!i.matchesAnalysis(r))continue;a.push({kind:i.kind,label:i.label(1),rowIds:[],reqIds:[],count:1,fix:i.fix,fixLabel:i.fixLabel});continue}if("requirement"===i.scope){if(0===n.length)continue;a.push({kind:i.kind,label:i.label(n.length),rowIds:[],reqIds:[...n],count:n.length,fix:i.fix,fixLabel:i.fixLabel});continue}const e=i.matches;if(!e)continue;const s=t.filter(t=>e(t)).map(e=>e.id);0!==s.length&&a.push({kind:i.kind,label:i.label(s.length),rowIds:s,reqIds:[],count:s.length,fix:i.fix,fixLabel:i.fixLabel})}return a}(r.schemeId,o,s,c),u=d.map(e=>({kind:e.kind,label:e.label,row_ids:e.rowIds,req_ids:e.reqIds,gap_count:e.count,fix:e.fix,fix_label:e.fixLabel}));return Vs(ys({analysis_id:r.analysis.id,subtype:r.analysis.subtype,scheme:r.analysis.scheme,labels:r.analysis.labels,gaps:a,count:(t=d,t.reduce((e,t)=>e+t.count,0)),gap_kinds:u,system_level:i.level,system_level_source:i.source}))}catch(e){return Bs(Ds(e))}var t}function bh(e){return(e.failure_mode??"").trim()||(e.hazard??"").trim()||""}async function jh(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const s=await dd(r,e.project_id,e.analysis_id);if(!s)return Bs(vs("Analysis",e.analysis_id));if("analysis"!==s.type)return Bs(Ss(`Item ${e.analysis_id} is not an analysis (type='${s.type}')`));const o=s.data,l=o?.analysis?.subtype,c="hara"===l?"hara":"dfmea"===l?"dfmea":null;if(!c)return Bs(Ss(`Analysis ${e.analysis_id} is missing a valid analysis.subtype`));const{variant:d,schemeId:u}=await oh(r,e.project_id,c,o);if("hara"===c&&e.source_req)return Bs(Ss("A risk analysis row is seeded from a function, never a requirement: pass source_function"));if("dfmea"===c&&e.source_function)return Bs(Ss("source_function applies to a risk analysis only; seed an FMEA row with source_req"));const p=Array.isArray(e.rows)?e.rows:[];if(0===p.length)return Bs(Ss("rows must contain at least one drafted row"));if(p.length>Vr)return Bs(Ss(`Propose rows accepts at most ${Vr} rows per call; ${p.length} were sent. Split the proposal and call again.`));const m=[];for(let e=0;e<p.length;e++){const t=ch(u,0,p[e]??{},{extraKeys:"hara"===c?["effect","title"]:["effect"],where:`row ${e+1}`});if(!t.ok)return Bs(Ss(t.message));uh(t.writes),m.push(t.writes)}let _=Ls(e.source_function??"").trim(),f=[];if("hara"===c&&_){const t=await rh(r,e.project_id,[_],"ops"===i);t.names[0]&&(_=t.names[0]),f=t.unregistered}if("ops"===i)return await async function(e){const{client:t,params:n,subtype:r,schemeId:a,validatedRows:i}=e,s=n.project_id,o=da[r],l=ua[a],c=i.map(e=>un({analysis_id:n.analysis_id,writes:tr(e)})),d=await zu({projectId:s,tool:"atoms_propose_rows",key:n.idempotency_key,contents:c}),u=await mr(t,s,[...d.create,...d.link]),p=d.create.filter(e=>!u.has(e)).length,m=p>0?Su(await Au(t,s,{[l]:p})):null,_=d.create.map(e=>u.get(e)?.item_id??m(l)),f=[],h=[];i.forEach((t,a)=>{const i={source_req:"dfmea"===r?n.source_req??null:null,..."hara"===r?{source_function:e.seedFunction||null}:{},approved:!1,approved_at:null,approved_by:null,field_source:{}};let s="",l="";for(const[e,n]of Object.entries(t))"effect"===e?s=n:"title"===e?l=n:(i[e]=n,"failure_mode"===e&&"dfmea"===r&&(l=n)),i.field_source[e]="mcp";l||(l=bh(t)),h.push({writes:t,props:i}),f.push({op_id:d.create[a],kind:"create_item",item_id:_[a],path:[],value:{type:"requirement",title:l,data:{body:s,req_type:o,analysis_props:i}}})}),_.forEach((e,t)=>{f.push({op_id:d.link[t],kind:"add",item_id:n.analysis_id,path:["relationships","children"],value:e})});const y=await Eu({client:t,projectId:s,ops:f,preFound:u,labels:ph(a)}),g=d.create.map(e=>y.answers.find(t=>t.op_id===e)),w=await Cu(t,s,g.filter(e=>!!e)),v=h.map((e,t)=>{const n=g[t]?.item_id??_[t];return{id:n,written_fields:Object.keys(e.writes),computed_level:di(a,e.props),...w.get(n)?{base_token:w.get(n)}:{}}});return qu(y.outcome,{analysis_id:n.analysis_id,subtype:r,scheme:a,...e.variant?{variant:e.variant}:{},labels:hi(a),..."hara"===r?{source_function:e.seedFunction||null}:{source_req:n.source_req??null},rows:v,count:v.length,max_rows:Vr,approved:!1,acceptance_revoked:Tu(y.answers),...y.outcome.replayed?{message:Yt}:{},...Ci(e.unregisteredFunctions)},y.chunks)}({client:r,params:e,parent:s,subtype:c,schemeId:u,variant:d,validatedRows:m,seedFunction:_,unregisteredFunctions:f});const h=async()=>{const t=(new Date).toISOString(),n=da[c],i=[],s=[],o=ua[u],l=Su(await Au(r,e.project_id,{[o]:m.length}));for(const d of m){const p=l(o),m={source_req:"dfmea"===c?e.source_req??null:null,..."hara"===c?{source_function:_||null}:{},approved:!1,approved_at:null,approved_by:null,field_source:{}};let f="",h="";for(const[e,t]of Object.entries(d))"effect"===e?f=t:"title"===e?h=t:(m[e]=t,"failure_mode"===e&&"dfmea"===c&&(h=t)),m.field_source[e]="mcp";h||(h=bh(d));const y={id:p,type:"requirement",title:h,body:f,req_type:n,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[e.analysis_id],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:m,metadata:{created_at:t,created_by:a,updated_at:t,updated_by:a}},{error:g}=await _p(()=>r.rpc("save_item_with_revision",{p_item_id:p,p_project_id:e.project_id,p_type:"requirement",p_title:h,p_data:y,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null}));if(g)throw new Error(g.message);const{error:w}=await _p(()=>r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:p,p_to_id:e.analysis_id,p_type:"parent",p_action:"add",p_user_id:a,p_event_source:"mcp"}));w&&(process.stderr.write(`[atoms-mcp] Warning: proposed row parent link sync failed for ${p}: ${w.message}\n`),s.push({row_id:p,message:w.message})),await r.from("change_history").insert({item_id:p,project_id:e.project_id,changed_by:a,event_type:"created",old_data:null,new_data:y,actor:Zh(),session_id:Yh(),reason:"Row proposed through atoms_propose_rows (machine-proposed, unapproved)"}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),i.push({id:p,written_fields:Object.keys(d),computed_level:di(u,m)})}let p=!1,h=null;if(i.length>0)try{for(let t=0;t<3;t+=1){const n=await dd(r,e.project_id,e.analysis_id);if(!n)break;const i=n.data,{revoked:s,parentProps:o}=Hr(i);if(!s)break;const l={...i,analysis_props:o},{error:c}=await _p(()=>r.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:e.project_id,p_type:n.type,p_title:n.title,p_data:l,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at}));if(!c){p=!0;break}if(!(t<2&&/stale_item_write/i.test(c.message??""))){process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${n.id}': ${c.message}\n`),h=`The rows were saved but ${e.analysis_id} is still accepted: clearing its acceptance failed. Open the analysis and re-accept it, or call atoms_fill_row on a row to clear it.`;break}}}catch(t){process.stderr.write(`[atoms-mcp] Warning: acceptance revoke failed: ${t instanceof Error?t.message:String(t)}\n`),h=`The rows were saved but ${e.analysis_id} is still accepted: clearing its acceptance failed. Open the analysis and re-accept it, or call atoms_fill_row on a row to clear it.`}return Vs(ys({analysis_id:e.analysis_id,subtype:c,scheme:u,...d?{variant:d}:{},labels:hi(u),..."hara"===c?{source_function:_||null}:{source_req:e.source_req??null},rows:i,count:i.length,max_rows:Vr,approved:!1,acceptance_revoked:p,...Ci(f),...s.length>0||null!==h?{...s.length>0?{link_warnings:s}:{},warning:[s.length>0?`${s.length} proposed row(s) were created but could not be attached to ${e.analysis_id}. Repair: call atoms_link_items with type 'parent', from_id=<row id>, to_id=${e.analysis_id}.`:null,h].filter(e=>null!==e).join(" ")}:{}}))};return await h()}catch(r){const a=Ou(n,t,r);return a?jh(e,a):Bs(Ds(r))}}async function kh(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const s=await dd(r,e.project_id,e.row_id);if(!s)return Bs(vs("Analysis row",e.row_id));const o=s.data,l=Xf(o?.req_type);if(!l)return Bs(Ss(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const{schemeId:c}=await lh(r,e.project_id,l,o),d=e.rationale?function(e,t){return ta[e][t]?"hara_iso26262"===e?"severity"===t?"s_rationale":"exposure"===t?"e_rationale":"controllability"===t?"c_rationale":null:"hazard_iso14971"===e?"severity"===t||"residual_s"===t?"s_rationale":"p1"===t||"residual_p1"===t?"p1_rationale":"p2"===t||"residual_p2"===t?"p2_rationale":null:"security_tir57"===e?"severity"===t||"residual_s"===t?"s_rationale":"exploitability"===t||"residual_e"===t?"e_rationale":null:"rationale":null}(c,e.field):null;if(e.rationale&&!d)return Bs(Ss(`rationale applies to a rating field only; ${e.field} is not a rating of ${c}`));const u={[e.field]:e.value};d&&e.rationale&&(u[d]=e.rationale);const p=ch(c,0,u,{extraKeys:"hara"===l?["effect","title"]:["effect"]});if(!p.ok)return Bs(Ss(p.message));const m=p.writes;uh(m);const _=await ah(r,e.project_id,l,o,m,"ops"===i);if("ops"===i){const{ops:t,refusals:n}=await Mu({client:r,projectId:e.project_id,itemId:s.id,tokens:Ru(e.base_token),cells:mh(l,m)}),a=await Eu({client:r,projectId:e.project_id,ops:t,refusals:n,labels:ph(c)}),i={...o?.analysis_props??{}},u={...i.field_source??{}};for(const[e,t]of Object.entries(m))"effect"!==e&&"title"!==e&&(i[e]=t),u[e]="mcp";const p=ki({...i}),f=Object.entries(u).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return qu(a.outcome,{row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(m),...d?{rationale_field:d}:{},...p?{approval_cleared:!0}:{},row:{id:s.id,computed_level:di(c,i),approved:!0===i.approved&&!p,mcp_fields:f,...Object.fromEntries(na[c].map(e=>[e,i[e]??null]))},acceptance_revoked:Tu(a.answers),...Ci(_)},a.chunks)}const f=async()=>{const t=nh(o);t.analysis_props&&"object"==typeof t.analysis_props||(t.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const n=t.analysis_props;n.field_source&&"object"==typeof n.field_source||(n.field_source={});let i=s.title;for(const[e,r]of Object.entries(m))"effect"===e?t.body=r:"title"===e?(t.title=r,i=r):(n[e]=r,"failure_mode"===e&&"dfmea"===l&&(t.title=r,i=r)),n.field_source[e]="mcp";const u=ki(n),p=(new Date).toISOString();t.metadata={...t.metadata??{},updated_at:p,updated_by:a};const{data:f,error:h}=await r.rpc("save_item_with_revision",{p_item_id:s.id,p_project_id:e.project_id,p_type:s.type,p_title:i,p_data:t,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(h)throw new Error(h.message);if(!f)return Bs(ws(`Suggestion silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await r.from("change_history").insert({item_id:s.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:o,new_data:t,actor:Zh(),session_id:Yh(),reason:`${e.field} suggested through atoms_suggest_field (machine-proposed, unapproved)`+(u?"; approval cleared (a signature never covers content the approver did not see)":"")}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=sh(o),g=y?await Ur(y,"The suggestion was",{readParent:()=>dd(r,e.project_id,y),saveParent:(t,n)=>_p(()=>r.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:n,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at})),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},w=Object.entries(n.field_source).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return Vs(ys({row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(m),...d?{rationale_field:d}:{},...u?{approval_cleared:!0}:{},acceptance_revoked:g.revoked,...g.warning?{warning:g.warning}:{},row:{id:s.id,computed_level:di(c,n),approved:!0===n.approved,mcp_fields:w,...Object.fromEntries(na[c].map(e=>[e,n[e]??null]))},...Ci(_)}))};return await f()}catch(r){const a=Ou(n,t,r);return a?kh(e,a):Bs(Ds(r))}}async function Sh(e,t){let n;try{const r=await co(),a=_o();try{await wo(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}const i=t??await xu(r,e.project_id);if("unreadable"===i)return $u();n=i;const s=await dd(r,e.project_id,e.row_id);if(!s)return Bs(vs("Analysis row",e.row_id));const o=s.data,l=Xf(o?.req_type);if(!l)return Bs(Ss(`Item ${e.row_id} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`));const c=e.approver_id??a,d=await async function(e,t,n){const{data:r,error:a}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(a)throw new Error(a.message);if(!r)throw new Error(`Project '${t}' not found`);const{data:i,error:s}=await e.from("org_members").select("role").eq("user_id",n).eq("org_id",r.org_id).maybeSingle();if(s)throw new Error(s.message);const o=i?.role;return"string"==typeof o?o:null}(r,e.project_id,c);if(!d)return Bs(Ss(`Approver '${c}' is not a member of this project's organization. Approve as a project member (omit approver_id to approve as yourself).`));const{schemeId:u}=await lh(r,e.project_id,l,o),p=o?.analysis_props??{},m=di(u,p);if(m===Br)return Bs(Ss(`${e.row_id} cannot be approved before it is rated: complete the rating fields first (the computed ${"hara_iso26262"===u?"ASIL":"hazard_iso14971"===u?"risk":"RPN"} is unset).`));if("ops"===i){const t=Ls(e.note??""),n=(new Date).toISOString(),{ops:a,refusals:i}=await Mu({client:r,projectId:e.project_id,itemId:s.id,tokens:Ru(e.base_token),cells:[{path:["analysis_props","approved"],value:!0},{path:["analysis_props","approved_at"],value:n},{path:["analysis_props","approved_by"],value:c},{path:["analysis_props","approved_note"],value:t}]}),o=await Eu({client:r,projectId:e.project_id,ops:a,refusals:i,labels:ph(u)}),_=Object.entries(p.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return qu(o.outcome,{row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:c,approved_at:n,approved_note:t,approver_role:d,computed_level:m,cleared_markers:_,acceptance_revoked:Tu(o.answers)},o.chunks)}const _=async()=>{const t=nh(o);t.analysis_props&&"object"==typeof t.analysis_props||(t.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const n=t.analysis_props;n.field_source&&"object"==typeof n.field_source||(n.field_source={});const i=Ls(e.note??""),_=(new Date).toISOString();n.approved=!0,n.approved_at=_,n.approved_by=c,n.approved_note=i;const f=[];for(const[e,t]of Object.entries(n.field_source))"mcp"===t&&(n.field_source[e]="user",f.push(e));f.sort(),t.metadata={...t.metadata??{},updated_at:_,updated_by:a};const{data:h,error:y}=await r.rpc("save_item_with_revision",{p_item_id:s.id,p_project_id:e.project_id,p_type:s.type,p_title:s.title,p_data:t,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(y)throw new Error(y.message);if(!h)return Bs(ws(`Approval silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await r.from("change_history").insert({item_id:s.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{approved:!0===p.approved,approved_at:p.approved_at??null,approved_by:p.approved_by??null,approved_note:p.approved_note??""},new_data:{approved:!0,approved_at:_,approved_by:c,approved_note:i},actor:Zh(),session_id:Yh(),reason:`${e.row_id} approved by ${c} via atoms_approve_row`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const g=sh(o);if(g){const t=await dd(r,e.project_id,g);if(t){const{revoked:n,parentProps:i}=Hr(t.data);if(n){const n={...t.data,analysis_props:i},{error:s}=await r.rpc("save_item_with_revision",{p_item_id:t.id,p_project_id:e.project_id,p_type:t.type,p_title:t.title,p_data:n,p_user_id:a,p_event_source:"mcp",p_event_session_id:Yh()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});s&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${t.id}': ${s.message}\n`)}}}return Vs(ys({row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:c,approved_at:_,approved_note:i,approver_role:d,computed_level:m,cleared_markers:f}))};return await _()}catch(r){const a=Ou(n,t,r);return a?Sh(e,a):Bs(Ds(r))}}H(Zf,{approveRowHandler:()=>Sh,createAnalysisHandler:()=>dh,fillRowHandler:()=>_h,getAnalysisHandler:()=>yh,getGapsHandler:()=>vh,linkMitigationHandler:()=>wh,proposeRowsHandler:()=>jh,registerFunctionTags:()=>rh,suggestFieldHandler:()=>kh});var Ah=D({"src/tools/analysis.ts"(){ko(),hd(),Iu(),gp(),ey(),Ks(),gr(),Nu(),gr(),Oi(),Bi(),Qf(),Yf(),Pc(),za(),Kf=new Set(["safety-goal","failure-mode"])}}),Ih={};async function xh(e,t){const{data:n,error:r}=await e.from("metadata").select("scenario_catalogs").eq("project_id",t).maybeSingle();if(r)throw new Error(r.message);const a=Ff(n?.scenario_catalogs??[]);return a.ok?a.value:[]}async function $h(e){try{const t=await co(),n=Math.min(Math.max(e.limit??50,1),200),r=Math.max(e.offset??0,0),a=await xh(t,e.project_id);return Vs(ys(a.slice(r,r+n),gs(a.length,n,r)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}}async function Eh(e){try{const n=await co();_o();try{await wo(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Bs(ks("Viewer"));throw e}if("string"!=typeof(t=e.op)||!Uf.includes(t))return Bs(Ss("op must be one of create_catalog, rename_catalog, delete_catalog, add_entry, edit_entry, remove_entry, tag_entry, accept_catalog."));const r=e.op;if("create_catalog"===r&&(await xh(n,e.project_id)).length>=Hf)return Bs(Ss(`This project already carries the maximum of ${Hf} catalogs.`));const a={};"create_catalog"!==r||e.catalog_id?void 0!==e.catalog_id&&(a.catalog_id=e.catalog_id):a.catalog_id=`cat-${crypto.randomUUID().replace(/-/g,"").slice(0,12)}`,void 0!==e.name&&(a.name=Ls(e.name)),void 0!==e.entry_id&&(a.entry_id=e.entry_id),void 0!==e.text&&(a.text=Ls(e.text)),void 0!==e.function_tags&&(a.function_tags=e.function_tags),void 0!==e.by&&(a.by=e.by),void 0!==e.on&&(a.on=e.on);const{data:i,error:s}=await n.rpc("mutate_project_scenario_catalogs",{p_project_id:e.project_id,p_op:r,p_payload:a});return s?Bs(Ss(s.message)):Vs(ys({scenario_catalogs:i?.scenario_catalogs??[]}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Bs(As()):Bs(Ps(e instanceof Error?e.message:String(e)))}var t}H(Ih,{listScenarioCatalogsHandler:()=>$h,mutateScenarioCatalogHandler:()=>Eh});var qh,Oh,Rh,Th,Mh,zh,Ch,Dh,Hh,Uh,Ph,Nh,Lh,Fh,Wh,Vh,Bh=D({"src/tools/catalogs.ts"(){ko(),Ks(),Qf()}}),Jh={};function Qh(e){pe(e.toolName)&&function(e,t){const n=`ui://${t.toolName}/${t.htmlFile}`,r=function(e,t){const n=s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href),r=T.default.dirname(n);return T.default.resolve(r,"apps","src","apps",e,t)}(t.appName,t.htmlFile),a=[...ed.resourceDomains,...t.extraResourceDomains??[]];c.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:n}}},t.handler),c.registerAppResource(e,`${t.title} UI`,n,{mimeType:c.RESOURCE_MIME_TYPE},async()=>{const e=await R.default.readFile(r,"utf-8");return{contents:[{uri:n,mimeType:c.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:a}}}}]}})}(Th,e)}function Gh(e){return void 0===e?.requestId?void 0:String(e.requestId)}function Kh(e,t){return async(n,r)=>{let a="",i=null,s=!1;try{i=await co(),a=_o()}catch(e){i=null,s=e instanceof Ve}if(i){const e=await async function(e,t){let n;try{n=await Ys(e,t)}catch(e){return process.stderr.write(`[atoms-mcp] platform_status lookup failed: ${e instanceof Error?e.message:String(e?.message??e)}\n`),Cs(e)?Is():ws("Authorization check failed.",["ATOMS could not confirm your account status, so the call was refused","Retry in a moment; if it keeps failing, run atoms_status"])}return"suspended"===n?bs("account"):"pending"===n?ws("Account pending platform approval.",["A platform admin must approve your ATOMS account before ATOMS tools can be used","Sign in to the ATOMS web app to check your account status"]):null}(i,a);if(e)return Bs(e)}if(i&&await async function(e,t){te&&Date.now()-Z<=X||(ee||(ee=(async()=>{try{const n=await Q(e,t),r=await G(e,t,n);K=r.effective,r.role,Y=n,te||ie(r,n),te=!0}catch{te=!1}Z=Date.now(),le()})().finally(()=>{ee=null})),await ee)}(i,a),!te&&h.has(e))return Bs(i||s?{status:"error",message:"ATOMS could not load your organization's access rules yet, so changes are paused. Reading still works.",next_steps:["Wait a few seconds, then retry the same call","Your saved session is fine: nothing needs doing on your side"],code:"policy_not_loaded",retryable:!0}:As());const o=N(oe(),e);if(!o.allowed)return Bs(ws(`Tool ${e} is blocked by org policy.`,[F(o.reason),"Contact your org admin to adjust the MCP access policy."]));const l=function(e,t,n){const r=g[t];if(!e.block_destructive||!r)return{allowed:!0};const a=n?.[r.param];return"string"==typeof a&&r.values.includes(a)?{allowed:!1,reason:"block_destructive",message:`Tool ${t} op ${a} is blocked by org policy.`}:{allowed:!0}}(oe(),e,n);if(!l.allowed)return Bs(ws(l.message,[F(l.reason),"Contact your org admin to adjust the MCP access policy."]));try{!function(e){const t=Zo();if(!t)return;if("object"!=typeof e||null===e)return;const n=e.project_id;if("string"==typeof n&&n!==t)throw new Go(t,n)}(n)}catch(e){if(e instanceof Go)return Bs(xs(e.expectedProjectId));throw e}{const e=oe(),t=n?.project_id;if(null!==e.project_scope&&"string"==typeof t&&!e.project_scope.includes(t))return Bs(ws("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"]))}if(!i)return t(n,r);const c=await async function(e,t){const n=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Vo,r=new Date,a=new Date(r.getTime()-Bo);try{const{count:i,error:s}=await t.from("mcp_rate_limits").select("id",{count:"exact",head:!0}).eq("user_id",e).gte("requested_at",a.toISOString());if(s)throw new Error(s.message);if((i??0)>=n){const{data:n,error:i}=await t.from("mcp_rate_limits").select("requested_at").eq("user_id",e).gte("requested_at",a.toISOString()).order("requested_at",{ascending:!0}).limit(1).maybeSingle();if(i)throw new Error(i.message);const s=(n?new Date(n.requested_at).getTime():r.getTime())+Bo-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*Bo);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}}}(a,i);if(!c.allowed)return Bs($s(c.retryAfterSeconds));if("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN){const e=n?.project_id;if("string"==typeof e)try{const{requireWriteAccess:t}=await Promise.resolve().then(()=>(ko(),lo));await t(i,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(Ks(),_s));return Bs(e("Viewer (lockdown mode: read access requires editor or admin)"))}}}const d=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let u,p="success";try{const e=await t(n,r),a=e;if(!0===a?.isError){p="error";const e=a?.content;if(e?.[0]?.text)try{u=JSON.parse(e[0].text).message}catch{}}return pl(e,Rh)}catch(e){throw p="error",u=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:n,status:p,duration_ms:d(),error_msg:u,project_id:n.project_id,session_id:zh,client_name:Ch,client_version:Rh};try{!function(e,t,n){const r=Wo(n.params);e.from("mcp_audit_log").insert({user_id:t,tool_name:n.tool_name,params:r,status:n.status,duration_ms:n.duration_ms,error_msg:n.error_msg??null,project_id:n.project_id??null,session_id:n.session_id??null,client_name:n.client_name??null,client_version:n.client_version??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await co(),a,t)}catch{}}}}function Yh(){return zh}function Zh(){return Dh}function Xh(){return Ch}H(Jh,{ATOMS_MCP_SERVER_VERSION:()=>Rh,getMcpActor:()=>Zh,getMcpClientName:()=>Xh,getMcpSessionId:()=>Yh,server:()=>Th});var ey=D({"src/server.ts"(){Lo(),Ko(),Yo(),fe(),il(),ce(),Ol(),B(),pt(),Rl(),Oi(),P(),nd(),Ql(),gr(),ms(),ko(),oo(),Ks(),Ze(),ad(),qh=u.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href),Oh=qh("../package.json"),Rh=Oh.version,function(e){const t=e=>e.endsWith(O)?e:`${e}\n\n${O}`;if("function"==typeof e.registerTool){const n=e.registerTool.bind(e);e.registerTool=(e,r,...a)=>n(e,r&&"string"==typeof r.description?{...r,description:t(r.description)}:r,...a)}if("function"==typeof e.tool){const n=e.tool.bind(e);e.tool=(e,...r)=>n(e,..."string"==typeof r[0]?[t(r[0]),...r.slice(1)]:r)}}(Th=new d.McpServer({name:"atoms-mcp-server",version:Rh})),function(e){re=e;const t=e.registerTool.bind(e);e.registerTool=(e,...n)=>{const r=t(e,...n);return r&&"function"==typeof r.enable&&"function"==typeof r.disable&&ne.set(e,r),r}}(Th),Mh=(e,t,n)=>{if(pe(e))return Th.registerTool(e,t,n)},zh=i.randomUUID(),Ch=it(process.env.ATOMS_CLIENT_NAME),Dh=st(Ch),Mh("atoms_status",{title:"ATOMS MCP Health Check",description:Xc.atoms_status,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>ml(await(async()=>{const e=(e,t)=>async function(e,t,n){try{const e=await(async()=>async function(e,t){Qs.delete(t);const n=await Ys(e,t);let r=null;const{data:a,error:i}=await e.from("organizations").select("id, name").eq("status","suspended");return i||(r=(a??[]).map(e=>({org_id:e.id,name:e.name}))),{platform_status:n,org_suspended:r}}(await co(),_o()))();return"suspended"===e.platform_status?{status:"suspended",email:t,message:"Your ATOMS account is suspended. ATOMS tools are unavailable.",next_steps:["Contact ATOMS support or your organization admin to restore access"]}:"pending"===e.platform_status?{status:"pending",email:t,message:"Your ATOMS account is waiting for platform approval. ATOMS tools are unavailable until then.",next_steps:["Sign in to the ATOMS web app to check your account status"]}:{status:"authenticated",email:t,message:(e.org_suspended??[]).length>0?Gs:n,...e.org_suspended?{org_suspended:e.org_suspended}:{}}}catch(e){return{status:"error",email:t,message:`Credentials are valid, but ATOMS could not check your account status: ${e instanceof Error?e.message:String(e)}`,next_steps:["Retry in a moment; tool calls are refused until the account status can be checked"]}}}(0,e,t);try{const{readCredentials:t,isTokenValid:n}=await Promise.resolve().then(()=>(qe(),he)),r=await t();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@latest login","3. Complete the login in your browser","4. Restart Claude Desktop (quit and reopen)","5. Try your query again"]},null,2)}]};if(!n(r))try{const{getValidToken:t}=await Promise.resolve().then(()=>(at(),Xe)),{email:n}=await t(),{invalidateClient:r}=await Promise.resolve().then(()=>(ko(),lo));return r(),{content:[{type:"text",text:Zs(await e(n,"Token was expired but has been refreshed. You're good to go!"))}]}}catch(e){return e instanceof Ve?{content:[{type:"text",text:JSON.stringify({...Ge(),status:"unavailable",email:r.user_email??"unknown"},null,2)}]}:{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@latest logout","3. Run: npx @atoms-tech/atoms-mcp@latest login","4. Complete the login in your browser","5. Restart Claude Desktop (quit and reopen)"]},null,2)}]}}return{content:[{type:"text",text:Zs(await e(r.user_email??"unknown","ATOMS MCP is connected and authenticated. All tools are ready."))}]}}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@latest login","3. Restart Claude Desktop"]},null,2)}]}}})(),Rh)),Mh("atoms_list_projects",{title:"List ATOMS Projects",description:Xc.atoms_list_projects,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(wd(),yd));return e()})),Mh("atoms_list_items",{title:"List ATOMS Items",description:Xc.atoms_list_items,inputSchema:{project_id:l.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:l.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),domain:l.z.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:l.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:l.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:l.z.number().int().min(0).default(0).describe("Pagination offset (default 0)"),after:l.z.string().min(1).max(400).optional().describe("Cursor from meta.next_cursor of the previous page. Returns the next page strictly after it, even if an item before it was trashed meanwhile. Overrides offset."),baseline_id:l.z.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:l.z.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns items as they were at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(jd(),vd));return t(e)})),Mh("atoms_get_item",{title:"Get ATOMS Item Details",description:Xc.atoms_get_item,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:l.z.string().uuid().optional().describe("Optional baseline UUID. Returns the item as it was at that baseline's moment. Mutually exclusive with as_of."),as_of:l.z.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns the item as it was at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(Ld(),Dd));return t(e)})),Mh("atoms_list_changes",{title:"List ATOMS Changes",description:q,inputSchema:{project_id:l.z.string().uuid(),since_seq:l.z.number().int().min(0).optional(),limit:l.z.number().int().min(1).max(500).default(100)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_changes",async e=>{const{listChangesHandler:t}=await Promise.resolve().then(()=>(Bd(),Fd));return t(e)})),Mh("atoms_search",{title:"Search ATOMS Items",description:Xc.atoms_search,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),query:l.z.string().min(1).max(1e3).describe("Search text"),type:l.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),asset:l.z.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:l.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:l.z.string().uuid().optional().describe("Optional baseline UUID. Searches within the project state at that baseline's moment.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(Kd(),Qd));return t(e)})),Mh("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:Xc.atoms_semantic_search,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),query:l.z.string().min(1).max(1e3).describe("Natural-language concept query"),type:l.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),limit:l.z.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(Xd(),Yd));return t(e)})),Qh({appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:Xc.atoms_get_coverage,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),domain:l.z.string().max(64).optional().describe("Filter by domain tag"),level:l.z.string().max(32).optional().describe("Filter by level"),baseline_id:l.z.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:l.z.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Kh("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(au(),eu));return t(e)})}),Mh("atoms_verification_status",{title:"Get Release Verification Status",description:"Release-bound verification state per requirement, matching the in-app projection.\n\nEach requirement's state is derived from the runs bound to a formal Release:\nverified, failing, incomplete, or not-run, plus a stale flag and the\n(points_run / points_total) counts for its parameterized test points.\nA requirement's test cases are those linked from either side (its verified_by,\nor a test case's verifies). stale is true when the state is verified or\nincomplete and the requirement's content changed after the Release snapshot AND\nafter the newest run bound to this Release of at least one passed point of a\nlinked test case (a point of its matrix on an asset that reads passed at this\nRelease). Each such point is judged on its own: a passing run of it bound to\nthis Release after the change clears that point only, and the requirement stays\nstale until every one of them has passed again.\nThe content of a requirement is its title, its text, its item type and\nrequirement type, and the value of a project variable its text uses; a tag, a\nlink, the level, a custom field, a domain rename, turning review on and an\napproval do not change it. The app shows a stale requirement as Rerun. A row's\nstate stays verified or incomplete when its stale flag is true.\n\nrerun names the tests to rerun: each requirement with its linked test cases\nthat need one. A test case needs a rerun when a passed point of it was last run\nbefore the requirement's content changed, whatever the requirement's own state\n(the app's R on that test case). At a Release it reads the runs bound to that\nRelease and only a requirement changed after the snapshot, as stale does. A\nproject with no current formal Release (and no release_id) gets rerun alone,\nwith release null and a hint: judged on every recorded run, as the Matrix does.\n\nArgs:\n - project_id (string, UUID): The project to report on\n - release_id (string, UUID, optional): A formal Release (a baselines row with\n a release_version). Defaults to the project's CURRENT Release\n (release_status = 'released'). Without one, only rerun is returned.\n - include_gaps (boolean, optional, default false): Also return the not-run\n (test x unit x value) points for the Release.\n\nReturns:\n { release: {id, version, status} or null,\n readiness: {requirements, verified, failing, incomplete, not_run, stale,\n points_total, points_run}. Each requirement is counted once:\n verified = state verified and not stale; incomplete = state incomplete\n and not stale; failing = state failing; not_run = state not-run;\n stale = state verified or incomplete and stale. A stale requirement is\n counted under stale only (never also under verified or incomplete), so\n verified + failing + incomplete + not_run + stale = requirements,\n requirements: [{requirement_id, state, stale, points_total, points_run}],\n rerun: [{requirement_id, test_case_ids}],\n gaps?: [{tc_id, asset, point_key}] }\n readiness, requirements and gaps are left out when release is null.\n An empty requirements array with a \"hint\" field means the projection has not\n been rebuilt for this project yet, NOT that everything is unverified.\n\nExamples:\n - \"Are we ready to ship 2.0?\" → atoms_verification_status(project_id)\n - \"What's still not run for release R?\" → atoms_verification_status(project_id, release_id=\"...\", include_gaps=true)\n - \"Which tests need a rerun?\" → atoms_verification_status(project_id), then read rerun",inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),release_id:l.z.string().uuid().optional().describe("Formal Release (baselines row) UUID; defaults to the project's current Release"),include_gaps:l.z.boolean().default(!1).describe("Include the not-run (test x unit x value) points for the Release")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_verification_status",async e=>{const{verificationStatusHandler:t}=await Promise.resolve().then(()=>(lu(),iu));return t(e)})),Mh("atoms_get_history",{title:"Get Item Change History",description:Xc.atoms_get_history,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).describe("Item ID"),limit:l.z.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(mu(),uu));return t(e)})),Qh({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:Xc.atoms_export_mermaid,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),root_item_id:l.z.string().max(20).optional().describe("Root item ID to start from"),depth:l.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:l.z.boolean().default(!0).describe("Include test case links"),baseline_id:l.z.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:l.z.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Kh("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(ju(),wu));return t(e)})}),Uh=()=>l.z.string().max(128).optional().describe(S),Ph=()=>l.z.enum(["edit","apply_mine"]).describe(A).optional(),Nh=()=>l.z.string().min(1).max(600).optional().describe(x),Lh=(Hh=()=>l.z.union([l.z.string().min(1).max(At),l.z.array(l.z.string().min(1).max(At)).min(1).max(It)]).describe(k).optional())(),Fh=Uh(),Mh("atoms_create_item",{title:"Create ATOMS Item",description:Xc.atoms_create_item,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the target project"),type:l.z.enum(["requirement","test-case","note"]).describe("Item type"),title:l.z.string().min(1).max(500).describe("Item title"),req_type:l.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe("Requirement classification (functional|interface|performance|safety). safety-goal and failure-mode are analysis rows created by atoms_create_analysis, not here."),body:l.z.string().max(5e4).optional().describe("Rich text body"),summary:l.z.string().max(2e3).optional().describe("Brief summary"),domains:l.z.array(l.z.string().max(64)).max(20).optional().describe("Domain tags"),level:l.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:l.z.array(l.z.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:l.z.record(l.z.string().max(60),l.z.string().max(1e4)).optional().describe("Project-field values keyed by defined field name"),echo:l.z.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens"),idempotency_key:Uh()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Wp(),Lp));return t(e)})),Wh={steps:l.z.array(l.z.object({id:l.z.string().describe("Stable step id within the item"),instruction:l.z.string().describe("What the tester does"),test_data:l.z.string().optional().describe("Optional test data for the step"),expected:l.z.string().describe("Expected result")}).passthrough()).optional().describe("Test-case script steps: array of {id, instruction, test_data?, expected}. Max 50 steps, enforced by the DB trigger."),params:l.z.array(l.z.object({name:l.z.string().describe("Parameter name; steps reference it as {name}"),unit:l.z.string().optional().describe("Optional unit (e.g. km/h, V, m)"),values:l.z.array(l.z.union([l.z.string(),l.z.number()])).describe("Value set the test sweeps")}).passthrough()).optional().describe("Matrix parameters: array of {name, unit, values[]}. Matrix points (product of value-set sizes) capped at 64 by the DB trigger. "+Al)},Mh("atoms_update_item",{title:"Update ATOMS Item",description:Xc.atoms_update_item,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).optional().describe("Item ID (single form)"),title:l.z.string().min(1).max(500).optional().describe("New title"),body:l.z.string().max(5e4).optional().describe("New body"),summary:l.z.string().max(2e3).optional().describe("New summary"),domains:l.z.array(l.z.string().max(64)).max(20).optional().describe("New domain tags (a tag flagged as a function is not a domain and is rejected)"),level:l.z.string().max(32).optional().describe("New level"),status:l.z.enum(["passed","failed","blocked","not-run"]).optional().describe("Status. A test case's result can only come from a run: passed, failed and blocked are refused on a test case (use atoms_record_test_result); not-run is accepted on a test case with no runs"),req_type:l.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe("Requirement classification (functional|interface|performance|safety). safety-goal and failure-mode are analysis rows created by atoms_create_analysis, not here."),fields:l.z.record(l.z.string().max(60),l.z.string().max(1e4)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),...Wh,expected_updated_at:fl.optional().describe(`metadata.updated_at value from atoms_get_item; rejects stale writes. ${$}`),base_token:Hh(),intent:Ph(),asil_confirm_lower:l.z.string().max(8).optional().describe(To),widget_proof:Nh(),echo:l.z.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:l.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:l.z.array(l.z.object({item_id:l.z.string().min(1).max(20),title:l.z.string().min(1).max(500).optional(),body:l.z.string().max(5e4).optional(),summary:l.z.string().max(2e3).optional(),domains:l.z.array(l.z.string().max(64)).max(20).optional(),level:l.z.string().max(32).optional(),status:l.z.enum(["passed","failed","blocked","not-run"]).optional(),req_type:l.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional(),fields:l.z.record(l.z.string().max(60),l.z.string().max(1e4)).optional(),...Wh,expected_updated_at:fl.optional(),base_token:Hh(),intent:Ph(),asil_confirm_lower:l.z.string().max(8).optional().describe(To)})).optional().describe("Array form: update many items in one call"),idempotency_key:Uh(),continue_on_error:l.z.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(km(),gm));return t(e)})),Mh("atoms_delete_item",{title:"Delete ATOMS Item",description:Xc.atoms_delete_item,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:l.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Im(),Sm));return t(e)})),Mh("atoms_restore_item",{title:"Restore ATOMS Item",description:Yi,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().max(256).describe("ID of the item in Trash"),confirm:l.z.boolean().optional().describe(Zi)},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(Rm(),xm));return t(e)})),Mh("atoms_link_items",{title:"Link ATOMS Items",description:`Add or remove relationships between items.\n\nSingle-op form:\n - project_id, from_id, to_id, type (parent|child|related|verifies|verified_by|affects|affected_by), action (add|remove)\n - affects/affected_by (REQ-ANL-242): links a security risk analysis row (CYB-n) to an ISO 14971\n risk row (RSK-n) only; nothing is derived onto the risk row's own ratings. Any other pair is\n refused by name.\n - expected_from_updated_at? / expected_to_updated_at?: metadata.updated_at values from atoms_get_item to reject stale link commands\n - echo? false → lean {action,from_id,to_id} response\n - reason?: persisted in audit history\n\nArray form (batch link ops, same tool, much faster for restructures):\n - project_id, operations: [{action, from_id, to_id, type, expected_from_updated_at?, expected_to_updated_at?}]\n - Validated as a whole (DAG cycle check) before any write, then applied one at a time (removes before adds), NOT in a single transaction: a mid-batch failure leaves earlier operations committed and names which ones\n - reason?, idempotency_key? supported\n\nidempotency_key: ${S}`,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),from_id:l.z.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:l.z.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:l.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by"]).optional().describe("Relationship type"),action:l.z.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:fl.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:fl.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:l.z.boolean().optional().describe("false → lean response"),reason:l.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:l.z.array(l.z.object({action:l.z.enum(["add","remove"]),from_id:l.z.string().min(1).max(20),to_id:l.z.string().min(1).max(20),type:l.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by"]),expected_from_updated_at:fl.optional(),expected_to_updated_at:fl.optional()})).optional().describe("Array form: batch relationship ops, DAG-validated as a whole then applied in sequence (not one transaction); a mid-batch failure reports which ops committed."),idempotency_key:Uh()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(Um(),Tm));return t(e)})),Qh({appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:Xc.atoms_bulk_import,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the target project"),items:l.z.array(l.z.object({type:l.z.enum(["requirement","test-case","note"]).describe("Item type"),title:l.z.string().min(1).max(500).describe("Item title"),body:l.z.string().max(5e4).optional().describe("Rich text body"),summary:l.z.string().max(2e3).optional().describe("Brief summary"),domains:l.z.array(l.z.string().max(64)).max(20).optional().describe("Domain tags"),level:l.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:l.z.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(500).describe("Items to create (1-100; 1-500 on a project that saves one field at a time)"),confirmation_token:l.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),idempotency_key:Uh()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:Kh("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(Vm(),Nm));return t(e)})}),Vh={point:l.z.record(l.z.string(),l.z.union([l.z.string(),l.z.number()])).optional().describe('Matrix point this run executed, e.g. {"speed": 40}'),release_id:l.z.string().uuid().optional().describe("Formal Release to bind this run to (a baseline with a release_version)"),build:l.z.string().optional().describe("Free-text build label"),environment:l.z.string().optional().describe("Structured environment field, distinct from build"),tooling:l.z.string().optional().describe("Structured tooling field, distinct from build"),steps_rev:l.z.string().optional().describe(jl),evidence_url:l.z.string().optional().describe(Sl),step_results:l.z.array(l.z.object({step_id:l.z.string().describe("Step id from atoms_get_item steps[].id"),status:l.z.enum(["passed","failed","blocked","skipped"]).describe("Per-step status"),actual:l.z.string().optional().describe("Actual-result note"),evidence_url:l.z.string().optional().describe(kl)}).passthrough()).optional().describe("Per-step results [{step_id, status, actual?, evidence_url?}]. When present the run verdict is derived server-side and the top-level result is ignored.")},Mh("atoms_record_test_result",{title:"Record Test Result",description:Xc.atoms_record_test_result,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:l.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:l.z.string().max(500).optional().describe("Reason or comment for this result"),asset:l.z.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new."),date:l.z.string().optional().describe(gl),...Vh,idempotency_key:Fh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_record_test_result",async(e,t)=>{const{recordTestResultHandler:n}=await Promise.resolve().then(()=>(Gm(),Bm));return n({...e,request_id:Gh(t)})})),Mh("atoms_record_test_results",{title:"Record Test Results (bulk)",description:Xc.atoms_record_test_results,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:l.z.array(l.z.object({asset:l.z.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:l.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:l.z.string().max(500).optional().describe("Run note"),date:l.z.string().optional().describe("Ignored: runs are stamped with server time. A supplied date is reported in the response warning, never stored."),...Vh})).min(1).max(100).describe("1 to 100 result entries on this test case"),idempotency_key:Fh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_record_test_results",async(e,t)=>{const{recordTestResultsBulkHandler:n}=await Promise.resolve().then(()=>(Zm(),Km));return n({...e,request_id:Gh(t)})})),Qh({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:Xc.atoms_trace,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).describe("Starting item ID"),direction:l.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:l.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:l.z.array(l.z.enum(["parent","child","related","verifies","verified_by","mitigated_by","mitigates","affects","affected_by"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Kh("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(t_(),Xm));return t(e)})}),Mh("atoms_list_assets",{title:"List Project Assets",description:Xc.atoms_list_assets,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),include_archived:l.z.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(i_(),n_));return t(e)})),Mh("atoms_list_variables",{title:"List Project Variables",description:Xc.atoms_list_variables,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),baseline_id:l.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:l.z.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads"),limit:l.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:l.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(g_(),s_));return t(e)})),Mh("atoms_get_variable",{title:"Get Project Variable",description:Xc.atoms_get_variable,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),variable_name:l.z.string().min(1).max(64).describe("Variable name"),baseline_id:l.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:l.z.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(g_(),s_));return t(e)})),Mh("atoms_update_variable",{title:"Update Project Variable",description:Xc.atoms_update_variable,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),variable_name:l.z.string().min(1).max(64).describe("Variable name"),value:l.z.string().max(500).optional().describe("New value"),unit:l.z.string().max(32).optional().describe("Unit abbreviation"),description:l.z.string().max(2e3).optional().describe("Description"),echo:l.z.boolean().optional(),base_token:Lh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(g_(),s_));return t(e)})),Mh("atoms_create_variable",{title:"Create Project Variable",description:Xc.atoms_create_variable,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(64).optional().describe("Variable name (single form)"),value:l.z.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:l.z.string().max(32).optional().describe("Unit abbreviation"),description:l.z.string().max(2e3).optional().describe("Description"),echo:l.z.boolean().optional().describe("false → lean response (default true)"),variables:l.z.array(l.z.object({name:l.z.string().min(1).max(64).describe("Variable name"),value:l.z.string().min(1).max(500).describe("Initial value"),unit:l.z.string().max(32).optional().describe("Unit abbreviation"),description:l.z.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:l.z.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(g_(),s_));return t(e)})),Mh("atoms_delete_variable",{title:"Delete Project Variable",description:Xc.atoms_delete_variable,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(64).describe("Variable name to delete"),force:l.z.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:l.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),base_token:Lh},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(g_(),s_));return t(e)})),Mh("atoms_list_domains",{title:"List Project Domains",description:"List the domain tags of a project's taxonomy, with item counts.\n\nA tag flagged as a FUNCTION (metadata.function_tags, the seed of a HARA row) is not a domain: it is\nleft out of this list, exactly as the app's domain picker leaves it out, because atoms_create_item,\natoms_update_item and atoms_bulk_import refuse it as a domain. Such tags are named in\nexcluded_function_tags; use them through atoms_create_analysis source_functions or atoms_fill_row\nsource_function. To turn one back into a domain, call atoms_update_domain with is_function=false.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { domains: [{ name, registered, item_count }], total, registered_count, unregistered_count,\n excluded_function_tags: string[], note? }\n registered: false marks a tag found on items but not in the taxonomy (an orphan); a flagged tag\n an item still carries is a function on that item, never counted as an orphan.",inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(I_(),w_));return t(e)})),Mh("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.\nA name that is already a function is refused (a function is not a domain tag): unflag it first with atoms_update_domain is_function=false.\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:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(I_(),w_));return t(e)})),Mh("atoms_list_levels",{title:"List Project Levels",description:Xc.atoms_list_levels,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(pp(),Zu));return t(e)})),Mh("atoms_create_level",{title:"Create Project Level",description:Xc.atoms_create_level,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(pp(),Zu));return t(e)})),Mh("atoms_delete_level",{title:"Delete Project Level",description:Xc.atoms_delete_level,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(64).describe("Level name to delete"),confirmation_token:l.z.string().optional().describe("Token from the first (preview) call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_delete_level",async e=>{const{deleteLevelHandler:t}=await Promise.resolve().then(()=>(pp(),Zu));return t(e)})),Mh("atoms_reorder_levels",{title:"Reorder Project Levels",description:Xc.atoms_reorder_levels,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),names:l.z.array(l.z.string().min(1).max(64)).min(1).describe("Every existing level name, in the desired order")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_reorder_levels",async e=>{const{reorderLevelsHandler:t}=await Promise.resolve().then(()=>(pp(),Zu));return t(e)})),Mh("atoms_list_fields",{title:"List Project Fields",description:'List the project\'s custom field definitions (project-scoped key-value slots on items, e.g. "Verification Method"), with counts of items carrying a value.\n\nField values are set per item via atoms_create_item / atoms_update_item fields.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { fields: [{ name, type, options, item_count }], total }',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(Np(),Sp));return t(e)})),Mh("atoms_create_field",{title:"Create Project Field",description:Xc.atoms_create_field,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:l.z.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:l.z.array(l.z.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:l.z.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization"),appliesTo:l.z.array(l.z.enum(["requirement","test-case","note","table"])).max(4).optional().describe("Item types this field shows on (requirement|test-case|note|table); omit for all types")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(Np(),Sp));return t(e)})),Mh("atoms_delete_field",{title:"Delete Project Field",description:"Delete a project field definition. Existing item values are left in item JSON but no longer render as Matrix columns until a matching field is created again.\n\nArgs:\n - project_id (string, UUID): Project containing the field\n - name (string): Field name to delete",inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(60).describe("Field name")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(Np(),Sp));return t(e)})),Mh("atoms_reorder_fields",{title:"Reorder Project Fields",description:"Reorder project field definitions. Definition order drives the Column Picker listing and a fresh user's Matrix column order.\n\nOrdering only: no definition is added, dropped, renamed, or retyped, and no item value moves. Use this instead of deleting and recreating definitions to change their order.\n\nArgs:\n - project_id (string, UUID): Project containing the fields\n - names (string[]): Every existing field name exactly once, in the order you want them. A list that is not a permutation of the current names is refused, not partially applied.",inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),names:l.z.array(l.z.string().min(1).max(60)).describe("Every existing field name exactly once, in the desired order")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(Np(),Sp));return t(e)})),Mh("atoms_update_domain",{title:"Update Project Domain",description:'Rename a domain tag, or flag it as a function and unflag it again. Pass exactly one of new_name or is_function.\n\nRename (new_name): updates the taxonomy and propagates to all tagged items. The name is found in any case. A tag items carry in another case (for example "visualization" beside "Visualization") is a separate tag, as atoms_list_domains lists it, and is not renamed. Use dry_run=true first to see how many items will be affected before committing.\n\nFlag (is_function=true): makes a registered domain a function, the seed of a HARA row (atoms_create_analysis source_functions, atoms_fill_row source_function). A tag is a domain or a function, never both: the flagged tag leaves the Domains group, items that already carry it keep the tag, and no new item can take it as a domain until it is unflagged. Using a domain as a function never flags it as a side effect: atoms_create_analysis, atoms_fill_row and atoms_propose_rows refuse it until you flag it here. Before flagging, preview with dry_run=true and ask the user: the preview counts the items that carry the tag.\n\nUnflag (is_function=false): turns a function back into a domain, so items can be tagged with it again. Analysis rows that name it as their function keep the name as text (they are not changed) and the answer counts them; flag it again to restore the Functions listing.\n\ndry_run=true previews either change and changes nothing.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Current domain name (or function name, to unflag it)\n - new_name (string, optional): New domain name (rename)\n - is_function (bool, optional): true flags the domain as a function, false unflags a function back to a domain\n - dry_run (bool, optional): If true, return the impact without making changes (default false)\n\nReturns (rename, dry_run=false):\n { domain: { name }, renamed_from, items_updated, message }\n\nReturns (rename, dry_run=true):\n { dry_run: true, rename: { from, to }, items_affected, message }\n\nReturns (is_function=true):\n { domain: { name }, is_function: true, changed, items_carrying_tag, message }\n\nReturns (is_function=false):\n { domain: { name }, is_function: false, changed, analysis_rows_using_function, message }\n\nWith dry_run=true a flag change returns the same fields plus dry_run: true and changes nothing.',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(64).describe("Current domain name (or function name, to unflag it)"),new_name:l.z.string().min(1).max(64).optional().describe("New domain name (rename)"),is_function:l.z.boolean().optional().describe("true flags the domain as a function, false unflags a function back to a domain"),dry_run:l.z.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(I_(),w_));return t(e)})),Mh("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. The name is found in any case. A tag items\ncarry in another case is a separate tag, as atoms_list_domains lists it, and is kept.\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:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(64).describe("Domain name to delete"),force:l.z.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:l.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(I_(),w_));return t(e)})),Qh({appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:Xc.atoms_project_summary,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Kh("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(q_(),x_));return t(e)})}),Qh({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:Xc.atoms_browse,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),type:l.z.enum(["requirement","test-case","note","table","analysis"]).optional().describe("Filter by item type"),domain:l.z.string().max(64).optional().describe("Filter by domain tag"),level:l.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:l.z.string().max(1e3).optional().describe("Full-text search query"),limit:l.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:l.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Kh("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(M_(),O_));return t(e)})}),Mh("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:Xc.atoms_impact_analysis,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),item_id:l.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:l.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:l.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:l.z.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(G_(),z_));return t(e)})),Mh("atoms_list_baselines",{title:"List ATOMS Baselines",description:Xc.atoms_list_baselines,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),limit:l.z.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:l.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(Pf(),If));return t(e)})),Mh("atoms_create_baseline",{title:"Create ATOMS Baseline",description:Xc.atoms_create_baseline,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),name:l.z.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:l.z.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(Pf(),If));return t(e)})),Mh("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:Xc.atoms_lock_baseline,inputSchema:{baseline_id:l.z.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(Pf(),If));return t(e)})),Mh("atoms_diff_baselines",{title:"Diff ATOMS Baselines",description:Xc.atoms_diff_baselines,inputSchema:{baseline_a_id:l.z.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:l.z.string().uuid().describe("UUID of the second (newer) baseline"),detail:l.z.boolean().default(!1).describe("Add a per-field from/to diff object to each modified item (default false)"),limit:l.z.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:l.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(Pf(),If));return t(e)})),Mh("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:Xc.atoms_restore_baseline,inputSchema:{baseline_id:l.z.string().uuid().describe("UUID of the baseline to restore from"),confirm:l.z.boolean().default(!1).describe("Set true to execute; false (default) returns a preview"),source_seq:l.z.number().int().min(0).optional().describe("The source_seq the preview returned. Required to confirm on a project that saves one field at a time."),bulk_id:l.z.string().uuid().optional().describe(I),after_id:l.z.string().min(1).max(64).optional().describe(I)},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(Pf(),If));return t(e)})),Mh("atoms_create_analysis",{title:"Create Analysis (HARA, Risk analysis, FMEA)",description:'Create a new analysis (a HARA under ISO 26262, a Risk analysis under ISO 14971, a Security risk\nanalysis under AAMI TIR57 (subtype security_risk, or hara with variant tir57), a DFMEA, a PFMEA,\na Software FMEA or a Use FMEA) with one empty row per seed. The analysis carries its standard:\nthe subtype and the variant name it, and a project may hold analyses under both standards.\n\nRequires editor or admin role. Structure matches analyses created in the ATOMS web app.\nA hara (HARA or risk analysis) is seeded from FUNCTIONS (tags flagged as functions), never from\nrequirements: a requirement is an output of the analysis. A dfmea (DFMEA or FMEA) is seeded from\nrequirements / design elements; a PFMEA from a process step.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Target project\n - subtype (string): hara | dfmea | risk_analysis | fmea. risk_analysis is an alias of hara and\n fmea an alias of dfmea, so a medical user never has to say HARA or DFMEA.\n hazard_analysis is still accepted as the older name of risk_analysis.\n - variant (string, optional): the standard the analysis carries. hara: iso26262 | iso14971 | tir57;\n risk_analysis implies iso14971; security_risk implies tir57; dfmea: design | process |\n software | use; fmea implies process (the PFMEA). A variant outside the subtype\'s family is\n refused by name. The project\'s industry setting limits which analyses can be created, exactly\n as the create menu in the app does: automotive offers the HARA (iso26262) and the DFMEA\n (design); medical device offers the Risk analysis (iso14971), the Security risk analysis\n (tir57), the PFMEA (process), the Software FMEA (software) and the Use FMEA (use). A project\n with no industry set counts as automotive, as in the app. A variant the industry does not\n offer, an alias counting as the variant it implies, is refused before anything is written,\n naming the industry and what it offers. Analyses already in the project keep working\n whatever their variant. One exception: a project that counts as automotive but already\n holds a live medical device analysis (its industry was never chosen) is not limited and can\n keep creating the medical device analyses. A medical device project is always limited.\n Name none and the default follows the project\'s industry: automotive gives hara iso26262 and\n dfmea design, medical device gives hara iso14971 and dfmea process. The variant is stored on\n the analysis and selects its scheme for every later read and write; the setting never\n changes an analysis that already exists.\n - title (string, optional): Analysis title (default "New <parent label>": "New HARA",\n "New Risk analysis", "New DFMEA", "New PFMEA", "New Software FMEA", "New Use FMEA")\n - source_functions (string[], hara only, max 50): Function names to seed rows from. A name\n absent from the project\'s tags is registered as a function-flagged tag; a name that is\n already a domain is refused, never flagged (flag it first: atoms_update_domain with\n is_function=true); matching is case-insensitive and trimmed. Rejected for dfmea.\n - source_req_ids (string[], dfmea only, max 50): Requirement IDs to seed rows from.\n Each must exist, be a plain requirement, and not itself be an analysis row. Rejected for hara.\n - revision (string, optional): Revision label (default "1.0")\n - intended_use (string, optional, ISO 14971 risk analysis only): what the device is for, for\n which patient, by which user and in which environment (ISO 14971:2019 5.2).\n - foreseeable_misuse (string, optional, ISO 14971 risk analysis only): the reasonably\n foreseeable misuse, ONE CASE PER LINE (ISO 14971:2019 5.2).\n - safety_characteristics (string, optional, ISO 14971 risk analysis only): the characteristics\n related to safety, ONE PER LINE (ISO 14971:2019 5.3).\n The three scope fields are the analysis\'s, not a row\'s. They are refused by name on a scheme\n that carries no scope (a HARA, a DFMEA, an FMEA), and they can be written later on the\n analysis id with atoms_fill_row.\n The stored subtype and the row req_types are the same under every standard; ids follow the\n scheme: HARA-n / SG-n (hara_iso26262), RA-n / RSK-n (hazard_iso14971), DFMEA-n / FM-n (dfmea_rpn),\n PFMEA-n / PF-n (fmea_process), SFMEA-n / FM-n (fmea_software), UFMEA-n / FM-n (fmea_use).\n\nReturns:\n { id (e.g. "HARA-001", "RA-001", "PFMEA-001"), subtype, title, revision,\n standard? ("ISO 26262" | "ISO 14971" for a hara; "AIAG-VDA FMEA Handbook" for a DFMEA or PFMEA;\n absent for a Software FMEA or a Use FMEA), scheme, variant,\n labels: { parent, row, row_statement, mitigating_requirement, lane, level },\n rows: [{ id, source_function }] (hara) | [{ id, source_req }] (dfmea),\n link_warnings?: [{ row_id, source_function | source_req, message }], warning? }\n rows lists every created row. If any row could not be attached to the analysis, it is\n named in link_warnings and warning explains the repair (atoms_link_items with type\n \'parent\', from_id=<row id>, to_id=<analysis id>); such rows will not appear in\n atoms_get_analysis until relinked.\n\nSide effects:\n - Creates the analysis parent item plus one row item per seed (row ids follow the scheme: SG-n or RSK-n, FM-n or PF-n)\n - hara: registers new function names in the project\'s tags and function flags (metadata)\n - Links each row to the parent (dual-written to the relationship shadow table)\n - Logs each created item to change_history with actor=\'mcp_<client>\'\n\nIf a function name cannot be added to the project\'s Functions list, the write still succeeds and the\nanswer carries unregistered_functions (the names) and function_warning (how to add them).',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the target project"),subtype:l.z.enum(["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"]).describe("Analysis subtype; risk_analysis is an alias of hara and fmea of dfmea, hazard_analysis is still accepted as the older name of risk_analysis, and security_risk names the AAMI TIR57 security risk analysis (implies variant tir57) (REQ-ANL-192, REQ-ANL-245)"),title:l.z.string().min(1).max(500).optional().describe("Analysis title"),source_functions:l.z.array(l.z.string().min(1).max(100)).max(50).optional().describe("hara only: function names to seed rows from (0-50); new names are registered as function-flagged tags"),source_req_ids:l.z.array(l.z.string().min(1).max(20)).max(50).optional().describe("dfmea only: requirement IDs to seed rows from (0-50)"),revision:l.z.string().min(1).max(32).optional().describe("Revision label (default 1.0)"),variant:l.z.enum(["iso26262","iso14971","tir57","design","process","software","use"]).optional().describe("The standard the analysis carries (REQ-ANL-212). hara: iso26262 | iso14971 | tir57; dfmea: design | process | software | use. risk_analysis implies iso14971, fmea implies process, security_risk implies tir57. Omit it and the default follows the project industry setting (REQ-ANL-216); a variant the project's industry does not offer is refused before anything is written (REQ-ANL-347, REQ-ANL-349)."),intended_use:l.z.string().max(1e4).optional().describe("ISO 14971 risk analysis only: what the device is for, for which patient, by which user and in which environment (ISO 14971:2019 5.2)."),foreseeable_misuse:l.z.string().max(1e4).optional().describe("ISO 14971 risk analysis only: the reasonably foreseeable misuse, one case per line (ISO 14971:2019 5.2)."),safety_characteristics:l.z.string().max(1e4).optional().describe("ISO 14971 risk analysis only: the characteristics related to safety, one per line (ISO 14971:2019 5.3)."),threat_model_method:l.z.string().max(1e4).optional().describe("Security risk analysis only: the threat modeling methodology used, e.g. STRIDE."),threat_model_rationale:l.z.string().max(1e4).optional().describe("Security risk analysis only: why that methodology was chosen."),environment_assumptions:l.z.string().max(1e4).optional().describe("Security risk analysis only: assumptions about the operating environment, one per line."),attack_surfaces:l.z.string().max(1e4).optional().describe("Security risk analysis only: interfaces and entry points considered, one per line."),related_documents:l.z.string().max(1e4).optional().describe("Security risk analysis only: where the SBOM, the security testing report and the architecture views live."),idempotency_key:Fh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_fill_row",{title:"Fill Analysis Row Fields",description:'Fill fields on one analysis row: a HARA or risk analysis row, a security risk analysis row, a DFMEA or FMEA row (row ids follow the scheme: SG-n or RSK-n, CYB-n, FM-n or PF-n).\n\nRequires editor or admin role. Written fields are marked as MCP-sourced so the\nweb app shows their provenance. The computed level (ASIL, RPN or Risk) is derived and\nnever stored: asil is never a writable key.\n\nA security risk analysis row (CYB-n) accepts threat_event, vulnerability, impact, harm,\nseverity, exploitability (E: the ease of exploiting the vulnerability across the device\nlifecycle; it is NOT a probability), residual_s, residual_e, s_rationale, e_rationale,\njustification, safety_goal (the security control statement), safety_impact (Yes|No),\nsafety_impact_justification, source_function (the asset), assumptions and rationale. It\nrefuses p1, p2, occurrence and detection by name (those belong to the other schemes).\n\nrow_id may also name the ANALYSIS PARENT (e.g. "RA-001", "SEC-001"), which carries the\nanalysis\'s own fields rather than a row\'s: on an ISO 14971 risk analysis exactly intended_use,\nforeseeable_misuse, safety_characteristics (its scope, ISO 14971:2019 5.2 and 5.3),\noverall_residual_risk (Low | Medium | High) with overall_residual_rationale (its overall\nresidual risk, ISO 14971:2019 clause 8) and software_safety_class (A | B | C) with\nsoftware_safety_rationale (IEC 62304 4.3); on a security risk analysis exactly\nthreat_model_method, threat_model_rationale, environment_assumptions, attack_surfaces,\nrelated_documents, lifecycle_sources (a JSON array of [name, considered, note] tuples) and\noverall_residual_risk (Very Low | Low | Moderate | High | Very High) with\noverall_residual_rationale. Any other key on a parent is refused by name with that list\ngiven, and a scheme that carries no parent field (a HARA, a DFMEA, an FMEA) refuses all of\nthem. Both judged values are a PERSON\'s: nothing computes them, the empty string clears\none, and the app only ever suggests one from the rows.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. "SG-001", "RSK-002", "FM-003", "PF-004"), or the\n analysis parent ID (e.g. "RA-001") to write the analysis\'s scope and overall judgement\n - fields (object): Field name to value map. Allowed keys:\n hara: failure_mode, operating_scenario, hazard, assumptions, severity (S0-S3), exposure (E0-E4),\n controllability (C0-C3), safe_state, ftti, rationale, source_function, effect, title\n dfmea: failure_mode, cause, severity (1-10), occurrence (1-10), detection (1-10),\n rationale, effect\n medical risk analysis: failure_mode (the hazard), operating_scenario (the sequence of events),\n hazard (the harm), assumptions, severity (1-5), p1 (1-5), p2 (1-5), rationale, source_function,\n safety_goal (the risk control statement), s_rationale, p1_rationale, p2_rationale,\n residual_s, residual_p1, residual_p2, benefit_note, effect\n medical FMEA: the FMEA keys of its variant; a PFMEA adds process_step and current_controls,\n and a Software FMEA has NO occurrence (fixed at 10, IEC 62304).\n The analysis carries its standard: the variant stored on the row\'s parent analysis selects\n the scheme (an analysis stored before v5.4 without one resolves through the project\'s legacy hint).\n The derived level (asil / rpn / risk / p0) and the approval keys (approved, approved_at,\n approved_by, approved_note, field_source, link_roles, mitigation_types) are refused BY NAME.\n A suggested rating is written together with its rationale: pass the rating and its evidence\n field in one call (severity + s_rationale, p1 + p1_rationale), or use atoms_suggest_field.\n \'effect\' writes the row\'s long text body (the hazardous event of a HARA row, the hazardous situation\n of a medical risk analysis row, the effect of an FMEA row). dfmea failure_mode also\n becomes the row title. dfmea ratings accept numbers and are stored as strings.\n hara failure_mode: the standardized suggestions are No function, Loss of function, Partial function,\n Degradation of function, Misinterpretation of function (a suggestion; any text is accepted).\n hara source_function: the function the row analyzes, registered as a function-flagged tag if new;\n a name that is already a domain is refused, never flagged (atoms_update_domain is_function=true).\n\nReturns:\n { row_id, subtype, written_fields, computed_level, asil_propagated_to?, approval_cleared? }\n approval_cleared: true means the row WAS approved and this write cleared approved, approved_by,\n approved_at and approved_note: a signature never covers content the approver did not see. A\n person approves the row again with atoms_approve_row once they have read the new values.\n On the analysis parent instead: { analysis_id, scheme, written_fields,\n scope: { intended_use, foreseeable_misuse: string[], safety_characteristics: string[] },\n overall: { residual_risk, residual_rationale, safety_class, safety_rationale } }.\n\nSide effects:\n - Saves the row with stale-write protection and logs to change_history\n - On an approved row: clears the approval (history-logged with the reason)\n - ISO 26262 HARA only (scheme hara_iso26262): if the row is linked and its computed ASIL changed,\n updates the asil / asil_source of each requirement atoms_get_analysis lists in the row\'s\n mitigated_by, never the row itself or a test case (each update is history-logged). asil is an\n ISO 26262 field: a row of an ISO 14971 risk analysis or of a TIR57 security risk analysis never\n writes it (REQ-ANL-257)\n\nIf a function name cannot be added to the project\'s Functions list, the write still succeeds and the\nanswer carries unregistered_functions (the names) and function_warning (how to add them).',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),row_id:l.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003), or the analysis parent ID (e.g. RA-001) for its scope and overall residual risk"),fields:l.z.record(l.z.string().max(64),l.z.union([l.z.string().max(5e4),l.z.number()])).describe("Field name to value map (see description for allowed keys per subtype)"),base_token:Lh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_get_analysis",{title:"Get Analysis",description:'Get a full analysis view: every row with its computed level (ASIL, RPN or Risk, by the\nanalysis\'s scheme) and gap / critical / stale classifications, plus summary counts and the\nscheme\'s vocabulary.\n\nClassifications match the ATOMS web app exactly (same rules, same thresholds). The analysis\ncarries its standard: the variant stored on it selects the scheme (a hara is a HARA under\nISO 26262 or a Risk analysis under ISO 14971; a dfmea is a DFMEA, a PFMEA, a Software FMEA or\na Use FMEA). An analysis stored before v5.4 without a variant resolves through the project\'s\nlegacy hint and reads variant null.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "RA-001", "PFMEA-002")\n\nReturns:\n { analysis: { id, title, subtype, scheme, revision, standard, variant,\n labels: { parent, row, row_statement, mitigating_requirement, lane, level },\n acceptability: { Low, Medium, High } | null (the ISO 14971 wording per risk level, e.g. High is\n "Not acceptable"; null on every scheme but the medical risk analysis),\n definitions: [{ key, text }] (the scheme\'s glossary, the text the app\'s tooltips show),\n control_types: [{ id, abbr, label, precedence }] (ISO 14971 clause 7, applied in precedence\n order; empty on the automotive schemes),\n field_labels: [{ key, label }] (each raw row key to the label this scheme shows for it, e.g. in a\n medical risk analysis failure_mode is "Hazard", effect is "Hazardous situation" and hazard is\n "Harm"; read the raw keys through this list, never as automotive words),\n scope: { intended_use, foreseeable_misuse: string[], safety_characteristics: string[] } | null\n (the analysis\'s scope, ISO 14971:2019 5.2 and 5.3; the two lists are the stored lines, blank\n lines dropped; null on a scheme that carries no scope),\n overall: { residual_risk, residual_rationale, safety_class, safety_rationale } | null\n (the overall residual risk a person judged, ISO 14971:2019 clause 8, and the IEC 62304 4.3\n software safety class; an unjudged value reads as the empty string; null on a scheme that\n carries neither),\n threat_model: { stated, method, rationale, environment_assumptions: string[], attack_surfaces: string[],\n lifecycle_sources: [{ name, considered, note }], related_documents } | null (security risk\n analysis only; null on every other scheme),\n acceptance: { acceptance_state, accepted_by, accepted_at, acceptance_note,\n open_gaps_at_acceptance: [{ kind, label }] } (REQ-ANL-249: the analysis-level acceptance\n record; a parent never accepted reads acceptance_state "draft" with an empty gap list,\n never null) },\n rows: [{ id, title, source_req, effect, <the scheme\'s fields under their raw keys>,\n computed_level, computed_level_text (the acceptability wording behind the level, or null),\n is_gap, gap_rule, is_critical, is_stale, mitigated_by, link_roles, mitigation_types,\n verified_by, residual_level (medical risk analysis and security risk analysis only; null\n elsewhere),\n approved, approved_at, approved_by, approved_note, mcp_fields }],\n counts: { rows, gaps, critical, stale, approved, linked } }\n The vocabulary lists are given once per analysis, never repeated per row.\n\nA row\'s mitigated_by lists the live requirements that mitigate it, whichever side stored the link\n(the row\'s mitigated_by or the requirement\'s mitigates), read the way the app\'s analysis grid reads\nit; a link to the row itself, to a test case or to another analysis row does not count. The gap and\ncritical rules and counts.linked read this list.',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),analysis_id:l.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:'Link a HARA / risk analysis / FMEA row to the technical requirement that mitigates it (the\nsafety requirement of a HARA row, the risk control of a medical row, the action of an FMEA row).\n\nRequires editor or admin role.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing both items\n - row_id (string): Analysis row ID (e.g. "SG-001", "RSK-002", "FM-003", "PF-004")\n - req_id (string): Target requirement ID (must be a plain requirement, not an analysis row)\n hara / medical risk analysis rows: the target must be a requirement of req_type \'safety\'\n (a safety requirement / risk control); any other requirement is refused with the rule\n named (REQ-ANL-142). An FMEA row accepts any requirement, so long as role is given.\n - control_type (string, medical and security schemes only, REQUIRED there): inherent | protective | information\n (ISO 14971 clause 7: inherently safe design, protective measure, information for safety), or on a security risk analysis row (CYB-n, AAMI TIR57) one of the eight FDA Appendix 1 categories: authentication | authorization | cryptography | code_data_execution_integrity | confidentiality | event_detection_logging | resiliency_recovery | firmware_software_updates (REQ-ANL-241).\n Stored on the LINK (the row\'s analysis_props.mitigation_types keyed by req_id), never on the\n requirement. The analysis carries its standard: control_type is required exactly when the\n row\'s resolved scheme is medical (hazard_iso14971, fmea_process, fmea_software, fmea_use: a\n risk analysis, PFMEA, Software FMEA or Use FMEA link carries one) and refused on a HARA\n (ISO 26262) or a DFMEA row.\n - role (string, dfmea rows only, REQUIRED there): prevention | detection | mitigation.\n Must be omitted for hara rows (a HARA or a risk analysis).\n - override (boolean, optional, default false): ISO 26262 HARA only. When the target\n already carries a different ASIL, the call fails with a structured error\n (details.code=\'asil_conflict\') unless override=true; the override is\n history-logged like a dialog accept.\n - action (string, optional, default "add"): add | remove. remove unlinks the pair the way the app\'s\n grid unlink does: both sides of the link, its role and its control type are cleared, an accepted\n analysis returns to draft, and the target\'s ASIL is left as it is. A pair linked on neither side\n is refused and nothing is written; role, control_type and override are refused with remove. A\n link of a row to itself counts as no link in the app or in any read here, and this tool does\n not remove it.\n\nReturns:\n { row_id, req_id, type: "mitigated_by", role, scheme, control_type? (medical links, the type stored\n on the link), asil_written? (ISO 26262 HARA only: the row\'s computed ASIL, written\n onto the target) }\n action remove: { row_id, req_id, type: "mitigated_by", action: "remove", scheme }\n\nSide effects:\n - Adds the mitigated_by/mitigates relationship (JSONB + shadow table, one transaction)\n - remove: deletes it the same way, then clears the link\'s control type on the row\n - ISO 26262 HARA only (scheme hara_iso26262): writes the row\'s computed ASIL onto the target\n requirement (data.asil + data.asil_source) with a history entry recording previous/new values.\n An ISO 14971 risk row and a TIR57 security row write no field on the target (REQ-ANL-257)\n - dfmea / every FMEA: never modifies any field on the target requirement',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),row_id:l.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:l.z.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:l.z.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows (every FMEA); must be omitted for hara rows."),override:l.z.boolean().optional().describe("hara only: apply the row's level (ASIL or Risk) over a conflicting existing value (history-logged)"),control_type:l.z.enum(["inherent","protective","information","authentication","authorization","cryptography","code_data_execution_integrity","confidentiality","event_detection_logging","resiliency_recovery","firmware_software_updates"]).optional().describe("Medical schemes only (required there): the ISO 14971 clause 7 control type. Security risk analysis rows (required there): one of the eight FDA Appendix 1 categories (authentication, authorization, cryptography, code_data_execution_integrity, confidentiality, event_detection_logging, resiliency_recovery, firmware_software_updates). Stored on the link; refused when it does not belong to the row's own scheme (REQ-ANL-241)."),action:l.z.enum(["add","remove"]).optional().describe("add (default) links the pair; remove unlinks it the way the app's grid unlink does (REQ-ANL-313).")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:'List only the gap rows of a HARA / risk analysis / FMEA analysis, each naming the rule that matched.\n\nGap rules (identical to the web app):\n hara (HARA): unmitigated row with ASIL A-D ("asil <X> unmitigated")\n hara (medical risk analysis): uncontrolled row with Risk above Low ("<level> risk uncontrolled")\n dfmea (DFMEA, PFMEA and every FMEA variant): unmitigated row with RPN >= 100 ("rpn >= 100") or\n severity >= 9 ("severity >= 9")\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. "HARA-001", "RA-001", "PFMEA-002")\n\nReturns:\n { analysis_id, subtype, gaps: [{ id, title, source_req, source_function, computed_level, rule }], count }\n count is the gap-line TOTAL: the sum of every gap kind\'s gap_count (a controlled-but-unverified risk, an analysis-scope gap all count), matching the app\'s gap banner, so it can be GREATER than gaps.length, which lists only the per-row gap rules.\n plus scheme, labels and gap_kinds: [{ kind, label, row_ids, req_ids, gap_count, fix, fix_label }],\n the scheme\'s gap kinds with the ids behind each, in the same order and wording the app banner uses.\n gap_count is how many gaps the kind stands for: its rows, or its requirements, or 1 for a kind\n that is one fact about the ANALYSIS and therefore carries neither list.\n hara: unmitigated, no_test (no test on its ODD), no_parent (safety requirement at the system\n level with no parent)\n medical: no_control (a risk above Low), not_verified, no_residual, no_parent (risk control at the\n system level with no parent), no_scope (the analysis holds rows but states no intended\n use, ISO 14971:2019 5.2) and no_overall (every row is controlled and residual-rated but\n the overall residual risk is not judged, ISO 14971:2019 clause 8); both are written on\n the analysis id with atoms_fill_row\n FMEA: rpn (RPN 100 or above with no mitigating requirement), severity (severity 9 or above\n below RPN 100 with no mitigating requirement, the REQ-ANL-047 floor; a row is under one\n kind, never both); an FMEA has no requirement-scope kind, so no project-wide scan runs\n for it\n and system_level, system_level_source: the level the no_parent kind was judged against. The system\n level is the SECOND rung of the project\'s level ladder (metadata.levels, positional: the L1 of\n REQ-ASH-031), matched against tags.level by name; source is "taxonomy". Only when the ladder has\n fewer than two rungs does the literal "L1" apply, and source then reads "fallback".\n\nA row counts as mitigated when a live requirement mitigates it, whichever side stored the link\n(the row\'s mitigated_by or the requirement\'s mitigates), read the way the app\'s analysis grid reads\nit; a link to the row itself, to a test case or to another analysis row does not count. The gaps\nlist and gap_kinds read this.',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),analysis_id:l.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_propose_rows",{title:"Write Proposed Analysis Rows",description:"Write rows YOU have drafted for one function into a HARA / risk analysis / FMEA (a DFMEA, a\nPFMEA, a Software FMEA or a Use FMEA). The analysis carries its standard: the rows are validated\nagainst the scheme its stored variant selects.\n\nThe drafting is the assistant's job: read the analysis with atoms_get_analysis (its scope, its\nODD / operating modes and its existing rows), draft the rows, then send them here. This tool\nvalidates every value against the analysis's scheme and writes the rows; it never invents a value.\n\nRequires editor or admin role. Every written value is marked as MCP-sourced and every row is\nwritten UNAPPROVED: a person approves it with atoms_approve_row.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the analysis\n - analysis_id (string): Analysis ID (e.g. \"HARA-001\", \"RA-001\", \"PFMEA-002\")\n - source_function (string, risk analysis only): the function these rows analyse; registered\n as a function-flagged tag if new (matching is case-insensitive and trimmed); a name that is\n already a domain is refused, never flagged (atoms_update_domain is_function=true)\n - source_req (string, FMEA only): the requirement these rows analyse\n - rows (object[], 1 to 8): the drafted rows, each a field name to value map using the\n analysis's scheme keys (the same keys atoms_fill_row accepts, plus 'effect', and 'title'\n on a risk analysis row). A risk analysis row sent without a title is named by its\n failure_mode (the hazard), else by its hazard; an FMEA row by its failure_mode. The cap of 8\n is shared with the app and the assistant; a longer list is refused, never truncated.\n The derived level (asil / rpn / risk) and the approval keys are refused by name.\n\nReturns:\n { analysis_id, subtype, scheme, variant?, labels, source_function | source_req,\n rows: [{ id, written_fields, computed_level }], count, max_rows, approved: false,\n link_warnings?, warning? }\n\nSide effects:\n - Creates one row item per drafted row, attached to the analysis (row ids follow the scheme: SG-n or RSK-n, FM-n or PF-n)\n - Marks every written field field_source='mcp' and leaves each row unapproved\n - Logs each created row to change_history with actor='mcp_<client>'\n\nIf a function name cannot be added to the project's Functions list, the write still succeeds and the\nanswer carries unregistered_functions (the names) and function_warning (how to add them).",inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),analysis_id:l.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),rows:l.z.array(l.z.record(l.z.string().max(64),l.z.union([l.z.string().max(5e4),l.z.number()]))).min(1).max(Vr).describe(`The drafted rows (1-${Vr}), each a scheme field name to value map`),source_function:l.z.string().min(1).max(100).optional().describe("Risk analysis only: the function these rows analyse"),source_req:l.z.string().min(1).max(20).optional().describe("FMEA only: the requirement these rows analyse"),idempotency_key:Fh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_propose_rows",async e=>{const{proposeRowsHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_suggest_field",{title:"Write a Suggested Value for One Analysis Field",description:"Write ONE value YOU have suggested for one field of one analysis row.\n\nThe suggestion is the assistant's job (Suggest evidence, Suggest safety goal, Suggest risk control\nstatement); this tool is the write half: it validates the value against the row's scheme, writes it marked as MCP-sourced and\nreturns the row. A suggested rating is written together with its rationale: pass 'rationale' and\nit lands in the scheme's evidence field for that rating (severity -> s_rationale, exposure ->\ne_rationale, controllability -> c_rationale, p1 -> p1_rationale, p2 -> p2_rationale, and the\nsingle 'rationale' column on an FMEA).\n\nAccepting a suggestion is a client action: it flips that one field's field_source to 'user'. The\nrow stays unapproved either way, until atoms_approve_row records who approved it.\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. \"SG-001\", \"RSK-002\", \"FM-003\", \"PF-004\")\n - field (string): the field to fill (any key atoms_fill_row accepts for this row's scheme)\n - value (string | number): the suggested value; a rating must be one the scheme allows\n - rationale (string, optional): the evidence behind a suggested RATING\n\nReturns:\n { row_id, subtype, scheme, field, field_source: \"mcp\", written_fields,\n rationale_field?, approval_cleared?, row: { id, computed_level, approved, mcp_fields, ...scheme fields } }\n approval_cleared: true means the row WAS approved and this suggestion cleared approved, approved_by,\n approved_at and approved_note: a signature never covers content the approver did not see.\n\nSide effects:\n - Saves the row with stale-write protection and logs to change_history\n - Marks the written field(s) field_source='mcp'; the row stays unapproved\n - On an approved row: clears the approval (history-logged with the reason)\n - hara: a source_function is registered in the project's Functions list as atoms_fill_row\n registers it (a domain is refused). If it cannot be added, the write still succeeds and the\n answer carries unregistered_functions (the names) and function_warning (how to add them).",inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),row_id:l.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),field:l.z.string().min(1).max(64).describe("The field to fill (a scheme key of this row)"),value:l.z.union([l.z.string().max(5e4),l.z.number()]).describe("The suggested value"),rationale:l.z.string().max(5e4).optional().describe("The evidence behind a suggested rating; written to the scheme's evidence field"),base_token:Lh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_suggest_field",async e=>{const{suggestFieldHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_approve_row",{title:"Approve an Analysis Row in a Named Person's Name",description:'Record the sign-off of ONE analysis row, naming who approved it.\n\nRequires editor or admin role. The approver must be a member of the project\'s organization: a\nname that cannot be traced to a member is refused, never stored. The note is optional. Approving\nclears the machine-proposed (✦) markers on the row: the approver takes those values as their own.\nA row whose ratings are incomplete cannot be approved (its level is unset), matching the grid.\n\nThis tool signs off one analysis row. It has nothing to do with change control: it never\napproves, dismisses or applies a suggestion (REQ-CHG-062).\n\nIn any security risk analysis row, E is exploitability: the ease of exploiting the vulnerability across the device lifecycle, never a probability.\nArgs:\n - project_id (string, UUID): Project containing the row\n - row_id (string): Analysis row ID (e.g. "SG-001", "RSK-002", "FM-003", "PF-004")\n - approver_id (string, UUID, optional): the approving member; defaults to the calling user\n - note (string, optional): the note captured with the approval\n\nReturns:\n { row_id, subtype, scheme, approved: true, approved_by, approved_at, approved_note,\n approver_role, computed_level, cleared_markers }\n\nSide effects:\n - Saves the row with stale-write protection: approved, approved_at, approved_by, approved_note\n - Flips every field_source=\'mcp\' entry on the row to \'user\'\n - Logs the approval (previous and new values) to change_history',inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),row_id:l.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),approver_id:l.z.string().uuid().optional().describe("The approving project member; defaults to the calling user"),note:l.z.string().max(2e3).optional().describe("Optional note captured with the approval"),base_token:Lh},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_approve_row",async e=>{const{approveRowHandler:t}=await Promise.resolve().then(()=>(Ah(),Zf));return t(e)})),Mh("atoms_list_scenario_catalogs",{title:"List Operational Scenario Catalogs",description:Xc.atoms_list_scenario_catalogs,inputSchema:{project_id:l.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),limit:l.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:l.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Kh("atoms_list_scenario_catalogs",async e=>{const{listScenarioCatalogsHandler:t}=await Promise.resolve().then(()=>(Bh(),Ih));return t(e)})),Mh("atoms_mutate_scenario_catalog",{title:"Mutate an Operational Scenario Catalog",description:Xc.atoms_mutate_scenario_catalog,inputSchema:{project_id:l.z.string().uuid().describe("UUID of the project"),op:l.z.enum(["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]).describe("The mutation to apply"),catalog_id:l.z.string().min(1).max(64).optional().describe("The catalog id (optional for create_catalog: generated when omitted)"),name:l.z.string().min(1).max(100).optional().describe("The catalog name (create_catalog, rename_catalog)"),entry_id:l.z.string().min(1).max(64).optional().describe("The entry id (caller-generated for add_entry)"),text:l.z.string().min(1).max(100).optional().describe("The entry's operational scenario text"),function_tags:l.z.array(l.z.string()).optional().describe("The functions this entry applies to; [] = every function"),by:l.z.string().min(1).max(200).optional().describe("The accepter's name (accept_catalog)"),on:l.z.string().min(1).max(32).optional().describe("The acceptance date (accept_catalog)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Kh("atoms_mutate_scenario_catalog",async e=>{const{mutateScenarioCatalogHandler:t}=await Promise.resolve().then(()=>(Bh(),Ih));return t(e)})),le()}});fe(),ce(),ko(),ae();var ty=u.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href)("../package.json"),ny=process.argv.slice(2)[0];(async function(){switch(ny){case"login":{const{login:e}=await Promise.resolve().then(()=>($o(),So));try{const{email:t}=await e();process.stderr.write(`\n ✓ Authenticated as ${t}\n`),process.stderr.write(" ✓ Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" Next steps:\n"),process.stderr.write(" $ claude mcp add atoms -- npx -y @atoms-tech/atoms-mcp@latest\n"),process.stderr.write("\n Or add to Claude Desktop (Settings → MCP → Edit Config):\n"),process.stderr.write(' {\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp@latest"]\n }\n }\n }\n\n')}catch(e){process.stderr.write(`\n ✗ ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>(at(),Xe));try{const{email:t,user_id:n}=await e();process.stderr.write(`\n ✓ Logged in as ${t}\n User ID: ${n}\n\n`)}catch(e){process.stderr.write(`\n ✗ Not authenticated: ${e instanceof Error?e.message:String(e)}\n Run: npx @atoms-tech/atoms-mcp@latest login\n\n`),process.exit(1)}break}case"logout":{const{clearCredentials:e}=await Promise.resolve().then(()=>(qe(),he));await e(),process.stderr.write("Logged out. Credentials removed.\n"),process.stderr.write("Run 'npx @atoms-tech/atoms-mcp@latest login' to authenticate again.\n");break}case"--version":case"-v":process.stderr.write(`@atoms-tech/atoms-mcp v${ty.version}\n`);break;case"--help":case"-h":process.stderr.write("ATOMS MCP Server — AI agent integration for requirements management\n\nUsage:\n npx @atoms-tech/atoms-mcp@latest Start MCP server (stdio)\n npx @atoms-tech/atoms-mcp@latest login Authenticate with ATOMS.tech\n npx @atoms-tech/atoms-mcp@latest logout Switch account / clear credentials\n npx @atoms-tech/atoms-mcp@latest whoami Show current user\n npx @atoms-tech/atoms-mcp@latest --version Show version\n");break;default:{process.stderr.write("[atoms-mcp] Starting MCP server via stdio...\n");let t=!0;try{const{startupAuth:e}=await Promise.resolve().then(()=>(Mo(),Eo)),n=await e();t=null!==n,n&&process.stderr.write(`[atoms-mcp] Authenticated as ${n}\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@latest login\n`)}if(t)try{const t=await co(),n=_o(),r=await Q(t,n),a=await G(t,n,r);e={effective:a.effective,role:a.role,org_id:r},K=e.effective,Y=e.org_id,Z=Date.now(),te=!0,ie(a,r)}catch(e){se(),process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). Changes are paused until it loads; RLS still enforces row-level access.\n`)}else se(),process.stderr.write("[atoms-mcp] Org policy not loaded (ATOMS sign-in check unavailable). Reads work; changes are paused until it loads.\n");process.stderr.write(`[atoms-mcp] Tool registry: ${function(){const e=ue(),t=de(),n=[];n.push(e?"read-only":"read+write"),null===t?n.push("all toolsets"):(n.push(`toolsets=${[...t.allowed].sort().join(",")||"(none — only always-on tools)"}`),t.unknown.length>0&&n.push(`unknown=${t.unknown.join(",")}`));const r=process.env.ATOMS_MCP_PROJECT_ID?.trim();return r&&n.push(`project_scope=${r.slice(0,8)}…`),("1"===process.env.ATOMS_MCP_LOCKDOWN||"true"===process.env.ATOMS_MCP_LOCKDOWN)&&n.push("lockdown=on"),n.join(" | ")}()}\n`);const{server:n}=await Promise.resolve().then(()=>(ey(),Jh)),r=new p.StdioServerTransport;await n.connect(r);const{startUpdateCheck:a}=await Promise.resolve().then(()=>(Ol(),sl));a(),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)});