@atoms-tech/atoms-mcp 0.99.0 → 0.100.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";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("@modelcontextprotocol/ext-apps/server"),d=require("@modelcontextprotocol/sdk/server/mcp.js"),c=require("zod"),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,g,y,w,v,b,k,j,S,A,$,x,I,q,O,E,z=_(e),M=_(n),R=_(i),T=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)T(e,n,{get:t[n],enumerable:!0})};function N(e){return k.get(e)}var P,F,U,L,W,V,B=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","atoms_create_model_design","atoms_update_model_design"]),g=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_level","atoms_delete_field","atoms_restore_baseline"]),y={atoms_mutate_scenario_catalog:{param:"op",values:["delete_catalog"]},atoms_link_items:{param:"action",values:["remove"],arrayParam:"operations"},atoms_link_mitigation:{param:"action",values:["remove"]}},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","atoms_list_model_designs","atoms_get_model_design","atoms_create_model_design","atoms_update_model_design"],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),k=new Map;for(const[e,t]of Object.entries(v))for(const n of t)k.set(n,e);j="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.",$="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.",I="Ignored on projects that save one field at a time; send base_token instead.",q="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.",O="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.",E="If a call answers code rate_limited, wait retry_after_seconds seconds before calling again. Do not retry sooner."}}),J=D({"src/core/types.ts"(){P={read_only:!1,lockdown:!1,block_destructive:!1,block_bulk_import:!1,cross_project_browse:!0,allowed_toolsets:["items","traceability","coverage","variables","domains","baselines","analysis"],forbidden_tools:[],project_scope:null,require_confirmation_for:[]},F={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 G(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&&g.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=N(t);return void 0===n||e.allowed_toolsets.includes(n)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function Q(e){switch(e){case"lockdown":return"This project's organization puts MCP in lockdown for your role: on its projects only atoms_list_items, atoms_get_item, atoms_search and atoms_browse work.";case"read_only":return"This project's organization puts MCP in read-only mode for your role, so its projects take no changes through MCP.";case"block_destructive":return"Your org policy blocks destructive operations (deletes, link removals, snapshot restore).";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."}}function K(e){const t=/^(?:Database error: )?(mcp_policy_(read_only|lockdown|block_destructive|block_bulk_import|project_scope|forbidden_tool)): (.+?) is blocked by your org's MCP Access Policy \(/.exec(e);if(!t)return null;const[,n,r,a]=t;return{status:"error",message:`${a.charAt(0).toUpperCase()}${a.slice(1)} is blocked by org policy. This change was not saved.`,next_steps:["project_scope"===r?W:Q(r),"Contact your org admin to adjust the MCP access policy.","Do not retry this call."],code:n,retryable:!1}}function Y(e,t,n=0){const r=e.project_scope;if(null===r)return null;if(0===t.length&&0===n)return null;if(0===r.length)return{status:"error",message:L,next_steps:["No tool works on this organization's projects while its Project scope is No projects (atoms_status and atoms_list_projects still work)","An org admin can change Project scope in the MCP policy of Org Settings"]};const a=[`Allowed projects: ${r.length} project${1===r.length?"":"s"} configured by your admin`,"Use atoms_list_projects to see which projects you can access in this session"];return n>0?{status:"error",message:V,next_steps:a}:t.some(t=>!function(e,t){return null===e.project_scope||e.project_scope.includes(t)}(e,t))?{status:"error",message:W,next_steps:a}:null}function Z(){return{status:"error",message:"Project scope check failed.",next_steps:["ATOMS could not confirm which project this call targets, so the call was refused","Retry in a moment; if it keeps failing, run atoms_status"]}}var X,ee,te,ne,re=D({"src/core/policy.ts"(){B(),U="Your organization's MCP policy could not be read just now. Nothing was run. Try again in a moment.",L="Your admin set Project scope to No projects for your role. Ask an org admin to change it.",W="Tool call rejected: project_id is outside your org's MCP project scope.",V="Tool call rejected: this baseline is not in a project your org's MCP project scope allows, or could not be found."}});async function ae(e,t){const{data:n,error:r}=await e.from("org_members").select("org_id, role").eq("user_id",t);if(r)throw new Error(r.message??String(r));return Array.isArray(n)?n:n?[n]:[]}function ie(e){return e.length>0&&e.every(e=>"viewer"===e.role)}function se(e){return new Set(e.filter(e=>"viewer"===e.role&&"string"==typeof e.org_id).map(e=>e.org_id))}async function oe(e,t){const n=t&&"object"==typeof t?t:{},r="string"==typeof n.project_id?[n.project_id]:[];let a=0;for(const t of["baseline_id","baseline_a_id","baseline_b_id"]){const i=n[t];if("string"!=typeof i)continue;const s=await de(e,i);s?r.push(s):a++}return{projectIds:r,unresolved:a}}async function le(e,t){const{data:n,error:r}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(r)throw new Error(r.message??String(r));const a=n?.org_id;return"string"==typeof a?a:null}async function de(e,t){const{data:n,error:r}=await e.from("baselines").select("project_id").eq("id",t).maybeSingle();if(r)throw new Error(r.message??String(r));const a=n?.project_id;return"string"==typeof a?a:null}function ce(){return{status:"error",message:"Authorization check failed.",next_steps:["ATOMS could not confirm your role in this project's organization, so the call was refused","Retry in a moment; if it keeps failing, run atoms_status"]}}var ue,pe,me,_e=D({"src/core/viewer-gate.ts"(){X="Viewers cannot use the ATOMS MCP. Ask an org admin for editor access.",ee=["Your role in this project's organization is viewer, and viewers cannot use ATOMS tools","Read the project in the ATOMS web app, or ask an org admin to make you an editor"],te=["You are a viewer in every organization you belong to, so no ATOMS tool can be used","Read your projects in the ATOMS web app, or ask an org admin to make you an editor"],ne=new Set(["atoms_status"])}});function fe(e,t=new Map){return{orgs:e,projectOrgs:t}}function he(e){const t="string"==typeof e?.code?e.code:"";return""===t||/^PGRST00[0-3]$/.test(t)}function ge(e,t){return e.orgs.find(e=>e.orgId===t)?.effective??F}function ye(e){if(0===e.orgs.length)return P;if(1===e.orgs.length)return e.orgs[0].effective;const t=e.orgs.map(e=>e.effective),n=e=>t.some(t=>!0===t[e]),r=e=>e.reduce((e,t)=>e.filter(e=>t.includes(e))),a=e=>[...new Set(e.flat())],i=t.map(e=>e.project_scope).filter(e=>null!==e);return{read_only:n("read_only"),lockdown:n("lockdown"),block_destructive:n("block_destructive"),block_bulk_import:n("block_bulk_import"),cross_project_browse:t.every(e=>!0===e.cross_project_browse),allowed_toolsets:r(t.map(e=>e.allowed_toolsets)),forbidden_tools:a(t.map(e=>e.forbidden_tools)),project_scope:0===i.length?null:[...new Set(r(i))],require_confirmation_for:a(t.map(e=>e.require_confirmation_for))}}function we(e,t){return!!f.has(t)||(0===e.orgs.length?G(P,t).allowed:e.orgs.some(e=>G(e.effective,t).allowed))}function ve(e,t,n){const r=G(e,t);if(!r.allowed)return{status:"error",message:`Tool ${t} is blocked by org policy.`,next_steps:[Q(r.reason),"Contact your org admin to adjust the MCP access policy."]};const a=function(e,t,n){const r=y[t];if(!e.block_destructive||!r)return{allowed:!0};const a=n??{},i=r.arrayParam&&Array.isArray(a[r.arrayParam])?a[r.arrayParam]:[],s=[a[r.param],...i.map(e=>e?.[r.param])].find(e=>"string"==typeof e&&r.values.includes(e));return void 0===s?{allowed:!0}:{allowed:!1,reason:"block_destructive",message:`Tool ${t} op ${s} is blocked by org policy.`}}(e,t,n);return a.allowed?null:{status:"error",message:a.message,next_steps:[Q(a.reason),"Contact your org admin to adjust the MCP access policy."]}}async function be(e,t,n){const r=t.projectOrgs.get(n);if("string"==typeof r)return r;const a=await le(e,n);return null!==a&&t.projectOrgs.set(n,a),a}function ke(e,t){if(e.orgs.length<=1)return e.orgs[0]?.effective??P;const n=t?e.projectOrgs.get(t):void 0;return"string"==typeof n?ge(e,n):ye(e)}var je,Se,Ae=D({"src/core/org-policy.ts"(){J(),re(),B(),_e(),ue=["baseline_id","baseline_a_id","baseline_b_id"],pe=new Set(["atoms_create_item","atoms_update_item","atoms_bulk_import"]),me=class extends Error{name="PolicyTransientError"}}});function $e(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?je.test(e)?e:(Se||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),Se=!0),null):null}function xe(){return process.env.ATOMS_MCP_ORG_ID?.trim()||null}var Ie=D({"src/middleware/project-scope.ts"(){je=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Se=!1}});async function qe(e,t,n){return async function(e,t,n=new Map){const r=await Promise.all(e.map(t));return fe(e.map((e,t)=>({orgId:e,role:r[t].role,effective:r[t].effective,failedClosed:r[t].effective===F})),n)}(await async function(e,t){try{const n=await async function(e,t){const{data:n,error:r}=await e.from("org_members").select("org_id, joined_at, organizations!inner(status)").eq("user_id",t).eq("organizations.status","active").neq("role","viewer").order("joined_at",{ascending:!0});if(r)throw new Error(r.message??String(r));const a=Array.isArray(n)?n:n?[n]:[];return[...new Set(a.map(e=>e.org_id).filter(e=>"string"==typeof e))]}(e,t),r=xe();return r?n.filter(e=>e===r):n}catch(e){const t=e instanceof Error?e.message:String(e);throw process.stderr.write(`[atoms-mcp] Could not resolve session org: ${t}\n`),new Error(`Could not resolve session org: ${t}`)}}(e,t),n=>async function(e,t,n){if(!n)return{role:null,is_member:!1,effective:P};const{data:r,error:a}=await async function(e,t,n){const r={p_user_id:t,p_org_id:n},a=await e.rpc("mcp_resolve_policy",r);return a.error&&he(a.error)?await e.rpc("mcp_resolve_policy",r):a}(e,t,n);if(a&&he(a))throw process.stderr.write(`[atoms-mcp] mcp_resolve_policy unreachable: ${a.message}. Changes are paused until it loads.\n`),new me(String(a.message??"mcp_resolve_policy unreachable"));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:F}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:P};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.filter(e=>"string"==typeof e):null;return{role:n,is_member:r,effective:{read_only:s(a.read_only,P.read_only),lockdown:s(a.lockdown,P.lockdown),block_destructive:s(a.block_destructive,P.block_destructive),block_bulk_import:s(a.block_bulk_import,P.block_bulk_import),cross_project_browse:s(a.cross_project_browse,P.cross_project_browse),allowed_toolsets:i(a.allowed_toolsets,P.allowed_toolsets),forbidden_tools:i(a.forbidden_tools,P.forbidden_tools),project_scope:l,require_confirmation_for:i(a.require_confirmation_for,P.require_confirmation_for)}}}(r)}(e,t,n),n)}var Oe,Ee,ze,Me,Re,Te,Ce,De,He=D({"src/db/policy.ts"(){Ae(),Ie(),J()}});function Ne(e){if(0!==e.orgs.length)for(const t of e.orgs)process.stderr.write(t.failedClosed?`[atoms-mcp] Org policy could not be read: org=${t.orgId.slice(0,8)}… (its projects are refused until it can be read)\n`:`[atoms-mcp] Org policy loaded: org=${t.orgId.slice(0,8)}… role=${t.role??"?"} read_only=${t.effective.read_only} lockdown=${t.effective.lockdown}\n`);else process.stderr.write("[atoms-mcp] No org membership detected — running with permissive default policy.\n")}function Pe(){Re=!1}function Fe(){return Oe}function Ue(){const e=De,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 Ce){const n=we(Oe,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?.()}async function Le(e,t){Re&&Date.now()-Ee<=ze||(Me||(Me=(async()=>{try{const n=await qe(e,t,Oe.projectOrgs);Oe=n,Re||Ne(n),Re=!0,Te=!1}catch(e){Re=!1,Te=e instanceof me}Ee=Date.now(),Ue()})().finally(()=>{Me=null})),await Me)}var We=D({"src/middleware/session-policy.ts"(){Ae(),He(),Oe=fe([]),Ee=Date.now(),ze=3e4,Me=null,Re=!0,Te=!1,Ce=new Map,De=null}});function Ve(){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 Be(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function Je(e){if(Be()&&h.has(e))return!1;if(f.has(e))return!0;const t=Ve();if(null===t)return!0;const n=N(e);return!!n&&t.allowed.has(n)}var Ge,Qe,Ke=D({"src/middleware/tool-registry.ts"(){B(),Ae(),We()}}),Ye={};async function Ze(){try{const t=await e.readFile(Qe,"utf-8"),n=JSON.parse(t);return n.access_token&&n.refresh_token?n:null}catch{return null}}async function Xe(t){await e.mkdir(Ge,{recursive:!0,mode:448}),await e.writeFile(Qe,JSON.stringify(t,null,2),{mode:384})}async function et(){const e=await Ze();return!!e&&e.expires_at>Date.now()+6e4}function tt(e){return e.expires_at>Date.now()+6e4}async function nt(){try{await e.unlink(Qe)}catch{}}function rt(){return Qe}H(Ye,{clearCredentials:()=>nt,getCredentialsPath:()=>rt,hasValidCredentials:()=>et,isTokenValid:()=>tt,readCredentials:()=>Ze,writeCredentials:()=>Xe});var at,it,st,ot,lt,dt,ct,ut=D({"src/auth/token-store.ts"(){Ge=n.join(t.homedir(),".atoms"),Qe=n.join(Ge,"credentials.json")}}),pt={};async function mt(){try{await e.mkdir(at,{recursive:!0,mode:448});const t=await e.open(it,"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 _t(){try{await e.unlink(it)}catch{}}async function ft(){try{const t=await e.stat(it);return Date.now()-t.mtimeMs>st}catch{return!1}}async function ht(e,t,n=ct){const r=n.now()+ot;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(lt)}}}H(pt,{runExclusiveAuth:()=>ht});var gt,yt,wt,vt=D({"src/auth/lock.ts"(){at=n.join(t.homedir(),".atoms"),it=n.join(at,".auth.lock"),st=7e4,ot=12e4,lt=300,dt=e=>new Promise(t=>setTimeout(t,e)),ct={now:Date.now,wait:dt,tryAcquire:mt,release:_t,isStale:ft}}}),bt={};function kt(e){return e.trim().replace(/\/+$/,"")}H(bt,{ATOMS_APP_URL:()=>wt,ATOMS_SUPABASE_ANON_KEY:()=>yt,ATOMS_SUPABASE_URL:()=>gt,resolveUrl:()=>kt});var jt,St,At,$t,xt,It=D({"src/config.ts"(){gt=kt(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),yt=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",wt=process.env.ATOMS_APP_URL??"https://atoms.tech"}});function qt(e){return e instanceof $t||!!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||!!xt.statuses.includes(n)||xt.codedStatuses.includes(n)&&"string"==typeof r&&xt.codes.includes(r)}(e)}function Ot(){return{status:"error",code:jt,retryable:!0,message:At,next_steps:[`Wait ${St} seconds, then retry the same call`,"Do not sign out or log in again: the saved session is still valid"]}}var Et,zt,Mt=D({"src/core/auth-outage.ts"(){jt="auth_unavailable",St=5,At="ATOMS could not check your sign-in just now. Your session is kept. Try again in a moment.",$t=class extends Error{code=jt;constructor(e){super(`${jt}: ${e}`),this.name="AuthServiceUnavailableError"}},xt={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"]}}}),Rt={};async function Tt(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=Dt(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await Ze();if(t&&t.expires_at>Date.now()+6e4){const e=Dt(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 Ct(){const e=await Tt();if(e)return e;const t=await Ze();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp@latest login' to connect your ATOMS account.");return ht(async()=>{const e=await Tt();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(gt,yt,{global:{fetch:zt}});let n=await t.auth.refreshSession({refresh_token:e.refresh_token});if(n.error||!n.data.session){const r=await Ze();if(r&&r.expires_at>Date.now()+6e4){const e=Dt(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(qt(n.error))throw new $t(`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 Xe({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 Dt(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(Rt,{AUTH_CALL_TIMEOUT_MS:()=>Et,getValidToken:()=>Ct,readValidToken:()=>Tt});var Ht,Nt,Pt=D({"src/auth/refresh.ts"(){ut(),vt(),It(),Mt(),Et=1e4,zt=async(e,t)=>{const n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Auth did not answer within ${Et} ms`)),Et),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 Ft(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,Nt).replace(/_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?Ht:t:Ht}function Ut(e){const t=Ft(e);return"cursor"===t?"mcp_cursor":"copilot"===t?"mcp_copilot":"mcp_claude"}var Lt,Wt,Vt,Bt,Jt,Gt,Qt=D({"src/core/client-identity.ts"(){Ht="claude_desktop",Nt=64}});function Kt(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}function Yt(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 Zt(e){return/token refresh failed|saved atoms session is no longer valid|jwt\s*expired|invalid.?jwt|jwt.*invalid|pgrst30[12]/i.test(e)}function Xt(e){return"string"==typeof e&&e.includes(Vt)}function en(e){return"string"==typeof e&&e.includes(Bt)}function tn(e){return"project"===e?{status:"error",message:"An org admin is needed to change this project's field definitions.",next_steps:["Ask an admin of this organization 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"]}}function nn(e,t){const n=Array.isArray(t.next_steps)?t.next_steps:[];return[`Do not re-send the whole batch: the ${e} committed operation(s) would be applied again.`,...!1===t.retryable?[]:["Reconcile from the committed list, then retry only the failed and any remaining operations."],...n]}function rn(e){const t=Gt.exec(e);if(!t)return null;const[,n,r,a]=t;return{status:"error",message:`${r} cannot be a parent of ${n}, because ${n} is already above ${r}${a.trim()?` (${a.trim()})`:""}. That link would make a loop, so nothing was saved.`,next_steps:["Do not retry this call: the same link is refused every time.",`Choose another parent for ${n}, or first remove the link that puts ${n} above ${r}.`],code:"hierarchy_cycle",retryable:!1}}var an=D({"src/core/errors.ts"(){Lt=[/^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 /,/^event_source .* is not allowed \(allowed: web, mcp\)/s],Wt=class extends Error{},Vt="rollout_switched:multiuser_saving: This project still saves whole items. Reload, then save again.",Bt="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.",Jt=10,Gt=/^(?:[A-Za-z_][\w ]{0,60}:\s+){0,2}hierarchy_cycle:\s+(\S+) cannot go under (\S+) because \S+ is already above it \(([^)]*)\)/}});function sn(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function on(e){return e.replace(/[\\%_*]/g,e=>`\\${e}`)}function ln(e){return sn(`*${on(e)}*`)}function dn(e){return on(e)}function cn(e){return`*"${on(e)}"*`}async function un(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 pn,mn,_n,fn,hn,gn,yn,wn,vn,bn,kn,jn,Sn=D({"src/core/postgrest.ts"(){}});async function An(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(a,n);void 0!==a&&(s=s.or(xn(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(`${$n(s)} read, page ${i}: ${l.message}`);const d=o??[];if(0===d.length)return r;const c=d[d.length-1];if(void 0!==a&&t.every(e=>String(c[e])===String(a[e])))throw new Error(`${$n(s)} read, page ${i}: the page did not move past the last row read`);r.push(...d),a=c}}function $n(e){const t=e.url;return t instanceof URL?decodeURIComponent(t.pathname).replace(/^.*\/rest\/v1\//,""):"query"}function xn(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 sn(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 In(e,t,n,r){return An(()=>e.rpc(t,{p_project_id:n,p_snapshot_at:r}),hn[t])}function qn(e,t,n){return"baselineId"in n?An((t,r)=>e.rpc("baseline_state_page",{p_baseline_id:n.baselineId,p_after_id:t?.id??null,p_limit:r}),pn):In(e,"project_state_at",t,n.at)}function On(e,t,n){return"baselineId"in n?An(()=>e.rpc("baseline_variables_state",{p_baseline_id:n.baselineId}),fn):In(e,"variables_at",t,n.at)}async function En(e,t){const n=[];for(let r=0;r<e.length;r+=wn){const{data:a,error:i}=await t(e.slice(r,r+wn));if(i)throw new Error(i.message);n.push(...a??[])}return n}function zn(e,t){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(kn(t)?[e.created_at,e.id,t]:[e.created_at,e.id]))}var Mn,Rn,Tn,Cn,Dn,Hn,Nn,Pn,Fn,Un,Ln,Wn,Vn,Bn,Jn,Gn,Qn,Kn,Yn,Zn,Xn,er,tr,nr,rr,ar,ir,sr,or,lr,dr,cr,ur,pr,mr,_r,fr,hr,gr,yr,wr,vr,br,kr=D({"src/core/paginate.ts"(){Sn(),mn=["from_id","to_id","type"],_n=["name","id"],hn={project_state_at:pn=["id"],variables_at:fn=["name","id"]},gn=e=>({at:e}),yn=e=>({baselineId:e}),wn=200,vn=100,bn=["created_at","id"],kn=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0,jn=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 jr(e){return/rollout_switched:multiuser_saving/i.test(e)}function Sr(){return{status:"error",message:Rn,next_steps:[Tn],code:"rollout_switched",retryable:!1}}function Ar(e){return/project_in_trash/i.test(e)||e===Dn}function $r(){return{status:"error",message:Cn,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 xr(e){return e===Nn||/not a member of this project's organization/i.test(e)||/\b[a-z_]+: not a member of this project\s*$/i.test(e)}function Ir(){return{status:"error",message:Hn,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 qr(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 Or(e){const t=/approved_item_delete_blocked: ([^\s;:]{1,60}) /.exec(e);return t?{status:"error",message:`${t[1]}: ${Pn}. Nothing was changed.`,next_steps:["Do not retry this call.","Only a project admin releasing review on the project removes the block, and that returns every item to draft.","Use atoms_get_item to read the item."],code:"approved_item_delete_blocked",retryable:!1}:null}function Er(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&&Yt(t.message)?new Error(t.message):t&&"42501"!==t.code||!Fn.test(e)?new Error(`Project '${e}' not found`):new Error(Nn)}function zr(e){return/too_many_items/.test(e)}function Mr(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 Rr(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 Tr(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":Tr(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)}:${Tr(t[e])}`).join(",")}}`}return"null"}async function Cr(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 Dr(e,t,n="item"){return e&&"object"==typeof e?"variable"===n?"variables"!==t[0]?null:t.length<=2?e:Hr(e[t[2]],t.slice(3)):0===t.length?e.data??null:Gn.has(t[0])?1===t.length?e[t[0]]??null:null:Hr(e.data,t):null}function Hr(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 Nr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pr(e,t){return e.length<=t.length&&e.every((e,n)=>e===t[n])}function Fr(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=>Pr(e,t)));if(0===t.length||Qn.has(t[0]))return!1;switch(r){case"item":case"all":return!0;case"core":return Wn.some(e=>Nr(e,t));case"analysis":return Nr(t,["title"])||Nr(t,["body"])||("analysis_props"===t[0]||"relationships"===t[0])&&t.length>=2;case"paths":return(a??[]).some(e=>Pr(e,t))}return!1}async function Ur(e,t,n="item"){let r;if("string"!=typeof t)r=t.paths.map(t=>Dr(e,t,n));else if("core"===t||"analysis"===t){const a="core"===t?Wn:Vn;r=Object.fromEntries(a.map(t=>[JSON.stringify(t),Dr(e,t,n)]))}else r=e??null;return(await Cr(Tr(r))).slice(0,16)}function Lr(e,t,n){return`${e}.${t}~${function(e){return"string"==typeof e?e:`paths:${encodeURIComponent(JSON.stringify(e.paths))}`}(n)}`}async function Wr(e,t,n="item"){return Lr(e.id,await Ur(e.fields_snapshot,t,n),t)}function Vr(e){if("string"!=typeof e||0===e.length||e.length>Un)return null;const t=Jn.exec(e);if(!t)return null;const n=t[1].toLowerCase(),r=t[2].toLowerCase(),a=t[3];if(Bn.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 Br(e){return"variable"===e?{table:"variable_revisions",idCol:"variable_id"}:{table:"item_revisions",idCol:"item_id"}}function Jr(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 Gr(e,t){return new Error(String(e?.message??`${t} failed`))}async function Qr(e,t,n,r="item"){const a=new Map,i=[...new Set(n)],{table:s,idCol:o}=Br(r);for(let n=0;n<i.length;n+=vn){const{data:r,error:l}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in(o,i.slice(n,n+vn)).is("valid_to",null).is("deleted_at",null);if(l)throw Gr(l,`${s} read`);for(const e of r??[]){const t=Jr(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 Kr(e,t,n,r="item"){const a=new Map,i=[...new Set(n)],{table:s,idCol:o}=Br(r);for(let n=0;n<i.length;n+=vn){const{data:r,error:l}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in("id",i.slice(n,n+vn));if(l)throw Gr(l,`${s} read`);for(const e of r??[]){const t=Jr(e,o);a.set(t.id,t)}}return a}async function Yr(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 Gr(r,"changes_since");const a=n?.head_seq;return"number"==typeof a?a:Number(a??0)}async function Zr(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 Gr(o,"fresh_typing_notes");for(const e of s??[]){const t=a.get(e.item_id)??[];t.push({path:e.path,field_label:Xr(e.path,r),person:{name:e.user_name??"Someone",kind:"person"}}),a.set(e.item_id,t)}return a}function Xr(e,t){if(!e||0===e.length)return"Item";const n=Yn[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 ea(e){return JSON.stringify(e)}async function ta(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=Vr(n);t?(e.parsed.push(t),r.push(t.revisionId)):e.bad=!0}n.set(t.itemId,e)}const a=await Kr(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 Ur(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)Fr(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(ea(n),{base:Dr(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 d=[];if(o.length>0){const n=await Qr(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);d.push({op_id:"",status:"conflict",reason:a.badToken?"bad_token":"no_base",...na(t,e.req),path:e.path,seq:null,current:r?Dr(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)&&d.push({op_id:"",status:"skipped",reason:"item_skipped",...na(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:d}}function na(e,t){return"variable"===e?{item_id:null,name:t.name??t.itemId,variable_id:t.itemId}:{item_id:t.itemId}}function ra(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 aa(e){return e?"agent"===e.kind?e.label??e.name??null:e.name??null:null}async function ia(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??""}|${ea(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 d=l.path??null;if(Zn.has(l.status)){const e={item_id:l.item_id??null,path:d,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=(d??[]).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:aa(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 c=(l.op_id?t.get(l.op_id):void 0)??n.get(`${l.item_id??""}|${ea(d??[])}`),u={item_id:l.item_id??null,...null===l.item_id&&l.name?{name:l.name}:{},path:d,field_label:Xr(d,e.labels),status:l.status,reason:l.reason??("skipped_typing"===l.status?"typing":"locked"===l.status?"item_locked":null)};c&&"value"in c?u.your_value=c.value:"sent"in l&&(u.your_value=l.sent),"relationships"===d?.[0]&&"string"==typeof u.your_value&&u.your_value.length<=ir&&(u.to_id=u.your_value);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&&d?(u.theirs_value=Dr(m.fields_snapshot,d),_={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:c&&"base"in c&&(u.base_value=c.base);const f=l.current_author??p?.change?.author??null;f&&(u.changed_by={kind:f.kind,name:aa(f)});const h=l.current_at??p?.change?.at??null;(f||h)&&(u.changed_at=h);const g=l.current_seq??p?.change?.seq;if(null!=g&&(u.seq=g),("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),_&&d){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=ea(a.path);t.has(s)||(t.add(s),n.push(a.path),r.push(e.rev?Dr(e.rev.fields_snapshot,a.path):i))}const a=(await Cr(Tr(r))).slice(0,16),i=Lr(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=oa(e,t),a.not_applied.push(da(e));return a.replayed=e.answers.length>0&&e.answers.every(e=>!0===e.replayed),a}function sa(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 oa(e,t){const n=sa(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&&"far"===t?.trashed_end&&t.trashed_id?`${n} ${r} not saved: the linked item ${t.trashed_id} is in the Trash.`:"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: ${aa(t?.change_author??null)??a} has an open change on ${"string"==typeof t?.change_item_id&&t.change_item_id?t.change_item_id: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"approved_item_delete_blocked"===s?`${n}: ${Pn}.`:`${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"asil_put_back":return`${n} ${r} not saved: a row that gives ${n} its ASIL was not saved, so nothing of ${n} was saved.`;case"link_end_skipped":return`${n} ${r} not saved: an item linked with ${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 String(t?.forbidden_reason??"").startsWith("mcp_policy_")?`${n} ${r} not saved: your org's MCP Access Policy does not allow this change.`:`${n} ${r} not saved: your role cannot change it.`;case"approved":return`${n} ${r} not saved: ${n} is approved.`;case"chunk_not_sent":return e.to_id?`${n} --[${e.path?.[1]??"link"}]--\x3e ${e.to_id} not saved: an earlier part of this call failed, so this part was not sent.`:`${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 la(e){if("string"==typeof e)return e.length;const t=JSON.stringify(e);return void 0===t?0:t.length}function da(e){const t={...e},n=[];for(const e of cr)e in t&&la(t[e])>Xn&&(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 ${Xn} characters and was left out. Read it with atoms_get_item (${sa(e)}), then send your change again.`),t}function ca(e){return"string"==typeof e?`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`:Array.isArray(e)?e.map(ca):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,ca(t)])):e}function ua(e){const t=new TextEncoder,n=t.encode(JSON.stringify(e)??"").length,r=t.encode(JSON.stringify(ca(e),null,2)??"").length;return Math.max(n,r)}function pa(e,t=ua){if(t(e)<=er)return e;const n=e.not_applied.map(e=>{const t={...e};let n=!1;for(const e of cr)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)<=er)return r;const a=n.map(e=>{const{message:t,hint:n,...r}=e;return r});if(r={...r,not_applied:a},t(r)<=er)return r;const{applied:i,...s}=r,o={...s,next_steps:r.next_steps.map(e=>e===rr?ar:e),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<nr&&n.push(t)}return{...o,not_applied:a.slice(0,e),not_applied_omitted:{count:t.length,item_ids:n}}};let d=0,c=a.length;for(;d<c;){const e=Math.ceil((d+c)/2);t(l(e))<=er?d=e:c=e-1}return l(d)}function ma(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??oa(a),i=t-r-1>0?` And ${t-r-1} more.`:"";if([...n,e].join(" ").length+i.length>tr)break;n.push(e),r+=1}r<t&&n.push(`And ${t-r} more.`);const a=n.join(" ");return a.length<=tr?a:a.slice(0,tr)}function _a(e){const t=t=>e.not_applied.some(t),n=[rr];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(sr),t(e=>"skipped_typing"===e.status||"skipped"===e.status&&"typing"===e.reason)&&n.push(or),t(e=>"locked"===e.status||"skipped"===e.status&&"locked"===e.reason)&&n.push(lr),t(e=>"conflict"===e.status&&("no_base"===e.reason||"bad_token"===e.reason))&&n.push(dr),n}function fa(e,t,n){const r=e.applied.length+e.captured.length;return{isError:0===r,result:pa({...t??{},status:r>0?"partial":"error",code:"not_all_applied",retryable:!1,message:ma(e),next_steps:_a(e),applied:e.applied,not_applied:e.not_applied,seq:e.seq,...e.merged_fields.length>0?{merged_fields:e.merged_fields}:{}},n)}}function ha(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 ga(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)}`}(ur,e.map(String).join("\n"))}function ya(){return crypto.randomUUID()}function wa(e){return[e.userId,e.projectId,"create_item",e.content,e.k,e.sessionId]}function va(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 ba(e){return va({userId:e.userId,projectId:e.projectId,family:ja(e.tool),key:e.key,itemIdOrK:e.itemId,path:["runs"],runHash:e.runHash,runK:e.k})}function ka(e){return[e.userId,e.projectId,e.what,e.name]}function ja(e){return"atoms_create_item"===e||"atoms_bulk_import"===e?"item":e}function Sa(e){const t=new Map;return e.map(e=>{const n=t.get(e)??0;return t.set(e,n+1),n})}function Aa(e){return"string"==typeof e?e.replace(/<\s*\/?\s*user_content\s*>/gi,""):Array.isArray(e)?e.map(Aa):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Aa(t)])):e}function $a(e){return Tr(Aa({type:e.type,title:e.title,body:e.body??null,summary:e.summary??null,req_type:e.req_type??null,domains:pr(e.domains),level:e.level??null,parent_ids:pr(e.parent_ids),fields:e.fields??{}}))}function xa(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 Ia(e){if(!e.item_id)return[];const t=[e.item_id];if(("add"===e.kind||"remove"===e.kind)&&2===e.path.length&&"relationships"===e.path[0]){const n=e.value,r="string"==typeof n?n:n&&"object"==typeof n?n.id:void 0;"string"==typeof r&&r!==e.item_id&&t.push(r)}return t}function qa(e){const t=new Set;for(const n of e)for(const e of Ia(n.op))t.add(e);return t}function Oa(e,t,n){const r=[];let a=[],i=new Set;for(const s of e.flatMap(e=>function(e,t){if(qa(e.ops).size<=t)return[e];const n=[];let r=[],a=new Set;for(const i of e.ops){const s=Ia(i.op),o=new Set([...a,...s]);r.length>0&&o.size>t?(n.push({key:e.key,ops:r}),r=[],a=new Set(s)):a=o,r.push(i)}return r.length>0&&n.push({key:e.key,ops:r}),n}(e,t))){const e=new Set([...i,...qa(s.ops)]);a.length>0&&(e.size>t||a.length+s.ops.length>n)?(r.push(a),a=[],i=qa(s.ops)):i=e,a.push(...s.ops)}return a.length>0&&r.push(a),r.map(e=>e.sort((e,t)=>e.index-t.index).map(e=>e.op))}function Ea(e){return e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message:e)}function za(e){return/too_many_items/.test(Ea(e))}function Ma(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 Ra(e,t){let n;try{n=await e.rpc("rollout_state",{p_project_id:t})}catch{return null}const{data:r,error:a}=n;if(a){if("42501"===a.code||xr(a.message??""))throw new Error(Nn);return null}return!!r&&"object"==typeof r&&!0===r.multiuser_saving}function Ta(){return{status:"error",message:fr,next_steps:["Send the same call again in a moment"],code:"rollout_state_unreadable",retryable:!0}}function Ca(e,t){const n=Ea(t);return"ops"===e&&Xt(n)?"main":"main"===e&&(en(n)||n.includes(Mn))?"ops":null}async function Da(e,t){try{return await t(e)}catch(n){const r=Ca(e,n);if(!r)throw n;return t(r)}}function Ha(e){const t=Ut(e);return"mcp_cursor"===t?"Cursor":"mcp_copilot"===t?"Copilot":"Claude"}function Na(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)}`}function Pa(e){return e.startsWith("op_id_reused: ")}function Fa(){return{status:"error",message:hr,next_steps:["Send the call again with a new idempotency_key, or without one"],code:"op_id_reused",retryable:!1}}async function Ua(e){return Cr("string"==typeof e?e:Tr(Aa(e)))}async function La(e){return e.content_hash=await Ua({kind:e.kind,value:e.value??null,order_key:e.order_key??null}),e}function Wa(e){const t=new Map;for(const n of e){const e="string"==typeof n?n:n?.op_id;if("string"!=typeof e||0===e.length)continue;const r="string"==typeof n||"string"!=typeof n.content_hash?void 0:n.content_hash;t.has(e)&&void 0===r||t.set(e,r)}return t}async function Va(e,t,n){const r=new Map,a=new Set,i=Wa(n),s=[...i.keys()];for(let n=0;n<s.length;n+=vr){const{data:o,error:l}=await e.rpc("mcp_op_answers",{p_project_id:t,p_op_ids:s.slice(n,n+vr)});if(l)throw Gr(l,"mcp_op_answers");for(const e of o?.answers??[]){if(!e||!e.op_id)continue;const{content_hash:t,...n}=e,s=i.get(e.op_id);"string"==typeof t&&"string"==typeof s&&t!==s?a.add(e.op_id):r.set(e.op_id,{...n,replayed:!0})}}return{found:r,reused:a}}async function Ba(e,t,n){const{found:r,reused:a}=await Va(e,t,n);if(a.size>0)throw new Error(br);return r}async function Ja(e,t,n,r=[]){const a=e=>"invalid"===e.status&&"op_id_reused"===e.reason,i=n.filter(a).map(e=>e.op_id);if(0===i.length)return n.map(e=>({...e}));const s=Wa(r),{found:o,reused:l}=await Va(e,t,i.map(e=>({op_id:e,content_hash:s.get(e)})));return n.map(e=>{if(!a(e))return{...e};if(l.has(e.op_id))return{...e,retryable:!1,message:hr};const t=o.get(e.op_id);return t?{...t,replayed:!0}:{...e,message:hr}})}function Ga(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 Qa,Ka,Ya,Za,Xa,ei,ti,ni,ri,ai=D({"src/core/agent-saving.ts"(){Qt(),an(),kr(),B(),Mn="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.",Rn="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: ",""),Tn="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.",Cn="This project is in the Trash. Nothing was saved. A project admin can restore it in ATOMS, then try again.",Dn="PROJECT_IN_TRASH",Hn="You no longer have access to this project. Ask an admin of its organization to add you back.",Nn="PROJECT_ACCESS_LOST",Pn="it is approved under change control, so it cannot be moved to Trash",Fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Un=2e3,Ln=20,Wn=[["title"],["summary"],["body"],["req_type"],["status"],["tags","domains"],["tags","level"]],Vn=[["title"],["body"],["analysis_props"],["relationships"]],Bn=new Set(["item","all","analysis","core","variable"]),Jn=/^([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,Gn=new Set(["title","type","approver_user_id","requires_impacted_approval"]),Qn=new Set(["variables","taxonomy","settings"]),Kn="The items were saved, but their base_token could not be read. Read each item with atoms_get_item before you update it.",Yn={'["title"]':"Title",'["summary"]':"Summary",'["body"]':"Body",'["req_type"]':"Type",'["type"]':"Type",'["status"]':"Status",'["tags","level"]':"Level",'["tags","domains"]':"Domains",'["asil_confirm_lower"]':"ASIL"},Zn=new Set(["applied","noop","replaced"]),Xn=4e3,er=65536,tr=600,nr=200,rr="Changes under applied are saved; do not send them again. Tell the person which changes were not saved and why.",ar="The applied_count changes are saved; do not send them again. Send only the not_applied changes again, and tell the person which changes were not saved and why.",ir=64,sr="For each conflict: merge theirs_value with your change, then call the tool again with that entry's base_token.",or="For a field someone is typing in: offer to try again in a minute.",lr="For a locked item: ask the person it is locked to, or an admin, to unlock it.",dr="For a change with no base: read the item with atoms_get_item, or use the entry's base_token, then send it again.",cr=["your_value","theirs_value","base_value"],ur="0b7e5c1a-3d2f-4e6b-9a8c-1f2e3d4c5b6a",pr=e=>[...new Set((e??[]).map(e=>String(Aa(e))))].sort(),mr=50,_r=500,fr="Could not read how this project saves, so nothing was saved. Try again.",gr="The change is saved. A read for this answer failed, so part of the answer is missing. Do not send the write again; read the item with atoms_get_item if you need it.",yr="Already created by an earlier identical call. Nothing new was created. To create another copy, call again with a new idempotency_key.",wr="Already recorded by an earlier identical call. Nothing new was stored. To record another run, call again with a new idempotency_key.",vr=500,br="op_id_reused: "+(hr="idempotency_key already used for a different change; use a new key.")}});function ii(e){const t=e??{},n=t.tags?.domains;return[t.title||"",t.body||"",t.summary||"",Array.isArray(n)?n.join(", "):"",t.tags?.level||"",t.type||""].filter(Boolean).join(" | ")}function si(e){return{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken.replace(/^Bearer\s+/i,"")}`,...e.anonKey?{apikey:e.anonKey}:{}}}async function oi(e,t,n){try{if(!e.supabaseUrl||!e.accessToken)return;const r=e.fetch??fetch,a=[...new Set(n)],i=a.slice(0,Xa);a.length>i.length&&console.error(`[embed-on-save] ${a.length-i.length} of ${a.length} items of project ${t} left to the backlog sweep (more than ${Xa} in one call)`);const s=[];for(let n=0;n<i.length;n+=Za){const a=i.slice(n,n+Za).map(e=>`"${e.replace(/["\\]/g,"\\$&")}"`).join(","),o=`${e.supabaseUrl}/rest/v1/items?select=id,data&project_id=eq.${encodeURIComponent(t)}&deleted_at=is.null&id=in.(${encodeURIComponent(a)})`,l=await r(o,{method:"GET",headers:si(e)});if(!l.ok){console.error(`[embed-on-save] item read failed (${l.status})`);continue}const d=await l.json();Array.isArray(d)&&s.push(...d)}await async function(e,t,n){try{if(!e.supabaseUrl||!e.accessToken)return;const r=e.fetch??fetch,a=n.filter(e=>"string"==typeof e.id&&""!==e.id).map(e=>({itemId:e.id,projectId:t,text:ii(e.data??{})})).filter(e=>e.text.trim().length>=3),i=[];for(let e=0;e<a.length;e+=Ka)i.push(a.slice(e,e+Ka));let s=0,o=0;const l=async()=>{for(;o<i.length;){const t=i[o++];try{const n=await r(`${e.supabaseUrl}/functions/v1/embed/batch`,{method:"POST",headers:si(e),body:JSON.stringify({items:t})});if(n.ok){const e=Number((await n.json().catch(()=>({}))).failed);Number.isFinite(e)&&e>0&&(s+=e)}else s+=t.length,console.error(`[embed-on-save] embed batch failed (${n.status}) for ${t.map(e=>e.itemId).join(", ")}`)}catch(e){s+=t.length,console.error("[embed-on-save] embed batch failed:",e instanceof Error?e.message:e)}}};await Promise.all(Array.from({length:Math.min(Ya,i.length)},l)),s>0&&console.error(`[embed-on-save] ${s} of ${a.length} items of project ${t} left without a fresh embedding; scripts/backfill-embeddings.ts fills them`)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}(e,t,s)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}function li(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){if(!n||"string"!=typeof n.item_id||""===n.item_id)continue;const e=Array.isArray(n.path)?n.path[0]:void 0;("create_item"===n.kind||"string"==typeof e&&Qa.includes(e))&&t.add(n.item_id)}return[...t]}function di(e,t,n){return`${e.supabaseUrl}/rest/v1/project_changes?project_id=eq.${encodeURIComponent(t)}&bulk_id=eq.${encodeURIComponent(n)}`}function ci(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e[ni];return t&&"object"==typeof t?t:null}function ui(e){const t=globalThis.EdgeRuntime;try{t?.waitUntil?.(e)}catch{}}function pi(e,t=fetch){const n={...e,fetch:t};return async(e,r)=>{const a=await t(e,r);try{const t=a.ok?function(e,t){if("POST"!==(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase())return null;const n="string"==typeof e?e:e instanceof URL?e.href:e instanceof Request?e.url:"",r=/\/rest\/v1\/rpc\/([A-Za-z0-9_]+)(?:\?|$)/.exec(n);return r&&ri.has(r[1])?r[1]:null}(e,r):null;if(t&&"string"==typeof r?.body){const e=JSON.parse(r.body),a=e.p_project_id;if("string"==typeof a){const r="apply_item_ops"===t?li(e.p_ops):"save_item_with_revision"===t?"string"==typeof e.p_item_id?[e.p_item_id]:[]:(Array.isArray(e.p_items)?e.p_items.map(e=>e?.id):[]).filter(e=>"string"==typeof e&&""!==e);ui(oi(n,a,r))}}}catch(e){console.error("[embed-on-save] not queued:",e instanceof Error?e.message:e)}return a}}var mi,_i,fi,hi=D({"src/core/embed-on-save.ts"(){Qa=["title","body","summary","tags","type"],Ka=5,Ya=3,Za=100,Xa=500,ei=1e3,ti=5e3,ni=Symbol.for("atoms.embedOnSave.config"),ri=new Set(["save_item_with_revision","bulk_save_items_with_revisions","apply_item_ops"])}});function gi(e=(e,t)=>fetch(e,t)){return async(t,n)=>{const r="string"==typeof t?t:t instanceof URL?t.href:null,a=null==n?.body||"string"==typeof n.body,i=null!==r&&a&&function(e,t){let n;try{n=new URL(e).pathname}catch{return!1}if(!n.startsWith("/rest/v1/"))return!1;if("GET"===t||"HEAD"===t)return!0;const r=/^\/rest\/v1\/rpc\/([^/]+)$/.exec(n);return"POST"===t&&null!==r&&mi.has(r[1])&&!_i.has(r[1])}(r,(n?.method??"GET").toUpperCase());let s;try{s=await e(t,n)}catch(r){if(!i||!function(e){for(let t=e,n=0;null!=t&&n<4;t=t.cause,n++){if("object"!=typeof t)return"string"==typeof t&&fi.test(t);const{name:e,code:n,message:r}=t;if("AbortError"===e||"TimeoutError"===e)return!1;if(fi.test(`${String(n??"")} ${String(r??"")}`))return!0}return!1}(r))throw r;return e(t,n)}return 502===s.status&&i?(await(s.body?.cancel().catch(()=>{})),e(t,n)):s}}var yi,wi,vi,bi,ki,ji,Si=D({"src/core/gateway-retry-reads.ts"(){mi=new Set(["baseline_item_state","baseline_state","baseline_state_page","baseline_variables_state","cc_normative_changed","cc_project_is_controlled","changes_since","fresh_typing_notes","is_active_project_member_for_field","is_platform_admin","item_state_at","item_trash_info","mcp_count_items","mcp_count_recent_changes","mcp_field_value_counts","mcp_op_answers","mcp_resolve_policy","mcp_variable_reference_counts","model_design_get","model_designs_list","mue_value_at","needs_attention_test_states","next_item_id","order_key_valid","order_keys_initial","project_function_mode","project_item_domain_tags","project_state_at","release_report_stored","restore_baseline_preview_counts","rollout_state","tag_key","tcm_requirements_for_test_cases","tcm_rerun_list","variables_at","verification_accepted_failures","verification_document_closures","verification_notrun_points","verification_readiness"]),_i=new Set(["mcp_resolve_policy"]),fi=/ECONNRESET|UND_ERR_SOCKET|connection reset|connection closed before message completed|other side closed|socket hang up|invalid response (?:was received )?from the upstream|invalid response from upstream/i}});function Ai(e){const t=yi[e];return[...t.top,...t.other]}async function $i(e,t,n){const r=function(e){const t=Ai(e);return bi.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))}function xi(e){return function(e){return"automotive"===(e.industry??"automotive")&&!e.holdsAnalysisOutsideAutomotive}(e)?e.hazardGoalItemsOn&&e.multiuserSavingOn?null:ji:ki}var Ii,qi,Oi,Ei,zi,Mi,Ri,Ti,Ci,Di,Hi,Ni,Pi,Fi,Ui,Li,Wi,Vi,Bi,Ji,Gi,Qi,Ki,Yi=D({"src/core/analysis-industry.ts"(){yi={automotive:{top:["iso26262","design"],other:[]},medical:{top:["iso14971","tir57","process"],other:["software","use"]},general:{top:[],other:[]}},wi={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"},vi={automotive:"Automotive (ISO 26262)",medical:"Medical device (ISO 14971)",general:"Standard"},bi=Object.keys(wi),ki="Hazard and Safety goal items are for ISO 26262 (automotive) projects. In a medical device project hazards are rows of the ISO 14971 risk analysis.",ji="rollout_switched:hazard_goal_items"}});function Zi(e){let t=0,n=e.length;for(;t<n&&Ti.includes(e[t]);)t++;for(;n>t&&Ti.includes(e[n-1]);)n--;return e.slice(t,n)}function Xi(e){const t=zi(Zi(e??""));return t<1||t>qi.maxName?"a model design needs a name of 1 to 200 characters":null}function es(e){return zi(e??"")>qi.maxDescription?"a description holds at most 5000 characters":null}function ts(e){const t=new Set;for(const n of e.boxes)for(const e of n.links??[])t.add(e);for(const n of e.arrows)for(const e of n.links??[])t.add(e);return[...t]}function ns(e,t=""){let n="";for(const r of e??""){const e=Di.find(([e])=>e===r);e?n+=e[1]:t.includes(r)?n+=`#${r.codePointAt(0)};`:n+=r}return n}function rs(e){return e.replace(/#(quot|lt|gt|amp|\d{1,7});/g,(e,t)=>{if(t in Hi)return Hi[t];const n=Number(t);if(n<=0||n>1114111||n>=55296&&n<=57343)throw new Ni(`#${t}; names no character that can be stored`);return String.fromCodePoint(n)})}function as(e){const t=e.replace(/[^A-Za-z0-9_]/g,"_"),n=/^[A-Za-z_]/.test(t)?t:`n_${t}`;return(Pi.has(n.toLowerCase())?`n_${n}`:n).slice(0,qi.maxIdLength)}function is(e){const t=new Map,n=new Set,r=e=>{if(t.has(e))return;const r=as(e);let a=r;for(let e=1;n.has(a);e++){const t=`_${e}`;a=r.slice(0,qi.maxIdLength-t.length)+t}n.add(a),t.set(e,a)};for(const t of e.groups)r(t.id);for(const t of e.boxes)r(t.id);return t}function ss(e,t){const n=e.x+e.w/2,r=e.y+e.h/2;return n>=t.x&&n<=t.x+t.w&&r>=t.y&&r<=t.y+t.h}function os(e){const t=new Map;for(const n of e.boxes){let r=null;for(const t of e.groups)ss(n,t)&&(!r||t.w*t.h<r.w*r.h)&&(r=t);r&&t.set(n.id,r.id)}return t}function ls(e,t,n){const r=(t??[]).filter(e=>"string"==typeof e&&Oi.test(e));return 0===r.length?null:`%% links ${e}: ${r.map(e=>{const t=n?n(e):void 0;return void 0===t?e:null===t?`${e} (not in this project)`:`${e} "${ns(t,",")}"`}).join(", ")}`}function ds(e,t={},n){const r=[];r.push("%% ATOMS model design"+(t.displayId?` ${t.displayId}`:"")),null!=t.name&&r.push(`%% name: ${ns(t.name)}`),t.description&&r.push(`%% description: ${ns(t.description)}`),r.push("flowchart LR");const a=is(e),i=e=>a.get(e)??as(e),s=os(e),o=(e,t)=>{r.push(`${t}${i(e.id)}["${ns(e.label??"")}"]`);const a=ls(i(e.id),e.links??[],n);a&&r.push(`${t}${a}`)};for(const t of e.groups){r.push(` subgraph ${i(t.id)}["${ns(t.label??"")}"]`);for(const n of e.boxes)s.get(n.id)===t.id&&o(n," ");r.push(" end")}for(const t of e.boxes)s.has(t.id)||o(t," ");return e.arrows.forEach((e,t)=>{const a=e.label?`|"${ns(e.label)}"|`:"";r.push(` ${i(e.from)} ${function(e){return e.bi?e.dashed?"<-.->":"<--\x3e":e.dashed?"-.->":"--\x3e"}(e)}${a} ${i(e.to)}`);const s=ls(`edge ${t+1}`,e.links??[],n);s&&r.push(` ${s}`)}),r.join("\n")+"\n"}var cs,us,ps,ms,_s,fs,hs=D({"src/core/model-design.ts"(){Ii=Object.freeze({boxes:[],arrows:[],groups:[]}),qi=Object.freeze({maxElements:1e3,maxLabel:200,maxTechDetail:1e3,maxLinksPerElement:20,maxIdLength:64,maxName:200,maxDescription:5e3,maxCanvasBytes:2097152}),Oi=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Ei=Object.freeze({maxChars:4194304,maxElements:1e3}),zi=e=>{let t=0;for(const n of e)t++;return t},Mi=Object.freeze({boxWidth:160,boxHeight:60,gapX:80,gapY:40,originX:40,originY:40,belowExistingGap:80,groupPadding:20,groupLabelSpace:40}),Ri=/^MD-\d{3,}$/i,Ti=" \t\r\n\f\v",Ci=e=>"number"==typeof e&&Number.isFinite(e),Di=[["#","#35;"],['"',"#quot;"],["<","#lt;"],[">","#gt;"],["&","#amp;"],["|","#124;"],["`","#96;"],["\n","#10;"],["\r","#13;"],["\t","#9;"],["[","#91;"],["]","#93;"]],Hi={quot:'"',lt:"<",gt:">",amp:"&"},Ni=class extends Error{},Pi=new Set(["end","subgraph","graph","flowchart","direction","style","classdef","class","click","linkstyle"]),Fi="[A-Za-z_][A-Za-z0-9_]{0,63}",Ui='"([^"]*)"',Li=new RegExp(`^(${Fi})(?:\\[${Ui}\\])?$`),Wi=new RegExp(`^subgraph\\s+(${Fi})(?:\\[${Ui}\\])?$`),Vi=new RegExp(`^(${Fi})(?:\\[${Ui}\\])?\\s*(<-\\.->|<--\x3e|-\\.->|--\x3e)(?:\\|(?:${Ui}|([^|"]*))\\|)?\\s*(${Fi})(?:\\[${Ui}\\])?$`),Bi=new RegExp(`^%%\\s*links\\s+(edge\\s+(\\d{1,4})|${Fi})\\s*:\\s*(.*)$`),Ji=/^([A-Za-z][A-Za-z0-9._-]{0,63})(?:\s+(?:"[^"]*"|\([^)]*\)))?$/,Gi=e=>zi(e)>qi.maxLabel,Qi=e=>20*Math.ceil(e/20),Ki="Add me as editor"}});function gs(){return{status:"error",code:"rollout_switched",key:"model_designs",retryable:!1,message:us,next_steps:["Ask an org admin to turn on Model design for this project if it should have model designs","Do not retry this call"]}}function ys(e){const t=String(e?.message??e??""),n=String(e?.details??""),r=e=>t.slice(t.indexOf(e)+e.length).trim();if(t.includes("rollout_switched:model_designs"))return gs();if(t.includes("model_design_stale:")){let e={};try{e=JSON.parse(n)}catch{e={}}return{status:"error",code:"stale_version",retryable:!0,message:`Not saved: ${r("model_design_stale:")}.`,..."number"==typeof e.version?{current_version:e.version}:{},next_steps:["Read the design again with atoms_get_model_design","Apply your change to that version's Mermaid, then call atoms_update_model_design with its version as expected_version"]}}if(t.includes("model_design_not_editor:")){const e=/add yourself as an editor/i.test(t),n=/Ask (.+?) for edit access\.?\s*$/.exec(t)?.[1]?.trim(),i="Only the design's creator and the editors named on it can change it";return{status:"error",code:"not_an_editor",retryable:!1,message:`Not saved: ${r("model_design_not_editor:")}`,next_steps:e?[`Open the design in the ATOMS app and press ${Ki} in its Details panel, then call again`,`${i}; as an org admin you can add yourself`,"There is no tool that names editors"]:[...n?[(a=n,`Ask ${a} for edit access.`)]:[],`${i}${n?"; editors are named in the ATOMS app (the design's Details panel), and there is no tool for it":""}`,...n?[]:["Editors are named in the ATOMS app (the design's Details panel) by its creator or an org admin; there is no tool for it"],"Do not retry this call"]}}var a;if(t.includes("model_design_viewer:"))return{status:"error",code:"viewer_read_only",retryable:!1,message:"Not saved: an org viewer can view model designs but not change them.",next_steps:["Ask an org admin to make you an editor of the organization","Do not retry this call"]};if(t.includes("model_design_in_trash:"))return{status:"error",code:"model_design_in_trash",retryable:!1,message:`Not saved: ${r("model_design_in_trash:")}.`,next_steps:["Ask its creator or an org admin to restore it from the project Trash in the app","Do not retry this call"]};if(t.includes("model_design_not_found:"))return{status:"error",code:"not_found",retryable:!1,message:r("model_design_not_found:"),next_steps:["Use atoms_list_model_designs to see this project's model designs and their MD ids"]};const i=/model_design_(name|description|canvas|version|source|agent_client):\s*(.*)$/.exec(t);return i?{status:"error",code:"validation_error",retryable:!1,message:`Validation error: ${i[2]}`,next_steps:["Fix the named value and call again"]}:null}async function ws(e,t){const{data:n,error:r}=await e.from("projects").select("id, deleted_at").eq("id",t).maybeSingle();if(r)throw r;return!!n?.deleted_at}async function vs(e,t,n){return function(e){if(e.error)throw e.error;return e.data}(await e.rpc(t,n))}async function bs(e,t,n){const r=new Map;for(let a=0;a<n.length;a+=ps){const i=n.slice(a,a+ps),{data:s,error:o}=await e.from("items").select("id, title, type").eq("project_id",t).is("deleted_at",null).in("id",i);if(o)throw o;for(const e of s??[])r.set(e.id,e)}return r}async function ks(e,t,n){const r=await vs(e,"model_design_get",{p_project_id:t,p_design:n});return!0!==r?.enabled?null:r.design??null}async function js(e,t,n,r){const a=function(e){const t=Ei;if("string"!=typeof e)return{ok:!1,error:"mermaid must be text"};if((e=function(e){const t=e.length-e.trimStart().length,n=e.trim();return n.startsWith("<user_content>")&&n.endsWith("</user_content>")?" ".repeat(t)+n.slice(14,n.length-15):e}(e)).length>t.maxChars)return{ok:!1,error:`the Mermaid text holds ${e.length} characters; at most ${t.maxChars} are accepted`};const n={direction:"LR",name:null,description:null,nodes:[],edges:[],groups:[]},r=new Map,a=new Set,i=new Map,s=new Map;let o=!1,l=null;const d=(e,t)=>({ok:!1,error:`line ${e}: ${t}`}),c=(e,i,s)=>{if(a.has(e))return`${e} names a subgraph, not a box`;if(Pi.has(e.toLowerCase()))return`${e} is a Mermaid keyword and cannot name a box`;const o=void 0===i?void 0:rs(i);if(void 0!==o&&Gi(o))return`the label of ${e} holds more than 200 characters`;const l=r.get(e);if(l){if(void 0!==o){if(l.labelSet&&l.label!==o)return`${e} is declared twice with different labels`;l.label=o,l.labelSet=!0}if(s){if(l.group&&l.group!==s)return`${e} is in two subgraphs`;l.group=s}return null}if(r.size+n.edges.length+n.groups.length>=t.maxElements)return`more than ${t.maxElements} boxes, arrows and subgraphs`;const d={id:e,label:o??e,group:s,links:[],labelSet:void 0!==o};return r.set(e,d),null},u=e.split(/\r?\n/);for(let e=0;e<u.length;e++){const t=p(e+1,u[e].trim());if(t)return t}return function(){if(!o)return{ok:!1,error:'the diagram must start with "flowchart LR" (or TD, TB, RL, BT)'};if(l)return{ok:!1,error:`the subgraph ${l} has no "end"`};for(const[e,t]of i){const n=r.get(e);if(!n)return{ok:!1,error:`%% links names ${e}, which is no box of this diagram`};n.links=t}for(const[e,t]of s){const r=n.edges[e-1];if(!r)return{ok:!1,error:`%% links names edge ${e}, but the diagram has ${n.edges.length} arrows`};r.links=t}return n.nodes=[...r.values()].map(e=>({id:e.id,label:e.label,group:e.group,links:e.links})),{ok:!0,value:n}}();function p(e,u){try{return function(e,u){if(""===u)return null;if(u.startsWith("%%")){const t=/^%%\s*name:\s?(.*)$/.exec(u);if(t)return n.name=rs(t[1]),null;const r=/^%%\s*description:\s?(.*)$/.exec(u);if(r)return n.description=rs(r[1]),null;const a=Bi.exec(u);if(a){const t=""===a[3].trim()?[]:a[3].split(",").map(e=>e.trim()),n=[];for(const r of t){const t=Ji.exec(r);if(!t)return d(e,`"${r.slice(0,80)}" is not a linked item; write the item id, optionally followed by its title in quotes`);n.includes(t[1])||n.push(t[1])}if(n.length>qi.maxLinksPerElement)return d(e,"a box or arrow links at most 20 items");if(a[2]){const t=Number(a[2]);if(s.has(t))return d(e,`edge ${t} has a links line already; put all its linked items on one line`);s.set(t,n)}else{if(i.has(a[1]))return d(e,`${a[1]} has a links line already; put all its linked items on one line`);i.set(a[1],n)}return null}return null}if(!o){const t=/^(flowchart|graph)\s+(LR|RL|TB|TD|BT)\s*;?$/.exec(u);return t?(n.direction=t[2],o=!0,null):d(e,'the diagram must start with "flowchart LR" (or TD, TB, RL, BT)')}const p=u.replace(/;$/,"").trim(),m=Wi.exec(p);if(m){if(l)return d(e,"subgraphs inside subgraphs are not supported");const i=m[1];if(a.has(i)||r.has(i))return d(e,`${i} is used twice`);if(r.size+n.edges.length+n.groups.length>=t.maxElements)return d(e,`more than ${t.maxElements} boxes, arrows and subgraphs`);const s=void 0===m[2]?i:rs(m[2]);return Gi(s)?d(e,`the label of ${i} holds more than 200 characters`):(a.add(i),n.groups.push({id:i,label:s}),l=i,null)}if("end"===p)return l?(l=null,null):d(e,'"end" without a subgraph');const _=Vi.exec(p);if(_){if(l)return d(e,'write arrows after the subgraph\'s "end", not inside it');const[,a,i,s,o,u,p,m]=_,f=c(a,i,null);if(f)return d(e,f);const h=c(p,m,null);if(h)return d(e,h);if(r.size+n.edges.length+n.groups.length>=t.maxElements)return d(e,`more than ${t.maxElements} boxes, arrows and subgraphs`);const g=rs((o??u??"").trim());return Gi(g)?d(e,"an arrow label holds more than 200 characters"):a===p?d(e,`the arrow from ${a} to itself is not supported`):(n.edges.push({from:a,to:p,label:g,dashed:s.includes("."),bi:s.startsWith("<"),links:[]}),null)}const f=Li.exec(p);if(f){const t=c(f[1],f[2],l);return t?d(e,t):null}return d(e,`"${p.slice(0,80)}" is not a model design line; write boxes as id["label"], arrows with --\x3e, -.->, <--\x3e or <-.-> (an optional |"label"| after the arrow), groups as subgraph id["label"] ... end, and links as %% links id: REQ-001`)}(e,u)}catch(t){if(t instanceof Ni)return d(e,t.message);throw t}}}(n);if(!a.ok)return{ok:!1,error:cs("mermaid_not_accepted",`Validation error: the Mermaid was not accepted: ${a.error}`,['Write a flowchart as atoms_get_model_design returns it: flowchart LR, boxes as id["label"], arrows --\x3e, -.->, <--\x3e or <-.-> with an optional |"label"|, subgraph id["label"] ... end, and %% links id: REQ-001',"Fix the named line and call again"])};const i=function(e,t=Ii){const n=Mi,r="TB"===e.direction||"TD"===e.direction||"BT"===e.direction,a=is(t),i=new Map;for(const e of t.boxes)i.set(a.get(e.id),e);const s=new Map;for(const e of t.groups)s.set(a.get(e.id),e);const o=e.nodes.filter(e=>i.has(e.id)),l=e.nodes.filter(e=>!i.has(e.id)),d=new Set([...t.boxes.map(e=>e.id),...t.groups.map(e=>e.id),...t.arrows.map(e=>e.id)]),c=e=>{const t=e.slice(0,qi.maxIdLength);let n=t;for(let e=1;d.has(n);e++){const r=`_${e}`;n=t.slice(0,qi.maxIdLength-r.length)+r}return d.add(n),n},u=new Map,p=new Map;for(const t of e.edges)p.set(t.to,[...p.get(t.to)??[],t.from]);const m=(e,t)=>{if(u.has(e))return u.get(e);if(t.has(e))return 0;t.add(e);const n=(p.get(e)??[]).filter(t=>t!==e),r=0===n.length?0:Math.max(...n.map(e=>m(e,t)+1));return t.delete(e),u.set(e,r),r};for(const t of e.nodes)m(t.id,new Set);const _=new Map;for(const e of o){const t=i.get(e.id);_.set(e.id,{...t,label:e.label,links:[...e.links]})}const f=t=>e.nodes.filter(e=>e.group===t).map(e=>e.id),h=e=>s.get(e),g=[...o.map(e=>{const t=i.get(e.id);return t.y+t.h}),...e.groups.map(e=>h(e.id)).filter(e=>!!e).map(e=>e.y+e.h)],y=[...o.map(e=>{const t=i.get(e.id);return t.x+t.w}),...e.groups.map(e=>h(e.id)).filter(e=>!!e).map(e=>e.x+e.w)],w=n.originX,v=n.originY;let b=r?0===y.length?w:Qi(Math.max(...y)+n.belowExistingGap):0===g.length?v:Qi(Math.max(...g)+n.belowExistingGap);const k=()=>r?{x:b,y:v}:{x:w,y:b},j=e=>{b=Qi((r?e.x+e.w:e.y+e.h)+n.gapY)},S=(e,t)=>{const r=e.map(e=>_.get(e)),a=Math.min(...r.map(e=>e.x))-(t?n.groupPadding:0),i=Math.min(...r.map(e=>e.y))-(t?n.groupLabelSpace:0);return{x:a,y:i,w:Math.max(...r.map(e=>e.x+e.w))+(t?n.groupPadding:0)-a,h:Math.max(...r.map(e=>e.y+e.h))+(t?n.groupPadding:0)-i}},A=e=>({x:e.x,y:e.y,w:n.boxWidth+2*n.groupPadding,h:n.boxHeight+n.groupLabelSpace+n.groupPadding}),$=(t,a,i)=>{const s=new Map,o=i?n.groupPadding:0,l=i?n.groupLabelSpace:0;for(const i of t){const t=e.nodes.find(e=>e.id===i),d=u.get(i)??0,p=s.get(d)??0;s.set(d,p+1);const m=d*((r?n.boxHeight:n.boxWidth)+(r?n.gapY:n.gapX)),f=p*((r?n.boxWidth:n.boxHeight)+(r?n.gapX:n.gapY));_.set(i,{id:c(i),x:a.x+o+(r?f:m),y:a.y+l+(r?m:f),w:n.boxWidth,h:n.boxHeight,label:t.label,links:[...t.links]})}},x=new Set(o.map(e=>e.id));let I=e.groups.filter(e=>h(e.id)&&f(e.id).every(e=>x.has(e)));for(let e=!0;e;){e=!1;const t=I.map(e=>({...h(e.id),id:e.id})),n=os({boxes:o.map(e=>({..._.get(e.id),id:e.id})),groups:t}),r=I.filter(e=>{const t=o.filter(t=>n.get(t.id)===e.id).map(e=>e.id).sort(),r=f(e.id).sort();return t.length===r.length&&t.every((e,t)=>e===r[t])});r.length!==I.length&&(I=r,e=!0)}const q=new Set(I.map(e=>e.id)),O=new Map;for(const e of I){const t=h(e.id);O.set(e.id,{x:t.x,y:t.y,w:t.w,h:t.h})}for(const t of e.groups){if(q.has(t.id))continue;const e=f(t.id).filter(e=>!x.has(e)),n=f(t.id);if(0===n.length){const e=h(t.id);if(e){O.set(t.id,{x:e.x,y:e.y,w:e.w,h:e.h});continue}const n=A(k());O.set(t.id,n),j(n);continue}e.length>0&&($(e,k(),!0),e.length,n.length,j(S(e,!0))),O.set(t.id,S(n,!0))}const E=l.filter(e=>null===e.group).map(e=>e.id);E.length>0&&($(E,k(),!1),j(S(E,!1)));const z=()=>e.nodes.map(e=>({..._.get(e.id),id:e.id}));for(let t=0;t<=e.groups.length;t++){const t=e.groups.map(e=>({id:e.id,label:e.label,...O.get(e.id)})),n=os({boxes:z(),groups:t}),r=e.groups.find(t=>{const r=e.nodes.filter(e=>n.get(e.id)===t.id).map(e=>e.id).sort(),a=f(t.id).sort();return!(r.length===a.length&&r.every((e,t)=>e===a[t]))});if(!r)break;const a=e.groups.find(t=>t.id!==r.id&&e.nodes.some(e=>e.group===r.id&&n.get(e.id)===t.id))??r,i=f(a.id),s=k();if(0===i.length){const e=A(s);O.set(a.id,e),j(e);continue}const o=S(i,!0),l=s.x-o.x,d=s.y-o.y;for(const e of i){const t=_.get(e);_.set(e,{...t,x:t.x+l,y:t.y+d})}const c=S(i,!0);O.set(a.id,c),j(c)}const M=new Map(t.boxes.map((e,t)=>[e.id,t])),R=e.nodes.map(e=>_.get(e.id)).map((e,n)=>({b:e,k:M.get(e.id)??t.boxes.length+n})).sort((e,t)=>e.k-t.k).map(e=>e.b),T=new Map;for(const e of t.arrows){const t=`${e.from}\0${e.to}`;T.set(t,[...T.get(t)??[],e])}return{boxes:R,arrows:e.edges.map(e=>{const t=_.get(e.from).id,n=_.get(e.to).id,a=`${t}\0${n}`,i=T.get(a)?.shift();return i?{...i,label:e.label,dashed:e.dashed,bi:e.bi,links:[...e.links]}:{id:c(`arrow_${t}_${n}`),from:t,to:n,fromPort:r?"bottom":"right",toPort:r?"top":"left",label:e.label,techDetail:"",dashed:e.dashed,bi:e.bi,ortho:!1,curve:!1,bendOffset:0,links:[...e.links]}}),groups:e.groups.map(e=>{const t=h(e.id),n=O.get(e.id);return t&&q.has(e.id)?{...t,label:e.label}:{id:t?t.id:c(e.id),x:n.x,y:n.y,w:n.w,h:n.h,label:e.label}})}}(a.value,r),s=function(e){const t=e;if(!t||"object"!=typeof t||Array.isArray(t))return"the canvas must be an object with boxes, arrows and groups";if(!Array.isArray(t.boxes)||!Array.isArray(t.arrows)||!Array.isArray(t.groups))return"the canvas must hold the arrays boxes, arrows and groups";if(t.boxes.length+t.arrows.length+t.groups.length>qi.maxElements)return"a model design holds at most 1000 boxes, arrows and groups";if(function(e){const t=e=>(new TextEncoder).encode(e).length,n=e=>{if(null===e||"object"!=typeof e)return t(JSON.stringify(e)??"null");if(Array.isArray(e))return 2+e.reduce((e,t)=>e+n(t),0)+2*Math.max(0,e.length-1);const r=Object.entries(e).filter(([,e])=>void 0!==e);return 2+r.reduce((e,[r,a])=>e+t(JSON.stringify(r))+2+n(a),0)+2*Math.max(0,r.length-1)};return n(e)}(t)>qi.maxCanvasBytes)return"a model design canvas holds at most 2 MB of JSON";const n=new Set,r=new Set;for(const e of["boxes","groups","arrows"])for(const a of t[e]){const t=a;if(!t||"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.id||t.id.length<1||t.id.length>qi.maxIdLength)return"every box, arrow and group needs an id of 1 to 64 characters";if(n.has(t.id))return`the id ${t.id} is used twice`;if(n.add(t.id),"label"in t&&"string"!=typeof t.label)return"a label must be text";if(zi(String(t.label??""))>qi.maxLabel)return"a label holds at most 200 characters";if("arrows"!==e&&!(Ci(t.x)&&Ci(t.y)&&Ci(t.w)&&Ci(t.h)))return"every box and group needs the numbers x, y, w and h";if("boxes"===e&&r.add(t.id),"arrows"===e){if("string"!=typeof t.from||"string"!=typeof t.to||!r.has(t.from)||!r.has(t.to))return`the arrow ${t.id} must join two boxes of this design`;if("techDetail"in t&&"string"!=typeof t.techDetail)return"a technical detail must be text";if(zi(String(t.techDetail??""))>qi.maxTechDetail)return"a technical detail holds at most 1000 characters"}if("links"in t){if(!Array.isArray(t.links))return"links must be a list of item ids";if(t.links.length>qi.maxLinksPerElement)return"a box or arrow links at most 20 items";for(const e of t.links)if("string"!=typeof e||!Oi.test(e))return"a linked item id is an item id such as REQ-001"}}return null}(i);if(s)return{ok:!1,error:cs("validation_error",`Validation error: ${s}`,["Make the diagram smaller and call again"])};const o=function(e,t=Ii){const n=new Set(ts(t));return ts(e).filter(e=>!n.has(e))}(i,r);if(o.length>0){const n=await bs(e,t,o),r=o.filter(e=>!n.has(e));if(r.length>0)return{ok:!1,error:cs("unknown_item_ids",`Validation error: these linked ids are no live item of this project: ${r.join(", ")}`,["Use atoms_search or atoms_list_items to find the item ids","Remove or correct the %% links entries and call again"],!1,{unknown_item_ids:r})}}return{ok:!0,canvas:i,parsed:a.value}}function Ss(e,t){const n=new Set(t.boxes.map(e=>e.id)),r=new Set(t.arrows.map(e=>e.id));return{removed_boxes:e.boxes.filter(e=>!n.has(e.id)).length,removed_arrows:e.arrows.filter(e=>!r.has(e.id)).length}}function As(e){return K(`mcp_policy_block_destructive: ${e} is blocked by your org's MCP Access Policy (Block destructive ops)`)}function $s(e,t){return void 0!==t.name&&null!==e.name&&Zi(e.name)!==Zi(t.name)?cs("validation_error","Validation error: the %% name: line of the Mermaid differs from the name param",["Send one name: change the %% name: line or the name param so they agree, or drop the line"]):void 0!==t.description&&null!==e.description&&e.description!==t.description?cs("validation_error","Validation error: the %% description: line of the Mermaid differs from the description param",["Send one description: change the %% description: line or the description param so they agree, or drop the line"]):null}var xs,Is,qs,Os,Es,zs=D({"src/core/model-design-tools.ts"(){hs(),ai(),re(),cs=(e,t,n,r=!1,a={})=>({ok:!1,error:{status:"error",code:e,retryable:r,message:t,next_steps:n,...a}}),us="Model design is not switched on for this project, so its model designs cannot be read or written here.",ps=100,ms=e=>({display_id:e.display_id,name:e.name,description:e.description,version:e.version,creator_name:e.created_by_name,updated_by_name:e.updated_by_name,updated_at:e.updated_at,editor_count:e.editor_count,you_can_edit:e.can_edit}),fs={atoms_list_model_designs:"List the model designs (user-drawn architecture diagrams, MD-001 and on) of a project: each design's display_id, name, description, version, creator_name, updated_at, editor_count and whether you can edit it. Use atoms_get_model_design for one design's diagram.",atoms_get_model_design:"Read one model design by its MD id: its name, description, version, creator, and its diagram as Mermaid (model_mermaid), plus for each box and arrow that links ATOMS items the linked items with id and title. Box names and arrow labels are the user's own words; there are no built-in box types. "+(_s='The Mermaid is a flowchart: a first line "flowchart LR" (or TD; the direction places new boxes and is not stored), boxes as id["label"], arrows as a --\x3e b (solid), a -.-> b (dashed), a <--\x3e b or a <-.-> b (both ways), each with an optional |"label"| after the arrow, groups as subgraph id["label"] ... end (not nested, arrows after the end), and per box or arrow one line %% links <box id>: REQ-001, TC-002 or %% links edge <n>: ... (n counts the arrows from 1) naming linked ATOMS items. The %% name: and %% description: lines set the name and description when you send no name or description param. Label text uses Mermaid codes: #quot; for ", #lt; #gt; #amp; #35; #124; #91; #93; #10; for a new line. Send the Mermaid as you read it, with or without its <user_content> markers. Anything else is refused with the line number. At most 1000 boxes, arrows and subgraphs together.'),atoms_create_model_design:`Create a model design in a project: a name (1 to 200 characters), an optional description (at most 5000 characters) and an optional Mermaid flowchart. You become its creator and its first editor. Every linked item id must be a live item of the project. ${_s}`,atoms_update_model_design:`Change a model design you may edit (its creator, or an editor its creator or an org admin named; an org admin who is not named adds themselves in the ATOMS app first): any of name, description and mermaid, with expected_version set to the version you read. A box whose id matches one already there keeps its place; new boxes are placed automatically; boxes and arrows you leave out are removed, and the design's history (atoms_get_history with the MD id) records what changed but keeps no copy to restore them from, so the answer counts them (removed_boxes, removed_arrows); removing a box, arrow, group or linked item is refused under an org's Block destructive ops. If someone saved after your read the call is refused, naming who and when: read again and redo your change. Editors are named only in the ATOMS app. ${_s}`}}});function Ms(e){const t=xs.exec(e);return t?t[1]:null}function Rs(e){return e.includes("function_is_item")}function Ts(){return{status:"error",code:"function_is_item",retryable:!1,message:Os,next_steps:['Create a Function with atoms_create_item and type "function", or edit the Function item itself',"Do not retry this call"]}}function Cs(){return{status:"error",code:"rollout_switched",key:"hazard_goal_items",retryable:!1,message:Es,next_steps:["This project keeps its hazards and safety goals as text on its HARA rows for now (atoms_fill_row hazard and safety_goal)","Ask an org admin to turn on Hazard and Safety goal items for this project if it should have them","Do not retry this call"]}}function Ds(e){return e.includes("hazard_goal_not_automotive")}function Hs(){return{status:"error",code:"hazard_goal_not_automotive",retryable:!1,message:`Validation error: ${ki} This change was not saved.`,next_steps:["In a medical device project, record the hazard as a row of the project's ISO 14971 risk analysis (atoms_create_analysis subtype risk_analysis, then atoms_propose_rows or atoms_fill_row)","A Standard project keeps no hazards or safety goals; Hazard and Safety goal items need the industry Automotive (ISO 26262), set on the project settings page","Do not retry this call"]}}function Ns(e){return e.includes("hazard_goal_restore_refused")}var Ps,Fs,Us,Ls,Ws,Vs,Bs,Js=D({"src/core/rollout-errors.ts"(){Yi(),zs(),xs=/rollout_switched:([a-z][a-z0-9_]{2,62})/,Is="This project's saving rules just changed. Read the item again, then retry your change.",qs="Function items are not on for this project yet, so a Function item cannot be created here. This change was not saved.",Os="Validation error: this project's Functions are items now, so its function tag list no longer changes. This change was not saved.",Es="Hazard and Safety goal items are not on for this project, so a Hazard, a Safety goal, or the Hazard or Safety goal of a hazardous event cannot be written here. This change was not saved."}});function Gs(e,t){const n=Us.indexOf(String(e??"")),r=Us.indexOf(String(t??""));return n<0||r<0?Ps:Ls[n][r]}function Qs(e){return"Moderate"===e||"High"===e||"Very High"===e}var Ks,Ys,Zs,Xs=D({"src/core/securityScheme.ts"(){Ps="-",Fs=["Very Low","Low","Moderate","High","Very High"],Us=["1","2","3","4","5"],Ls=[["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"]],Ws={"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"},Vs=[{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"}],Bs={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 eo(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 to(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. ${Zs}`}function no(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 ro(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function ao(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 io(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}=ao(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 so,oo,lo,co,uo,po,mo,_o,fo,ho,go,yo,wo,vo,bo,ko,jo,So,Ao,$o,xo,Io,qo,Oo,Eo,zo,Mo,Ro,To,Co,Do,Ho,No,Po,Fo,Uo,Lo,Wo,Vo,Bo,Jo,Go,Qo,Ko,Yo,Zo,Xo,el,tl,nl,rl,al,il,sl,ol=D({"src/core/acceptance.ts"(){Ks=["acceptance_state","accepted_by","accepted_at","acceptance_note","open_gaps_at_acceptance"],Ys=["prev_accepted_by","prev_accepted_at","accepted_snapshot_id","accepted_snapshot_name"],Zs="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 ll(e){return t=e?.industry,"automotive"===t||"medical"===t||"general"===t?e.industry:null;var t}function dl(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 cl(e){return oo[e]}function ul(e){return lo.some(t=>t.id===e)||function(e){return Vs.some(t=>t.id===e)}(e)}function pl(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:uo,source:"fallback"}}function ml(e){const t=(e??"").trim().toLowerCase();return"sub-system"===t?"subsystem":t}function _l(e,t){const n=pl(e),r=pl(t);return ml(n.level)===ml(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 fl(e,t,n){if("title"!==t&&("dfmea"!==e||"failure_mode"!==t)||n.length<=mo)return null;const r="title"===t?"a row's title holds":"an FMEA row's failure mode is also its title, which holds";return`${t} is ${n.length} characters; ${r} at most ${mo}. Shorten it to ${mo} or fewer.`}function hl(e){const t=(e.failure_mode??"").trim()||(e.hazard??"").trim()||"";if(t.length<=mo)return t;const n=t.slice(0,mo);return/[\uD800-\uDBFF]$/.test(n)?n.slice(0,-1):n}function gl(e){return"hazard_iso14971"===e?Io:"security_tir57"===e?zo:[]}function yl(e){return"security_tir57"===e?Fs:qo}function wl(e){return String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e)}function vl(e){const t=e??{};return{intended_use:String(t.intended_use??"").trim(),foreseeable_misuse:wl(t.foreseeable_misuse),safety_characteristics:wl(t.safety_characteristics)}}function bl(e,t=qo){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:Oo.includes(a)?a:"",safety_rationale:String(n.software_safety_rationale??"").trim()}}function kl(e){return""!==vl(e).intended_use}function jl(e,t){const n=gl(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 Sl(e,t,n){return`Invalid ${e} value ${JSON.stringify(t)}. Allowed: ${n.join(", ")}`}function Al(e){const t=e?.analysis_props;return null===t||"object"!=typeof t||Array.isArray(t)?"legacy":t.event_model===Do?"hazard_goal":"legacy"}function $l(e,t){return"hara_iso26262"===e&&"hazard_goal"===t?Ho:Ro[e]}function xl(e){return"risk_analysis"===e||"hazard_analysis"===e?["iso14971"]:"security_risk"===e?["tir57"]:so[No[e]]}function Il(e){return Object.entries(Qo[e]).map(([e,t])=>({key:e,label:t}))}function ql(e,t){const n=Qo[e];return t.map(e=>({key:e,label:n[e]??e}))}function Ol(e){return Object.entries(function(e){return"hara_iso26262"===e?Wo:"dfmea_rpn"===e?Jo:"hazard_iso14971"===e?Bo:"security_tir57"===e?Bs:Go}(e)).map(([e,t])=>({key:e,text:t}))}function El(e){return"hazard_iso14971"===e?bo:"security_tir57"===e?Ws:null}function zl(e,t){const n=El(e);return n?n[t]??null:null}function Ml(e){return(e??"").trim().toLowerCase()}function Rl(e,t){const n=Ml(e);if(!n)return null;for(const e of t)if(Ml(e)===n)return e;return null}function Tl(e){const t=e?.severity||"",n=e?.exposure||"",r=e?.controllability||"";return t&&n&&r?"S0"===t||"E0"===n||"C0"===r?"QM":ho[`${t}-${n}-${r}`]||_o:_o}function Cl(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)?_o:String(t*n*r)}function Dl(e,t,n){const r=String(e??""),a=String(t??""),i=String(n??"");if(yo.indexOf(r)<0||yo.indexOf(a)<0||yo.indexOf(i)<0)return _o;const s=wo[`${a}-${i}`];return s&&vo[`${s}-${r}`]||_o}function Hl(e){return Dl(e?.severity,e?.p1,e?.p2)}function Nl(e){return Dl(e?.residual_s,e?.residual_p1,e?.residual_p2)}function Pl(e){return Gs(e?.severity,e?.exploitability)}function Fl(e){return Gs(e?.residual_s,e?.residual_e)}function Ul(e,t){return"hara_iso26262"===e?Tl(t):"hazard_iso14971"===e?Hl(t):"security_tir57"===e?Pl(t):"fmea_software"===e?function(e){return Cl({...e??{},occurrence:ko})}(t):Cl(t)}function Ll(e,t,n,r){if(n)return!1;if("hara_iso26262"===e&&r?.cited&&r.satisfied)return!1;if("hara_iso26262"===e){const e=Tl(t);return"C"===e||"D"===e}if("hazard_iso14971"===e)return"High"===Hl(t);if("security_tir57"===e){const e=Pl(t);return"High"===e||"Very High"===e}const a=parseInt(Ul(e,t),10);return!Number.isNaN(a)&&a>=200}function Wl(e,t,n,r,a){if(!e?.approved||!e.approved_at)return!1;const i=Date.parse(e.approved_at);if(Number.isNaN(i))return!1;const s=r?Date.parse(r):NaN;return!Number.isNaN(s)&&s>i||[...e.source_req?[e.source_req]:[],...t,...a??[]].some(e=>{const t=n(e),r=t?Date.parse(t):NaN;return!Number.isNaN(r)&&r>i})}function Vl(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 Bl(e){return"fmea_software"===e?{field:"occurrence",value:ko}:null}function Jl(e){const t=Bl(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 Gl(e){return Xo[e]}function Ql(e){return"security_tir57"===e?Vs:function(e){return"hazard_iso14971"===e||"fmea_process"===e||"fmea_software"===e||"fmea_use"===e}(e)?lo:[]}function Kl(e){return Ql(e).map((e,t)=>({...e,precedence:t+1}))}function Yl(e){return"hara_iso26262"===e||"hazard_iso14971"===e||"security_tir57"===e}function Zl(e,t){return`${e} is not a ${Xo[t].mitigating_requirement}: a mitigation target must be a requirement of req_type '${co}'. Create or convert one, then link it.`}function Xl(e){return`control_type applies to the medical schemes only (ISO 14971 clause 7); ${Xo[e].parent} links carry none, so omit it.`}function ed(e){return"security_tir57"===e?`control_type is required for a security control link (FDA Appendix 1). Choose one of: ${Vs.map(e=>`${e.id} (${e.label})`).join(", ")}.`:`control_type is required for a risk control link (ISO 14971 clause 7). Choose one of: ${lo.map(e=>`${e.id} (${e.label})`).join(", ")}.`}function td(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 nd(e){const t=parseInt(e,10);return!Number.isNaN(t)&&t>=100}function rd(e){return"hara_iso26262"===e?nl:"hazard_iso14971"===e?rl:"security_tir57"===e?il:al}function ad(e){return!0===e.approved&&(e.approved=!1,e.approved_at=null,e.approved_by=null,e.approved_note="",!0)}function id(e,t,n,r){const a=[];for(const i of rd(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}function sd(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function od(e,t,n=Ml){const r=new Set(t.map(n).filter(e=>e.length>0));return e.filter(e=>r.has(n(e)))}function ld(e){const t=e.length>1;return`Function-flagged tag${t?"s":""} used as domain${t?"s":""}: ${e.join(", ")}. A function tag is not a domain tag: tag the item with a domain instead. A function is an item: create one with atoms_create_item type 'function' and name it on an analysis row by its id (atoms_create_analysis source_function_ids), in a project with Function items turned on; a project still on function tags turns one back into a domain in Taxonomy Management.`}var dd,cd,ud,pd=D({"src/core/analysis.ts"(){Xs(),Xs(),ol(),so={hara:["iso26262","iso14971","tir57"],dfmea:["design","process","software","use"]},oo={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"},lo=[{id:"inherent",label:"Inherent design",abbr:"ID"},{id:"protective",label:"Protective measure",abbr:"PM"},{id:"information",label:"Information for safety",abbr:"IFS"}],co="safety",uo="L1",po=8,mo=500,_o="-",fo=["prevention","detection","mitigation"],ho={"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"},wo={"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"},vo={"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"},bo={Low:"Acceptable",Medium:"Acceptable with justification",High:"Not acceptable"},ko="10",jo={hara_iso26262:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea_rpn:{severity:go=["1","2","3","4","5","6","7","8","9","10"],occurrence:go,detection:go},hazard_iso14971:{severity:yo=["1","2","3","4","5"],p1:yo,p2:yo,residual_s:yo,residual_p1:yo,residual_p2:yo},fmea_process:{severity:go,occurrence:go,detection:go},fmea_software:{severity:go,detection:go},fmea_use:{severity:go,occurrence:go,detection:go},security_tir57:{severity:[...Us],exploitability:[...Us],residual_s:[...Us],residual_e:[...Us]}},So={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"]},Ao={security_tir57:{aliases:{threat_event:"failure_mode",vulnerability:"operating_scenario",impact:"effect",harm:"hazard",security_control:"safety_goal"},row:"security risk analysis row",kind:"security name"},hazard_iso14971:{aliases:{harm:"hazard",hazardous_situation:"effect",sequence_of_events:"operating_scenario"},row:"risk analysis row",kind:"ISO 14971 name"}},$o=["intended_use","foreseeable_misuse","safety_characteristics"],xo=["overall_residual_risk","overall_residual_rationale","software_safety_class","software_safety_rationale"],Io=[...$o,...xo],qo=["Low","Medium","High"],Oo=["A","B","C"],Eo=["threat_model_method","threat_model_rationale","environment_assumptions","attack_surfaces","related_documents","overall_residual_risk","overall_residual_rationale"],zo=[...Eo,"lifecycle_sources"],Mo={hara:"safety-goal",dfmea:"failure-mode"},Ro={hara_iso26262:"SG",dfmea_rpn:"FM",hazard_iso14971:"RSK",fmea_process:"PF",fmea_software:"FM",fmea_use:"FM",security_tir57:"CYB"},To={hara_iso26262:"HARA",dfmea_rpn:"DFMEA",hazard_iso14971:"RA",fmea_process:"PFMEA",fmea_software:"SFMEA",fmea_use:"UFMEA",security_tir57:"SEC"},Co=["HA"],Array.from(new Set([...Object.values(To),...Object.values(Ro),...Co])).sort(),Do="hazard_goal",Ho="HE",No={hara:"hara",dfmea:"dfmea",risk_analysis:"hara",fmea:"dfmea",hazard_analysis:"hara",security_risk:"hara"},Po=["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"],Fo={hara:"iso26262",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"design",fmea:"process",security_risk:"tir57"},Uo={hara:"iso14971",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"process",fmea:"process",security_risk:"tir57"},Lo={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."},Wo={...Lo,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:to("The confirmation review of the HARA (ISO 26262)")},Vo={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)."},Bo={...Lo,...Vo,accept_analysis:to("The ISO 14971 clause 8 overall residual risk conclusion")},Jo={...Lo,dfmea_s:Wo.dfmea_s,o:Wo.o,d:Wo.d,rpn:Wo.rpn,accept_analysis:to("The AIAG-VDA FMEA sign-off")},Go={...Lo,dfmea_s:Vo.dfmea_s,o:Vo.o,o_sw:Vo.o_sw,d:Vo.d,rpn:Vo.rpn,process_step:Vo.process_step,controls:Vo.controls,fn:Vo.fn,risk_control:Vo.risk_control,control_req:Vo.control_req,verified_by:Vo.verified_by,accept_analysis:to("The FMEA sign-off")},Qo={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"}},Ko=["asil","rpn","risk","p0"],Yo=["approved","approved_at","approved_by","approved_note","field_source","link_roles","mitigation_types"],Zo=[...Ko,...Yo],Xo={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"}},el=(e,t,n)=>1===e?t:n,nl=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft safety requirement",label:e=>`${e} ${el(e,"safety goal","safety goals")} unmitigated`,matches:e=>e.level!==_o&&"QM"!==e.level&&!e.linked},{kind:"no_test",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${el(e,"safety goal","safety goals")} without a test on its ODD`,matches:e=>e.level!==_o&&"QM"!==e.level&&e.linked&&!e.verified},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} ${el(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},tl={kind:"not_accepted",scope:"analysis",fix:"open_analysis",fixLabel:"Accept analysis",label:()=>"Analysis not accepted",matchesAnalysis:e=>e.hasRows&&!e.accepted}],rl=[{kind:"no_control",scope:"row",fix:"link_requirement",fixLabel:"Draft risk control requirement",label:e=>`${e} ${el(e,"risk","risks")} above Low with no control`,matches:e=>e.level!==_o&&"Low"!==e.level&&!e.linked},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${el(e,"control","controls")} not verified for effectiveness`,matches:e=>e.level!==_o&&"Low"!==e.level&&e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual ${el(e,"risk","risks")} not assessed`,matches:e=>e.level!==_o&&"Low"!==e.level&&e.linked&&e.residualLevel===_o},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} risk ${el(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},tl],al=[{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=>nd(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=>!nd(e.level)&&null!==e.severity&&e.severity>=9&&!e.linked},tl],il=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft security control",label:e=>`${e} security ${el(e,"risk","risks")} above Low with no control`,matches:e=>Qs(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===_o},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${el(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===_o},{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(Qs(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 ${el(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},{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},tl],sl=[{kind:"row_no_goal",fix:"open_row",fixLabel:"Set the safety goal",informational:!1,label:e=>`${e} hazardous ${el(e,"event","events")} rated ASIL A-D with no safety goal or safety requirement`},{kind:"goal_no_safety_req",fix:"link_requirement",fixLabel:"Draft safety requirement",informational:!1,label:e=>`${e} ${el(e,"safety goal","safety goals")} with no safety requirement`},{kind:"goal_no_test",fix:"open_row",fixLabel:"Verify its safety requirement",informational:!1,label:e=>`${e} ${el(e,"safety goal","safety goals")} with a hazardous event no verified safety requirement covers`},{kind:"hazard_uncited",fix:"open_item",fixLabel:"Open hazard",informational:!0,label:e=>`${e} ${el(e,"hazard","hazards")} cited by no hazardous event`},{kind:"goal_trashed",fix:"open_row",fixLabel:"Open row",informational:!0,label:e=>`${e} hazardous ${el(e,"event cites","events cite")} a safety goal in Trash`}]}});async function md(e,t,n,r){const a=await async function(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)}(e,t),i=r.includes(n)||a.includes(n)?n:Rl(n,r)??Rl(n,a);return{spelling:i,registered:null!==i&&r.includes(i),carried:a.filter(e=>null!==Rl(e,[n]))}}async function _d(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 fd(e){return`Domain "${e}" registered. You can now tag items with domains=["${e}"].`}function hd(e,t){return t?`"${e}" is already a function tag of this project, and a function tag is not a domain tag. Choose another domain name. A function is an item: create one with atoms_create_item type 'function', in a project with Function items turned on.`:`Domain "${e}" already exists in this project.`}function gd(e){return`Domain "${e}" already exists. Choose a different name.`}var yd,wd,vd,bd,kd=D({"src/core/domains.ts"(){pd(),dd="domain_not_function",cd=class extends Error{code=dd;names;unregistered;constructor(e,t=[]){super(`${dd}: ${e.join(", ")}`),this.name="DomainNotFunctionError",this.names=[...e],this.unregistered=[...t]}},ud="domain_rename_onto_function"}});function jd(){return{status:"error",code:wd,retryable:!0,message:vd,next_steps:["Send the same call again in a moment","If it times out again, tell the user ATOMS is slow right now"]}}function Sd(e,t){return"57014"===e||/statement timeout|request timeout|upstream request timeout/i.test(t)}var Ad,$d,xd,Id=D({"src/core/read-budget.ts"(){yd=25e3,wd="read_timed_out",vd="ATOMS did not answer this read in time, so nothing was returned. The read changes nothing: asking again is safe.",bd=class extends Error{code=wd;constructor(e){super(`${wd}: the read did not finish within ${e} ms`),this.name="ReadBudgetExceededError"}}}});function qd(e,t=0,n=$d){const r=e.slice(t,t+n),a=t+r.length,i=a<e.length;return{rows:r,meta:{total_count:e.length,limit:n,offset:t,has_more:i,...i?{next_offset:a}:{}}}}function Od(e,t,n){const r=n+t<e;return{total_count:e,limit:t,offset:n,has_more:r,...r?{next_offset:n+t}:{}}}function Ed(e,t=Ad,n,r){if(xd(e)<=t)return e;if("success"!==e.status)return e;if(r)return function(e,t,n){const r=e.data;if(!r||"object"!=typeof r||!Array.isArray(r[n]))return Ed(e,t);const a=e=>Array.isArray(e)?e.map(e=>e&&"object"==typeof e&&!Array.isArray(e)?(({title:e,...t})=>t)(e):e):e,i=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,a(t)])),s=[],o={},l=()=>({...e,data:i,meta:{...e.meta??{},truncated:!0,truncation_message:`Response kept near ${t} characters: titles left out (they are the titles you sent, in the same order)${s.length>0?`; arrays cut: ${s.join(", ")}`:""}. Every created item is listed in '${n}'.`}});for(;;){const e=l();if(xd(e)<=t)return e;let r,a=0;for(const[e,t]of Object.entries(i))if(e!==n&&Array.isArray(t)&&t.length>1){const n=JSON.stringify(t).length;n>a&&(r=e,a=n)}if(!r)return e;const d=i[r];o[r]??=d.length,i[r]=d.slice(0,Math.floor(d.length/2));const c=`${r} ${o[r]} to ${i[r].length}`,u=s.findIndex(e=>e.startsWith(`${r} `));u>=0?s[u]=c:s.push(c)}}(e,t,r);if(n){const r=function(e,t,n){const r=void 0===n.list?e.data:e.data?.[n.list];if(!Array.isArray(r)||r.length<2)return null;const a=e.meta??{},i=i=>{let s;if("none"===n.resume)s={next:""};else if(n.resume)s=n.resume(i);else{const e="number"==typeof a.offset?a.offset:0;s={meta:{next_offset:e+i},next:`offset=${e+i}`}}const o=r.slice(0,i),l=void 0===n.list?o:{...e.data,[n.list]:o,...s.data},d=s.next?`Call again with ${s.next} to continue after the last returned row.`:"Lower 'limit' or narrow the query to see the rest.";return{...e,data:l,meta:{...a,returned:i,has_more:!0,...s.meta,truncated:!0,truncation_message:`Response truncated to stay under ${t} characters (${n.list??"items"} ${r.length} to ${i}). ${d}`}}};if(xd(i(1))>t)return null;let s=1,o=r.length-1;for(;s<o;){const e=Math.ceil((s+o)/2);xd(i(e))<=t?s=e:o=e-1}return i(s)}(e,t,n);if(r)return r;const a=function(e,t,n){const r=void 0===n.list?e.data:e.data?.[n.list];if(!Array.isArray(r)||0===r.length)return null;const a=void 0===n.list?{...e,data:r.slice(0,1)}:{...e,data:{...e.data,[n.list]:r.slice(0,1)}};if(xd(a)<=t)return null;const i=r[0],s=i&&"object"==typeof i?i.id??i.item_id??i.name:void 0,o="string"==typeof s||"number"==typeof s?String(s):"1",l={...e.meta??{}},d=r.length>1||!0===l.has_more;let c="";if("none"===n.resume);else if(n.resume){const e=n.resume(1);Object.assign(l,e.meta??{}),c=e.next,l.has_more=d}else{const e="number"==typeof l.offset?l.offset:0,t="number"==typeof l.total_count?l.total_count:void 0,n=void 0!==t?e+1<t:d;l.has_more=n,n?(l.next_offset=e+1,c=`offset=${e+1}`):delete l.next_offset}const u={...l,returned:0,truncated:!0,truncation_message:`Response truncated to stay under ${t} characters: row ${o} alone is larger than that, so this answer shows it only as a text preview and returns no other row. `+(c&&l.has_more?`Call again with ${c} to continue after it. `:"")+`Read row ${o} on its own (atoms_get_item for an item) or narrow the request to see it whole.`};return zd(e,t,()=>u)}(e,t,n);if(a)return a}const a=n=>({...e.meta??{},truncated:!0,truncation_message:`Response truncated to stay under ${t} characters (${n}). Narrow the request to see more results.`});if(Array.isArray(e.data)){const n=e.data.length;let r=e.data,i={...e,data:r,meta:a(`${n} items cut`)};for(;xd(i)>t&&r.length>1;)r=r.slice(0,Math.max(1,Math.floor(r.length/2))),i={...e,data:r,meta:a(`from ${n} to ${r.length} items`)};return xd(i)<=t?i:zd(e,t,a)}if(e.data&&"object"==typeof e.data){const n={...e.data},r=[],i={},s=()=>({...e,data:n,meta:a(`arrays cut: ${r.join(", ")}`)});for(;;){if(xd(s())<=t)return s();let e,a=0;for(const[t,r]of Object.entries(n))if(Array.isArray(r)&&r.length>1){const n=JSON.stringify(r).length;n>a&&(e=t,a=n)}if(!e)break;const o=n[e];i[e]??=o.length,n[e]=o.slice(0,Math.floor(o.length/2));const l=`${e} ${i[e]} to ${n[e].length}`,d=r.findIndex(t=>t.startsWith(`${e} `));d>=0?r[d]=l:r.push(l)}}return zd(e,t,a)}function zd(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-xd({...e,data:{preview:""},meta:r})-200);for(;;){const n={...e,data:{preview:a.slice(0,i)},meta:r},s=xd(n)-t;if(s<=0||0===i)return n;i=Math.max(0,i-s)}}var Md,Rd,Td,Cd,Dd,Hd,Nd,Pd,Fd,Ud=D({"src/core/response-limit.ts"(){Ad=25e3,$d=1e3,xd=e=>JSON.stringify(e,null,2).length}});function Ld(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)}function Wd(){const e=Dd.now(),t=null===Nd?0:Math.max(0,e-Nd);return Hd=Math.min(Td.capacity,Hd+t/1e3*Td.refillPerSecond),Nd=e,!(Hd<1||(Hd-=1,0))}function Vd(e,t){t.openUntil=Dd.now()+Cd.cooldownMs,t.probeAt=0,console.warn(`[atoms-mcp] busy breaker opened for project ${e}: ${t.failures} of ${t.calls} calls failed`)}function Bd(e,t,n){const r=Pd.get(e);if(n){if(!r)return;return void(t?Vd(e,r):(Pd.delete(e),console.warn(`[atoms-mcp] busy breaker closed for project ${e}`)))}if(r?.openUntil)return;if(!r&&!t)return;const a=Dd.now();!r&&Pd.size>=Cd.maxScopes&&Pd.delete(Pd.keys().next().value);const i=r??{windowStart:a,calls:0,failures:0,openUntil:0,probeAt:0};a-i.windowStart>Cd.windowMs&&Object.assign(i,{windowStart:a,calls:0,failures:0}),i.calls+=1,t&&(i.failures+=1),Pd.set(e,i),i.calls>=Cd.minCalls&&i.failures/i.calls>=Cd.failureRatio&&Vd(e,i)}async function Jd(e,t={}){const{scope:n,afterWrite:r=!1}=t,a=t.delays??(r?Rd:Md),i=void 0===n||r?"pass":function(e){const t=Pd.get(e);if(!t||0===t.openUntil)return"pass";const n=Dd.now();return n<t.openUntil?"shed":n-t.openUntil>=Cd.windowMs?(Pd.delete(e),"pass"):0!==t.probeAt&&n-t.probeAt<Cd.cooldownMs?"shed":(t.probeAt=n,"probe")}(n);if("shed"===i)return{data:null,error:{code:"55P03",message:"item_save_busy: this project is answering busy; retry in a few seconds"}};const s="probe"===i;let o;try{if(o=await e(),!s)for(const t of a){if(!Ld(o.error))break;if(!r&&!Wd())break;await Dd.sleep(Math.round(t*Dd.jitter())),o=await e()}}catch(e){throw void 0!==n&&Bd(n,!0,s),e}return void 0!==n&&Bd(n,function(e){const t=e.error;return Ld(t)||"57014"===t?.code||/statement timeout/i.test(t?.message??"")||Gd(e)}(o),s),o}function Gd(e){return null!=e.error&&[0,502,503,504].includes(e.status??-1)}async function Qd(e){const t=await e();return Gd(t)?(await Dd.sleep(250),e()):t}var Kd,Yd,Zd,Xd,ec,tc,nc=D({"src/core/busy-retry.ts"(){Md=[200,400,800],Rd=[100,200,400,800,1600],Cd={windowMs:1e4,minCalls:5,failureRatio:.5,cooldownMs:5e3,maxScopes:1e3},Dd={sleep:e=>new Promise(t=>setTimeout(t,e)),jitter:()=>Math.random(),now:()=>Date.now()},Hd=(Td={capacity:60,refillPerSecond:10}).capacity,Nd=null,Pd=new Map,Fd=[250,1e3,3e3]}});function rc(){return{status:"error",message:Kd,next_steps:["Do not retry this call","Tell the user that a person can restore it from Trash in ATOMS"],code:Yd,retryable:!1}}function ac(e,t){const n=function(e){const t=e.status??-1;return 0===t||t>=500||Ld(e)||"57014"===e.code||/timeout|timed out|canceling statement/i.test(e.message)}(t),r=Zd.find(([e])=>e.test(`${t.code??""} ${t.message}`));return{status:"error",message:`${e} is back from Trash, but its links could not be rebuilt (${t.message}). The links are still stored on the item, so none is lost, but some may not show until they are rebuilt.`,next_steps:n?[`Call atoms_restore_item again for ${e}: it is no longer in Trash, so the call only rebuilds its links, and it answers that ${e} is not deleted once they are rebuilt`,`If it keeps failing, tell the user that ${e} is back but some of its links may be missing, and to ask ATOMS support to rebuild them`]:[r?r[1](e):`Tell the user that ${e} is back but some of its links may be missing, and to ask ATOMS support to rebuild them`,`Until then ${e} may show without some of its links; ATOMS support can rebuild them`],code:"restore_links_not_rebuilt",retryable:n}}function ic(e){const t=e.trashed_by,n=t?.name?.trim()||"Someone";return t?.agent?`${n}'s agent`:n}function sc(e){return(e.deleted_at??"").slice(0,10)}function oc(e,t){const n=`Restored ${e.item_id} from Trash. It was moved there by ${ic(e)} on ${sc(e)}`;return e.trashed_by?.user_id&&e.trashed_by.user_id!==t?`${n}; they have been notified.`:`${n}.`}var lc,dc,cc,uc,pc,mc,_c,fc,hc,gc=D({"src/core/restore-confirm.ts"(){nc(),Kd="This item has been in Trash for more than 7 days. Only a person can restore it, from Trash in ATOMS.",Yd="item_trash_too_old",Zd=[[/change_open_by_other/i,e=>`Tell the user that a change another person opened on an item linked to ${e} stops its links from being rebuilt: once that change is approved or withdrawn, call atoms_restore_item again for ${e}`],[/suspended/i,e=>`Tell the user that their account or organization is suspended, so the links of ${e} cannot be rebuilt: an organization admin or ATOMS support must lift the suspension first`],[/42501|permission denied|access denied/i,e=>`Tell the user that rebuilding the links of ${e} needs editor access to this project: an admin of the project can grant it, and then atoms_restore_item can be called again for ${e}`]],Xd=["Show the user this message","Call atoms_restore_item again with confirm: true only after the user agrees"],ec='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',tc="true only after the user has seen the needs_confirmation message and agreed to the restore"}}),yc={};function wc(e,t=dc){if("string"!=typeof e)return"";const n=e.replace(pc,"").replace(mc,"");return n.length<=t?n:n.slice(0,t)+"..."}function vc(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function bc(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function kc(e,t,n){return{total_count:e,limit:t,offset:n,has_more:n+t<e}}function jc(e,t,n={}){return{status:"error",message:e,next_steps:t,...n}}function Sc(e,t){return jc(`${e} '${wc(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function Ac(e){return"account"===e?jc("Account suspended.",["Your ATOMS account is suspended, so ATOMS tools are unavailable","Contact ATOMS support or your organization admin to restore access"]):jc("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 $c(e){const t=/\b(account|organization) suspended\b/i.exec(e);return t?t[1].toLowerCase():null}function xc(e){return jc(`${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 Ic(e,t=cc){return jc(`Validation error: ${wc(e,t)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function qc(){return jc("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 Oc(){return jc("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 Ec(e){return jc("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 zc(e){return jc("Tool call rejected: this project's organization is outside the configured ATOMS_MCP_ORG_ID scope.",[`This MCP session is bound to organization ${e}`,"Use a project of that organization, or restart without ATOMS_MCP_ORG_ID to reach other organizations"])}function Mc(e){return function(e){const t=e&&e>0?Math.ceil(e):Jt;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 Rc(){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 Tc(e){return jc(`Parse error: ${wc(e,cc)}`,["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 Cc(e){return Kt(e)}function Dc(){return jc("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 Hc(){return jc("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 Nc(){return jc("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 Pc(){return jc("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 Fc(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 Uc(e,t={}){const n=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(a=n,Lt.some(e=>e.test(a)))return Ic(n,uc);var a,i;if(e instanceof Wt)return Ic(n);if(Xt(n))return Lc(e);if(jr(n))return Sr();if(Pa(n))return Fa();if(Ms(n))return"function_items"===(i=Ms(n))?{status:"error",code:"rollout_switched",key:"function_items",retryable:!1,message:qs,next_steps:["This project's Functions are not items yet, so it keeps using its function tags for now","Ask an org admin to turn on Function items for this project if it should have Function items","Do not retry this call"]}:"hazard_goal_items"===i?Cs():"model_designs"===i?gs():{status:"error",code:"rollout_switched",retryable:!0,message:Is,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(Rs(n))return Ts();if(Ds(n))return Hs();if(Ns(n))return{status:"error",code:"hazard_goal_restore_refused",retryable:!1,message:"Validation error: This Hazard or Safety goal item cannot be restored, because Hazard and Safety goal items are for ISO 26262 (automotive) projects. It stays in the trash.",next_steps:["Leave the item in the trash, or change the project's industry to Automotive (ISO 26262) on the project settings page and restore it then","Do not retry this call"]};if(/^auth_unavailable:/.test(n))return Ot();if(/^read_timed_out:/.test(n))return jd();if(t.read&&Sd(r,n))return jd();if(/not authenticated/i.test(n))return qc();const s=function(e){const t=function(e){if(e instanceof cd)return e.names;if(e&&"object"==typeof e&&e.code===dd){const t=e.names;if(Array.isArray(t))return t.filter(e=>"string"==typeof e)}return null}(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.filter(e=>null!==Rl(e,t)),i={code:dd,domains:[...e]};return a.length>0&&(i.unregistered=[...a]),{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"}. A function is an item: create one with atoms_create_item type 'function', in a project with Function items turned on. Nothing was written.`,next_steps:["Create the Function with atoms_create_item type 'function' and name it by its id","Or choose a function name that is not already a domain"],details:i}}(t,Array.isArray(n)?n.filter(e=>"string"==typeof e):[])}(e);if(null!==s)return s;if(Fc(e))return Oc();if(Ar(n))return $r();const o=rn(n);if(null!==o)return o;if(function(e){return/item_trash_too_old/i.test(e)}(n))return rc();if(xr(n))return Ir();const l=Mr(n);if(null!==l)return l;const d=qr(n);if(null!==d)return d;const c=Or(n);if(null!==c)return c;const u=K(n);if(null!==u)return u;if("55P03"===r||function(e,t){return"40P01"===e||/deadlock detected/i.test(t)}(r,n)||function(e,t){return"55P03"===e||/canceling statement due to lock timeout|lock timeout/i.test(t)}(r,n)||/item_save_busy/i.test(n))return Hc();if(zr(n))return{status:"error",message:"Nothing was saved: one save may name at most 50 items, counting both ends of each link, and this one names more.",next_steps:["Send the links in smaller batches (49 links from one item at a time, for example)","Do not send the same call again unchanged"],code:"too_many_items",retryable:!1};if(function(e,t){return!/^[0-9A-Z]{5}$/.test(e)&&function(e){return/(?:^|:\s*)invalid url\b|uri too long|request-uri too (?:long|large)|url too long|(?<![\w.-])414(?![\w-])/i.test(e)}(t)}(r,n))return{status:"error",message:"The request was too large to send to the database (its URL passed the length limit), so nothing was read or written. Waiting does not change it.",next_steps:["Do not retry this call unchanged: the same request is refused every time.","Narrow it (fewer ids, a smaller depth, or a filter), and report the tool and item to ATOMS support."],code:"request_too_large",retryable:!1};if(function(e,t){return!/^[0-9A-Z]{5}$/.test(e)&&/rate.?limit|too many requests|(?<![\w.-])429(?![\w-])/i.test(t)}(r,n))return Mc();if(Cc(n))return Dc();if(/soft_deleted_item_write/i.test(n))return Pc();if(/save_temporarily_unavailable/i.test(n))return Nc();if("55P03"===r||Sd(r,n)||/item_save_busy/i.test(n))return Hc();const p=$c(n);return p?Ac(p):"42501"===r&&/org_project_field_admin_required/i.test(n)?tn("organization"):"42501"===r&&/project_field/i.test(n)?tn("project"):"P0002"===r&&/project_field/i.test(n)?jc("Project field not found.",["Refresh the field list and retry with an existing field name"]):"22023"===r&&/^project_field_values_incompatible:/i.test(n)?Ic(n.replace(/^project_field_values_incompatible:\s*/i,"")):["22023","23505","23514"].includes(r)&&/project_field/i.test(n)?Ic(n.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(n)?Tc(n):Vc(n)}function Lc(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??"");if(!Xt(t)&&!en(t))return null;const n=t.indexOf(_c);return jc((n>=0?t.slice(n+_c.length):t).trim(),["Wait a moment, read the item again (atoms_get_item), then send your change again"],{code:"rollout_switched",retryable:!0})}function Wc(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??""):"",r=K(t);return["40001","PT409","55P03","57014"].includes(n)||null!==Ms(t)||null!==r&&"mcp_policy_block_destructive"!==r.code||/stale_item_write|soft_deleted_item_write|save_temporarily_unavailable|item_save_busy|lock timeout|statement timeout|request timeout|upstream request timeout|fetch failed|network error|connection (?:closed|reset|refused)/i.test(t)}function Vc(e){if(/^auth_unavailable:/.test(e))return Ot();const t=rn(e);if(null!==t)return t;if(Yt(e))return Mc();if(Zt(e))return Oc();if(/^not authenticated/i.test(e))return qc();if(Ar(e))return $r();if(jr(e))return Sr();if(Pa(e))return Fa();if(Rs(e))return Ts();if(Ds(e))return Hs();if(Ns(e))return{status:"error",code:"hazard_goal_restore_refused",retryable:!1,message:"Validation error: This Hazard or Safety goal item cannot be restored, because Hazard and Safety goal items are for ISO 26262 (automotive) projects. It stays in the trash.",next_steps:["Leave the item in the trash, or change the project's industry to Automotive (ISO 26262) on the project settings page and restore it then","Do not retry this call"]};if(xr(e))return Ir();const n=Mr(e);if(null!==n)return n;const r=qr(e);if(null!==r)return r;const a=Or(e);if(null!==a)return a;const i=K(e);return null!==i?i:zr(e)?{status:"error",message:"Nothing was saved: one save may name at most 50 items, counting both ends of each link, and this one names more.",next_steps:["Send the links in smaller batches (49 links from one item at a time, for example)","Do not send the same call again unchanged"],code:"too_many_items",retryable:!1}:/row.level security|permission denied for/i.test(e)?jc("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"]):jc(`Database error: ${wc(e,cc)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function Bc(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function Jc(e){return"string"!=typeof e?e:e.replace(/<\s*\/?\s*user_content\s*>/gi,"")}function Gc(e){return fc.has(e)}function Qc(e,t,n=!1){return"string"==typeof e?n||null!=t&&fc.has(t)?Bc(e):e:Array.isArray(e)?e.map(e=>Qc(e,t,n)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Qc(t,e,n||hc.has(e))])):e}function Kc(e,t={}){const n=t.complete?e:Ed(e,void 0,t.paging,t.receipt);return{content:[{type:"text",text:JSON.stringify(Qc(n),null,2)}],structuredContent:n}}function Yc(e){return{content:[{type:"text",text:JSON.stringify(Qc(e),null,2)}],structuredContent:e,isError:!0}}H(yc,{CHARACTER_LIMIT:()=>lc,USER_CONTENT_KEYS:()=>fc,VALIDATION_MESSAGE_LONG:()=>uc,accessDeniedError:()=>xc,authError:()=>qc,classifyError:()=>Uc,dbError:()=>Vc,errorResponse:()=>jc,formatErrorResult:()=>Yc,formatToolResult:()=>Kc,isAutoWrappedKey:()=>Gc,isItemSaveStopError:()=>Wc,isJwtExpiredErrorForTool:()=>Fc,isStaleWriteErrorMessage:()=>Cc,jwtExpiredError:()=>Oc,notFoundError:()=>Sc,orgScopeError:()=>zc,paginationMeta:()=>kc,parseError:()=>Tc,policyNotLoadedError:()=>Rc,rateLimitError:()=>Mc,sanitizeForEcho:()=>wc,sanitizeTagOrLevel:()=>vc,saveBusyError:()=>Hc,saveUnavailableError:()=>Nc,scopeError:()=>Ec,softDeletedItemError:()=>Pc,staleWriteError:()=>Dc,stripUserContentMarkers:()=>Jc,success:()=>bc,suspendedError:()=>Ac,suspensionKind:()=>$c,switchRedoFailedError:()=>Lc,validationError:()=>Ic,wrapMcpUserContentFields:()=>Qc,wrapUserContent:()=>Bc});var Zc,Xc,eu,tu=D({"src/tools/_base.ts"(){an(),Js(),kd(),Mt(),Id(),re(),Ud(),ai(),gc(),lc=25e3,dc=50,cc=200,uc=600,pc=new RegExp("[\\u0000-\\u001F\\u007F]","g"),mc=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g"),_c="rollout_switched:multiuser_saving: ",fc=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","source_function_title","rerun_scope","report_text","reason","model_mermaid","box_label","arrow_label","creator_name","updated_by_name"]),hc=new Set(["fields","diff","point","theirs_value","base_value","your_value","old_value","new_value"])}});async function nu(e,t){const n=Xc.get(t),r=Date.now();if(n&&r-n.at<Zc)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 Xc.set(t,{status:s,at:r}),s}function ru(e){return JSON.stringify(Qc(e),null,2)}var au,iu,su,ou,lu,du,cu,uu,pu=D({"src/middleware/status-gate.ts"(){tu(),_e(),Zc=3e4,Xc=new Map,eu="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."}}),mu={};async function _u(){if(au)try{const e=await Ze();e&&e.expires_at>lu&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),fu())}catch{}if(au&&ou>Date.now()+6e4)return au;au&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:n}=await async function(){if(du&&Date.now()-du.at<1e3*St)throw du.error;return cu??=Ct().then(e=>(du=null,e)).catch(e=>{throw e instanceof $t&&(du={at:Date.now(),error:e}),e}).finally(()=>{cu=null}),cu}(),a=e.split(".");if(3===a.length)try{const e=JSON.parse(Buffer.from(a[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());ou=1e3*(e.exp??0)}catch{ou=Date.now()+36e5}try{const e=await Ze();lu=e?.expires_at??0}catch{lu=0}const i=function(e,t){try{Object.defineProperty(e,ni,{value:t,enumerable:!1,configurable:!0})}catch{}return e}(r.createClient(gt,yt,{global:{headers:{Authorization:`Bearer ${e}`},fetch:pi({supabaseUrl:gt,anonKey:yt,accessToken:e},gi())}}),{supabaseUrl:gt,anonKey:yt,accessToken:e});return iu=t,su=n,au=i}function fu(){du=null,au=null,iu=null,su=null,uu=void 0,ou=0,lu=0,Xc.clear()}function hu(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 gu(e){try{return await e()}catch(t){if(!hu(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),fu(),await e()}}function yu(){if(!iu)throw new Error("Not authenticated. Call getClient() first.");return iu}function wu(){return su??""}async function vu(e){const t=yu();if(uu&&uu.userId===t)return uu.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 uu={userId:t,name:a},a}catch{return null}}function bu(e){if(e&&e.deleted_at)throw new Error(Dn)}async function ku(e,t){const{data:n,error:r}=await e.from("projects").select("deleted_at").eq("id",t).maybeSingle();if(r||!n)throw Er(t,r);bu(n)}async function ju(e,t){const n=yu(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Er(t,a);bu(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 Su(e,t){const n=yu(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Er(t,a);bu(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";throw new Error("PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED")}H(mu,{assertProjectLive:()=>ku,getClient:()=>_u,getUserEmail:()=>wu,getUserId:()=>yu,getUserName:()=>vu,invalidateClient:()=>fu,isJwtExpiredError:()=>hu,requireProjectFieldDefinitionAccess:()=>Su,requireWriteAccess:()=>ju,throwIfProjectInTrash:()=>bu,withJwtRetry:()=>gu});var Au,$u,xu=D({"src/db/client.ts"(){Pt(),Mt(),ut(),It(),ai(),hi(),Si(),pu(),au=null,iu=null,su=null,ou=0,lu=0,du=null,cu=null}}),Iu={};async function qu(){const e=i.randomBytes(32).toString("base64url"),t=i.createHash("sha256").update(e).digest("base64url"),n=`http://localhost:${Au}${$u}`,r=new s.URL(`${wt}/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:${Au}`);if(i.pathname!==$u)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(Ou("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(`${gt}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:yt},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(Ou(`Code exchange failed: ${e}`)),o(),l.close(),void n(new Error(`Code exchange failed: ${e}`))}let d="authenticated";try{d=JSON.parse(Buffer.from(s.access_token.split(".")[1],"base64").toString()).email??d}catch{}const{createClient:c}=await import("@supabase/supabase-js"),u=c(gt,yt,{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(Ou('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 Xe({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:Date.now()+1e3*(s.expires_in??3600),user_email:d}),a.writeHead(200,{"Content-Type":"text/html"}),a.end(function(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>`}(d)),o(),l.close(),void t({email:d})):(a.writeHead(200,{"Content-Type":"text/html"}),a.end(Ou("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.")))}a.writeHead(400,{"Content-Type":"text/html"}),a.end(Ou("This page did not receive an authorization code, so nothing was saved. If you are signing in, finish it in the sign-in tab. Otherwise run the login command again."))}catch(e){a.writeHead(500),a.end("Authentication failed"),o(),l.close(),n(e)}});l.listen(Au,"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 Ou(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(Iu,{login:()=>qu});var Eu=D({"src/auth/login.ts"(){ut(),It(),Au=19275,$u="/callback"}}),zu={};async function Mu(){const{getValidToken:e,readValidToken:t}=await Promise.resolve().then(()=>(Pt(),Rt)),{runExclusiveAuth:n}=await Promise.resolve().then(()=>(vt(),pt)),{login:r}=await Promise.resolve().then(()=>(Eu(),Iu));try{return(await e()).email}catch(e){if(e instanceof $t)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(zu,{startupAuth:()=>Mu});var Ru,Tu,Cu,Du=D({"src/auth/startup.ts"(){Mt()}});function Hu(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&&Ru.has(n.level)?{level:n.level,source:"string"==typeof n.source?n.source:null,dismissed:!0===n.dismissed}:null}function Nu(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?Hu(e.data):null;return a&&(r.asil_pending_lower={value:a.level,source:a.source,dismissed:a.dismissed,since:t.since}),r}function Pu(e){return{op_id:"",status:"forbidden",reason:"asil_lower_needs_person",item_id:e,path:[...Tu],seq:null}}var Fu,Uu,Lu,Wu=D({"src/core/asil-read.ts"(){Ru=new Set(["QM","A","B","C","D"]),Tu=["asil_confirm_lower"],Cu="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 Vu(e){return e.startsWith("req_type '")}function Bu(e,t){if("requirement"!==t)return`req_type applies only to requirements (type='requirement'), not '${t}'.`;const n=`Plain requirement types: ${Fu.join(", ")}.`;return"safety-goal"===e?`req_type '${e}' is the type of a row of a HARA, a risk analysis or a security risk analysis, not of a plain requirement, so atoms_create_item and atoms_update_item refuse it. To make a Safety goal item (SG-n), call atoms_create_item with type 'goal' (automotive projects where Hazard and Safety goal items are on). To add a row to an analysis, call atoms_propose_rows, or atoms_create_analysis for a new analysis. ${n}`:"failure-mode"===e?`req_type '${e}' is the type of an FMEA row (a DFMEA, PFMEA, Software FMEA or Use FMEA), not of a plain requirement, so atoms_create_item and atoms_update_item refuse it. To add a row to an FMEA, call atoms_propose_rows, or atoms_create_analysis for a new one. ${n}`:Fu.includes(e)?null:`Unknown req_type '${e.slice(0,50)}'. Allowed: ${Fu.join(", ")}.`}var Ju,Gu,Qu,Ku,Yu=D({"src/core/req-type.ts"(){Fu=["functional","interface","performance","safety"],Uu=["safety-goal","failure-mode"],Lu="Requirement classification (functional|interface|performance|safety). safety-goal and failure-mode are the types of analysis rows, not of plain requirements, and are refused here: make a Safety goal item with atoms_create_item type 'goal', and add analysis rows with atoms_propose_rows or atoms_create_analysis."}});function Zu(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Qu)if(t.test(e.trim()))return"[redacted]";return e.length>Ku?e.slice(0,Ku)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Zu(e,t+1));if(null!==e&&"object"==typeof e){const n={};for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();Ju.has(e)?n[r]="[redacted]":Gu.has(e)?n[r]="string"==typeof a?"[content]":Zu(a,t+1):n[r]=Zu(a,t+1)}return n}return e}function Xu(e){return Zu(e)}var ep,tp,np,rp,ap,ip,sp,op,lp=D({"src/middleware/audit.ts"(){Ju=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),Gu=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Qu=[/^[^\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_-]+$/],Ku=200}}),dp=D({"src/middleware/rate-limiter.ts"(){ep=60,tp=6e4}}),cp={};function up(){return M.default.join(t.homedir(),".atoms","update-check.json")}async function pp(){if(!op&&(op=!0,"1"!==process.env.ATOMS_MCP_NO_UPDATE_CHECK))try{const e=await async function(){try{const e=JSON.parse(await o.promises.readFile(up(),"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<rp)return void(ip=e.latest);const t=new AbortController,n=setTimeout(()=>t.abort(),ap);try{const e=await fetch(process.env.ATOMS_MCP_UPDATE_URL??np,{signal:t.signal});if(!e.ok)return;const n=await e.json();if("string"!=typeof n.version)return;ip=n.version,await async function(e){try{await o.promises.mkdir(M.default.dirname(up()),{recursive:!0}),await o.promises.writeFile(up(),JSON.stringify({checked_at:Date.now(),latest:e}),"utf8")}catch{}}(n.version)}finally{clearTimeout(n)}}catch{}}function mp(e){return null!==ip&&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,ip)?{current:e,latest:ip,args:["@atoms-tech/atoms-mcp@latest"],command:"npx @atoms-tech/atoms-mcp@latest"}:null}function _p(e){const t=mp(e);return t?Rr(t.current,t.latest):null}function fp(e){if(sp)return null;const t=_p(e);return null===t?null:(sp=!0,t)}function hp(e,t){const n=fp(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 gp(e,t){const n=mp(t);if(null===n||!e||"object"!=typeof e)return e;const r=Rr(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 yp(){ip=null,sp=!1,op=!1}H(cp,{UPDATE_CHECK_TIMEOUT_MS:()=>ap,attachUpdateAvailable:()=>gp,attachUpdateNotice:()=>hp,getUpdateAvailable:()=>mp,resetUpdateCheckForTests:()=>yp,startUpdateCheck:()=>pp,takeUpdateNotice:()=>fp,updateStatusSentence:()=>_p});var wp,vp,bp,kp,jp,Sp,Ap,$p,xp,Ip,qp,Op,Ep,zp,Mp,Rp,Tp,Cp=D({"src/middleware/update-check.ts"(){ai(),np="https://registry.npmjs.org/@atoms-tech/atoms-mcp/latest",rp=864e5,ap=3e3,ip=null,sp=!1,op=!1}}),Dp=D({"src/core/timestamps.ts"(){}});function Hp(e){return 32===e||9===e||13===e||10===e}function Np(e){if("string"!=typeof e)return NaN;const t=wp.exec(function(e){let t=0,n=e.length;for(;t<n&&Hp(e.charCodeAt(t));)t++;for(;n>t&&Hp(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="",d="Z"]=t,c=Number(n),u=Number(r),p=Number(a),m=Date.UTC(c,u-1,p,Number(i),Number(s),Number(o));if(new Date(m).getUTCDate()!==p)return NaN;let _=0;if("Z"!==d.toUpperCase()){const e="-"===d[0]?-1:1,t=d.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 Pp(e,t){const n=Np(e),r=Np(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 Fp(e){return"passed"===e||"failed"===e||"blocked"===e}function Up(e){const t=[];return e.forEach((e,n)=>{e&&void 0!==e.date&&null!==e.date&&t.push(n)}),t}function Lp(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 Wp(e){const t=[];return e.forEach((e,n)=>{const r=e?.release_id;"string"==typeof r&&""!==r.trim()||t.push(n)}),t}function Vp(e){return`No release_id was sent on ${e.length} ${1===e.length?"entry":"entries"} (results[${e.join(", ")}]), so ${1===e.length?"that run counts":"those runs count"} toward no Release: atoms_verification_status and the app's Release views do not read them, and their Release cannot be set later. A run counts toward a Release only when it is recorded with that Release's release_id (atoms_list_baselines lists the Releases).`}function Bp(e,t,n){if(Array.isArray(e))for(const n of e)if(n&&"object"==typeof n&&n.op_id===t){const e=n.result;if("string"==typeof e)return e}return null!=n?.step_results?null:String(n?.result??"")}function Jp(e,t){const n=[];return Array.isArray(t)?(e.forEach((e,r)=>{const a=t[r]?.result;"string"==typeof a&&a!==e?.result&&n.push(r)}),n):n}function Gp(e,t=!1){return(t?"This run was":`${1===e.length?"The run of":"The runs of"} results[${e.join(", ")}] ${1===e.length?"was":"were"}`)+" stored with another result than the one sent: a run sent with step_results takes its verdict from them and the result sent with it is not used. Each result in this answer is the verdict as stored."}function Qp(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 Kp(e,t){return"string"==typeof e?t(e):Array.isArray(e)?e.map(e=>Kp(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Kp(n,t)])):e}function Yp(e,t){const n=Kp(e,t);return zp(n?.point)&&(n.point=Object.fromEntries(Object.entries(n.point).map(([e,n])=>[t(e),n]))),n}function Zp(e,t){if(!Array.isArray(e)||!Array.isArray(t))return e;const n=["source","plus","minus"];return e.map(e=>{if(!zp(e)||n.some(t=>t in e))return e;const r=t.find(t=>zp(t)&&t.name===e.name);return zp(r)&&JSON.stringify(r.values)===JSON.stringify(e.values)?{...e,...Object.fromEntries(Object.entries(r).filter(([e])=>n.includes(e)))}:e})}function Xp(e){const t=e.data?.status,n="test-case"===e.type?im(e.data):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||Pp(r.date,n.date)<0)&&(n=r);return n}(e,e=>Fp(e.result))?.result;return Fp(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 em(e){const t=e.data?.runs;return"test-case"===e.type&&Array.isArray(t)&&t.length>0}function tm(e){return`${e} has runs: ${Mp}. Record a run: atoms_record_test_result(s).`}function nm(e,t){return"test-case"===e.type&&!em(e)&&("passed"===t||"failed"===t||"blocked"===t)}function rm(e){return`${e} has no runs: ${Rp}. Record a run: atoms_record_test_result(s).`}function am(e,t){const n="string"==typeof e.result?e.result:void 0;if(Fp(n))return n;if(!Array.isArray(e.step_results)||0===e.step_results.length)return"not-run";const r=e.step_results.map(e=>zp(e)?e.status:void 0);if(r.includes("failed"))return"failed";if(r.includes("blocked"))return"blocked";const a=r.filter(e=>"passed"===e||"skipped"===e).length;return a>=Math.max(t??r.length,1)&&a===r.length&&r.includes("passed")?"passed":"not-run"}function im(e){const t=e?.runs;if(!Array.isArray(t))return t;const n=Array.isArray(e?.steps)?e.steps.length:void 0;return t.map(e=>zp(e)?{...e,result:am(e,n)}:e)}var sm,om,lm,dm,cm,um,pm,mm,_m,fm=D({"src/core/run-order.ts"(){wp=/^([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,vp="No release_id was sent, so this run counts toward no Release: atoms_verification_status and the app's Release views do not read it, and its Release cannot be set later. A run counts toward a Release only when it is recorded with that Release's release_id (atoms_list_baselines lists the Releases).",bp="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.",kp="Ignored: the run is stamped with server time. A supplied date is reported in the response warning, never stored.",jp="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.",Sp="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.",Ap="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).",$p="Ignored: the server pins the test case's current steps revision itself",xp="Link to evidence kept elsewhere, at most 2048 characters. Stored as text; ATOMS does not open it",Ip="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",qp="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.",Op="Step id, required on every step. A step that already exists keeps the id atoms_get_item returned. A NEW step needs an id of the form st_ followed by exactly 16 lowercase hexadecimal characters, for example st_0f3a9c1d2b4e5f60; on a project that saves one field at a time any other new id is refused with bad_row_id.",Ep="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.",zp=e=>!!e&&"object"==typeof e&&!Array.isArray(e),Mp="its status comes from its runs and cannot be set",Rp="a result can only come from a run",Tp="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 hm(e){return"requirement"===e.type&&"string"==typeof e.data?.req_type&&Uu.includes(e.data.req_type)}function gm(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 ym(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||!hm(a)&&"goal"!==a.type)return;if("requirement"!==i.type||hm(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}function wm(e,t){const n=ym(e,t),r=new Map;for(const t of e)r.set(t.id,t);const a=new Map;for(const e of t){const[t,n]="event_goal"===e.type?[e.from_id,e.to_id]:"goal_events"===e.type?[e.to_id,e.from_id]:[null,null];if(!t||!n||a.has(t))continue;const i=r.get(t);i&&hm(i)&&"goal"===r.get(n)?.type&&a.set(t,n)}const i=new Map;for(const[e,t]of n)hm(r.get(e))&&i.set(e,t);for(const[e,t]of a){const r=n.get(t)??[];0!==r.length&&i.set(e,[...new Set([...i.get(e)??[],...r])].sort((e,t)=>e.localeCompare(t)))}return i}function vm(e){const t={};for(const n of["req_type","relationships","tags","status"])null!=e[n]&&(t[n]=e[n]);return{id:e.id,type:e.type??void 0,title:e.title??void 0,data:t}}async function bm(e,t){return An(()=>e.from("items").select(sm).eq("project_id",t).eq("type","requirement").is("deleted_at",null).not("data->relationships->mitigates","is",null).neq("data->relationships->mitigates","[]"),pn)}function km(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 Am(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 Am(t.data?.relationships?.mitigated_by))r.push({from_id:t.id,to_id:e,type:"mitigated_by"})}const a=wm([...n.values()],r);for(const t of e){const e=a.get(t.id);e&&a.set(t.id,[...new Set([...Am(t.data?.relationships?.mitigated_by).filter(t=>e.includes(t)),...e])])}return a}async function jm(e,t,n,r){return km([n],[...r.map(e=>({id:e.id,type:e.type,req_type:e.data?.req_type,mitigates:e.data?.relationships?.mitigates})),...await bm(e,t)]).get(n.id)??[]}function Sm(e,t,n,r){return(e?.asil!==n||e?.asil_source!==t)&&(r||e?.asil_source===t)}function Am(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function $m(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)}function xm(e,t){return`${e} is not linked to ${t}: neither ${e}'s mitigated_by nor ${t}'s mitigates names the other, so there is nothing to remove and nothing was changed.`}function Im(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 qm(e,t,n){return e.filter(e=>!t.has(e)&&(n.get(e)?.length??0)>0).length}var Om,Em,zm=D({"src/core/coverage-mitigation.ts"(){kr(),pd(),Yu(),sm="id, type, updated_at, content_changed_at, req_type:data->>req_type, mitigates:data->relationships->mitigates",om="id, type, title, req_type:data->req_type, relationships:data->relationships, tags:data->tags, status:data->status",lm=3,dm=0,cm=[],um=["severity","exposure","controllability"],pm="role, control_type and override apply to action add only; omit them to remove a link.",mm="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.",_m="coverage.covered and coverage.percent count a requirement's own linked test cases, and a requirement closed with a document (coverage.covered_by_document). 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."}});async function Mm(e,t){const{data:n,error:r}=await e.rpc("verification_document_closures",{p_project_id:t});if(r)throw r;const a=n??{};return!0!==a.enabled?null:(Array.isArray(a.document_closures)?a.document_closures:[]).map(e=>{const t=e;return{requirement_id:String(t.requirement_id??""),label:String(t.label??""),document_name:String(t.document_name??""),link:"string"==typeof t.link?t.link:null,closed_by:String(t.closed_by??""),closed_at:String(t.closed_at??"")}})}function Rm(e,t,n){if(!n)return e;const r=new Set(n.map(e=>e.requirement_id)),a={verified:0,failing:0,incomplete:0,not_run:0,stale:0,points_total:0,points_run:0};let i=0;for(const e of t){if(!r.has(e.requirement_id))continue;i+=1;const t=!0===e.stale;"verified"!==e.state||t||(a.verified+=1),"failing"===e.state&&(a.failing+=1),"incomplete"!==e.state||t||(a.incomplete+=1),"not-run"===e.state&&(a.not_run+=1),t&&(a.stale+=1),a.points_total+=Number(e.points_total??0)||0,a.points_run+=Number(e.points_run??0)||0}const s={...e};for(const[t,n]of Object.entries(a))n>0&&(s[t]=(Number(e[t]??0)||0)-n);const o=new Set(t.map(e=>e.requirement_id)),l=[...r].filter(e=>!o.has(e)).length;return l>0&&(s.requirements=(Number(e.requirements??0)||0)+l),s.closed_by_document=i+l,s}function Tm(e,t,n){if(!n)return{covered:e.slice(),uncovered:t.slice(),coveredByDocument:null};const r=new Set(n.map(e=>e.requirement_id)),a=t.filter(e=>r.has(e.id)),i=a.map(e=>e.id).sort();return{covered:[...e,...a],uncovered:t.filter(e=>!r.has(e.id)),coveredByDocument:{count:i.length,ids:i}}}var Cm,Dm,Hm=D({"src/core/document-closures.ts"(){Om="covered_by_document is present only while Close with a document is switched on for the project and the report reads the current state (no baseline_id, no as_of): it is { count, ids } for the requirements with no linked test case that an editor or admin closed in the app with a document, which the app reads as covered and done, so they are counted in covered and coverage_percent and left out of uncovered and uncovered_items. A report at a baseline or a past moment reads no closures and keeps the coverage that moment recorded.",Em="coverage.covered_by_document is present only while Close with a document is switched on for the project: it is { count, ids } for the requirements with no linked test case that an editor or admin closed in the app with a document, which the app reads as covered and done, so they are counted in coverage.covered, coverage.percent and coverage_by_domain, and left out of coverage.uncovered and coverage.via_mitigation."}});function Nm(e,t){return t>0?Math.round(e/t*1e3)/10:Cm}var Pm,Fm,Um=D({"src/core/project-summary.ts"(){fm(),Cm=100,Dm="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 Lm(e,t){const n=Fm.find(t=>t.type===e);return n?t?n.lane:n.incoming:void 0}function Wm(e){const t={};for(const n of Fm){const r=e[n.lane]??[];(n.always||r.length>0)&&(t[n.lane]=r)}return t}function Vm(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 Pm){const a=e[n];if(Array.isArray(a))for(const e of a)"string"==typeof e&&i(t.id,e,r)}}return a}var Bm,Jm,Gm,Qm,Km,Ym=D({"src/core/relationship-sync.ts"(){Pm=[["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"],["event_hazard","event_hazard"],["hazard_events","hazard_events"],["event_goal","event_goal"],["goal_events","goal_events"]],Fm=[{lane:"parents",type:"parent",incoming:"children",always:!0},{lane:"children",type:"child",incoming:"parents",always:!0},{lane:"related",type:"related",incoming:"related",always:!0},{lane:"verified_by",type:"verified_by",incoming:"verifies",always:!0},{lane:"verifies",type:"verifies",incoming:"verified_by",always:!0},{lane:"mitigated_by",type:"mitigated_by",incoming:"mitigates",always:!0},{lane:"mitigates",type:"mitigates",incoming:"mitigated_by",always:!0},{lane:"affects",type:"affects",incoming:"affected_by",always:!0},{lane:"affected_by",type:"affected_by",incoming:"affects",always:!0},{lane:"allocated_to",type:"allocated_to",incoming:"allocated_from",always:!1},{lane:"allocated_from",type:"allocated_from",incoming:"allocated_to",always:!1},{lane:"traces_to",type:"traces_to",incoming:"traced_by",always:!1},{lane:"traced_by",type:"traced_by",incoming:"traces_to",always:!1},{lane:"decomposes_to",type:"decomposes_to",incoming:"decomposed_from",always:!1},{lane:"decomposed_from",type:"decomposed_from",incoming:"decomposes_to",always:!1}]}});function Zm(e){const t=e?.trim();return t?`Release ${t}`:Bm}function Xm(e){const t=(e??[]).filter(e=>null!=e.release_version);return t.find(e=>"released"===e.release_status)??t.slice().sort((e,t)=>String(t.snapshot_at??"").localeCompare(String(e.snapshot_at??"")))[0]}async function e_(e,t){try{const{data:n,error:r}=await e.from("baselines").select("id, release_version, release_status, snapshot_at").eq("project_id",t).is("deleted_at",null);if(r)return Jm;const a=Xm(n);return a?{releaseId:a.id,label:Zm(a.release_version)}:Jm}catch{return Jm}}async function t_(e,t,n,r){return En([...new Set(n)],n=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:r,p_requirement_ids:n}))}async function n_(e,t,n){const r=n.filter(e=>"requirement"===e.type).map(e=>e.id),a=n.filter(e=>"test-case"===e.type);if(0===r.length&&0===a.length)return{flags:new Map,scope:null};const i=await e_(e,t),s=new Set(r);if(a.length>0){const n=a.map(e=>e.id),r=[],i=[];for(let s=0;s<n.length;s+=200){const o=n.slice(s,s+200),l=[...await An(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verified_by").in("to_id",o),mn),...await An(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verifies").in("from_id",o),mn)];r.push(...l);const d=new Set(l.map(e=>"verified_by"===e.type?e.from_id:e.to_id));for(const e of a.slice(s,s+200)){const t=e.data?.relationships;for(const e of Gm(t?.verifies))d.add(e)}i.push(...await An(()=>e.rpc("tcm_requirements_for_test_cases",{p_project_id:t,p_test_case_ids:o,p_requirement_ids:[...d]}),pn))}const o=new Set(i.map(e=>e.id)),l=new Set(n),d=Vm([...a,...i.map(e=>({id:e.id,data:{relationships:{verified_by:Gm(e.verified_by)}}}))],r);for(const e of d)"verified_by"===e.type&&o.has(e.from_id)&&l.has(e.to_id)&&s.add(e.from_id),"verifies"===e.type&&l.has(e.from_id)&&o.has(e.to_id)&&s.add(e.to_id)}const o=new Map,l=s.size>0?await t_(e,t,s,i.releaseId):[],d=new Set(l.map(e=>e.requirement_id)),c=function(e){return new Set(e.flatMap(e=>e.test_case_ids??[]))}(l);for(const e of r)o.set(e,d.has(e));for(const e of a)o.set(e.id,c.has(e.id));return{flags:o,scope:i}}function r_(e,t){const n=e?.flags.get(t);return void 0!==n&&e?.scope?{needs_rerun:n,rerun_scope:e.scope.label}:{}}var a_,i_,s_,o_=D({"src/core/rerun.ts"(){kr(),Ym(),Jm={releaseId:null,label:Bm="All runs"},Gm=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],Qm="needs_rerun (requirements and test cases, live reads only): true when a linked test case passed before the requirement's content last changed. The app shows such a test case as Rerun (R) instead of Passed, and the requirement as Rerun unless it is failing: report it as needing a rerun, never as passed. status keeps the verdict of the newest run. "+'Judged as the Matrix judges it: in the project\'s current formal Release when it has one (only runs bound to that Release count), otherwise on every recorded run; rerun_scope names the scope read ("Release 1.1" or "All runs", the label the Matrix prints), so say which runs you judged.'+" atoms_get_item carries rerun_scope beside needs_rerun, atoms_list_items once in meta.rerun_scope.",Km='rerun.requirements counts the requirements with a linked test case that passed before the requirement\'s content last changed (the Matrix reads them Rerun unless failing); rerun.test_cases counts the test cases whose status reads passed but need such a rerun (the app shows R): they are part of test_status.passed, so report them as needing a rerun, not as passed. Judged as the Matrix judges it: in the project\'s current formal Release when it has one (only runs bound to that Release count), otherwise on every recorded run; rerun_scope names the scope read ("Release 1.1" or "All runs", the label the Matrix prints), so say which runs you judged.'}});async function l_(e,t){try{const{data:n,error:r}=await e.rpc("project_function_mode",{p_project_id:t});return r?function(e){return!!e&&("PGRST202"===e.code||"42883"===e.code||/Could not find the function public\.project_function_mode/i.test(String(e.message??"")))}(r)?"tags":"unknown":"items"===n?"items":"tags"===n?"tags":"unknown"}catch{return"unknown"}}function d_(e){const t=["requirement","test-case","note","table"];return"items"===e?[...t,"function"]:t}function c_(e){return"items"===e?null:"unknown"===e?{status:"error",message:s_,next_steps:["Send the same call again in a moment"],code:"function_mode_unreadable",retryable:!0}:{status:"error",message:a_,next_steps:i_,code:"function_items_off",retryable:!1}}var u_,p_,m_,__,f_,h_,g_,y_,w_,v_,b_,k_=D({"src/core/function-mode.ts"(){a_="Function items are not turned on for this project, so a Function cannot be created or allocated to yet. Nothing was written. Ask an ATOMS administrator to convert the project's functions to Function items.",i_=["Until the project is converted its functions stay named by its function tags, which are not domains. Ask an ATOMS administrator to convert the project to Function items","Do not retry: the answer stays the same until an administrator converts the project"],s_="The project's Function setting could not be read just now. Nothing was written. Send the same call again in a moment."}});function j_(e){return(e??"").trim().toLowerCase()}function S_(e){const t=e.analysis_props;return t&&"object"==typeof t?t:{}}function A_(e){return"string"==typeof e?e:""}function $_(e,t,n,r){const a=S_(e),i=A_(a.source_function),s={id:null,title:null,label:i,state:"legacy-text"};if(!t||!u_.has(t))return s;let o=A_(a.source_function_id).trim();if(!o){const e=j_(i);if(!e)return s;const t=(r??[]).find(t=>t.tag_key===e&&!t.reverted_at);if(!t)return s;o=t.item_id}const l=n.get(o),d=!!l&&"function"===l.type&&!l.deleted_at;return{id:o,title:l&&"function"===l.type?l.title??"":null,label:i,state:d?"live":"trashed"}}function x_(e,t,n,r){const a=$_(e,t,n,r);if("live"!==a.state||!a.id)return null;const i=n.get(a.id);return i?.content_changed_at??i?.updated_at??null}function I_(e,t){const n=h_[e]?.[t]??`Create a Function with ${p_}.`;return`${t} was removed in ATOMS MCP ${m_}, with no deprecation period. ${n} Nothing was written.`}function q_(e,t){const n=function(e,t){const n=h_[e];return n&&t&&"object"==typeof t?Object.keys(n).filter(e=>void 0!==t[e]):[]}(e,t);return 0===n.length?null:{status:"error",message:`Validation error: ${n.map(t=>I_(e,t)).join(" ")}`,next_steps:[`Create a Function with ${p_}, then name it by its id, on a project with Function items turned on; a project without them needs an ATOMS administrator to convert it first`,"Do not send the removed input again: it is refused on every project"],code:"input_removed",retryable:!1}}function O_(e){return(t,n)=>{if("unrecognized_keys"===t.code){const n=h_[e]??{},r=(t.keys??[]).filter(e=>e in n);if(r.length>0)return{message:r.map(t=>I_(e,t)).join(" ")}}return{message:n.defaultError}}}function E_(e){const t=[];for(const n of e){const e="string"==typeof n?n.trim():"";e&&!t.includes(e)&&t.push(e)}return t}function z_(e){const t=e.map(e=>`${e.id} (${e.problem})`).join(", ");return{status:"error",message:`Validation error: ${1===e.length?"This id does":"These ids do"} not name a live Function of this project: ${t}. An analysis row names a Function item by its id. Nothing was written.`,next_steps:["Find the project's Functions with atoms_list_items type 'function'",`Or create the Function first with ${p_}`],code:"function_id_invalid",retryable:!1,invalid_function_ids:e.map(e=>e.id)}}function M_(e){return{status:"error",message:'Validation error: a Function id must be a non-blank string such as "FN-001"; an empty or whitespace-only id names no Function. Nothing was written.',next_steps:["Find the project's Functions with atoms_list_items type 'function'","Drop the blank entry from the list"],code:"function_id_invalid",retryable:!1,invalid_function_ids:e.filter(e=>"string"!=typeof e||""===e.trim()).map(e=>"string"==typeof e?e:String(e))}}async function R_(e,t,n){return T_(e,t,n,await l_(e,t))}async function T_(e,t,n,r){const a=c_(r);if(a)return{ok:!1,error:{...a}};if(function(e){return e.some(e=>"string"!=typeof e||""===e.trim())}(n))return{ok:!1,error:M_(n)};const i=E_(n);if(0===i.length)return{ok:!0,functions:[]};const s=await C_(e,t,i),o=[],l=[];for(const e of i){const t=s.get(e);t?"function"!==t.type?o.push({id:e,problem:"not a Function"}):t.deleted_at?o.push({id:e,problem:"in Trash"}):l.push({id:e,title:t.title??""}):o.push({id:e,problem:"no item with this id in this project"})}return o.length>0?{ok:!1,error:z_(o)}:{ok:!0,functions:l}}async function C_(e,t,n){const r=new Map;if(0===n.length)return r;let a;try{a=await En([...new Set(n)],n=>e.from("items").select("id, type, title, deleted_at, content_changed_at, updated_at").eq("project_id",t).in("id",n))}catch(e){throw new Error(`Function read failed: ${e?.message||"unknown error"}`)}for(const e of a)r.set(e.id,e);return r}function D_(e){return e.functionId?{source_function:e.text,source_function_id:e.functionId}:{source_function:e.text}}function H_(e,t){return t.functionId?{id:e,source_function:t.text,source_function_id:t.functionId,source_function_title:t.text}:{id:e,source_function:t.text}}function N_(e){return!!e&&u_.has(e)}async function P_(e,t,n){if(N_(e)){if(!t.includes("source_function"))return null;const r=`source_function was removed in ATOMS MCP ${m_}, with no deprecation period: a ${e} row names its Function by id.`,a=await n();return"items"===a?`${r} Pass source_function_id (find the id with atoms_list_items type 'function', or create the Function with ${p_}). Nothing was written.`:"tags"===a?`${r} This project has no Function items turned on, so source_function_id and creating a Function are refused here. A person sets the row's Function in the row panel of the ATOMS app, or ask an ATOMS administrator to convert the project to Function items. Send the row's other fields again without source_function. Nothing was written.`:`${r} Which step applies depends on whether the project has Function items turned on, which could not be read just now. Send the call again without source_function (the same call is refused on every project). Nothing was written.`}return t.includes(__)?"security_tir57"===e?"A security_tir57 row names an asset as text in source_function, never a Function: source_function_id is refused. Nothing was written.":`source_function_id applies to a HARA or a risk analysis row only; a ${e} row names no Function. Nothing was written.`:null}function F_(e,t=[]){return{status:"error",message:`Validation error: ${e}`,next_steps:t.length>0?[...t]:["Check the parameter types and constraints in the tool description"],code:"validation_error",retryable:!1}}function U_(e){return e?D_(e):{source_function:null}}function L_(e,t,n){return"hara"!==e?{source_req:n??null}:t?{source_function:t.text,source_function_id:t.functionId,source_function_title:t.text}:{source_function:null}}var W_,V_,B_=D({"src/core/functions.ts"(){ai(),k_(),kr(),u_=new Set(["hara_iso26262","hazard_iso14971"]),m_="0.62.0",__="source_function_id",h_={atoms_update_domain:{is_function:`A function is no longer a flagged domain tag: it is an item. Create one with ${p_="atoms_create_item type 'function'"}, on a project with Function items turned on. ${f_="A project without Function items cannot create a Function or name one by id over MCP: ask an ATOMS administrator to convert the project to Function items."}`},atoms_create_analysis:{source_functions:`Seed a HARA or a risk analysis with source_function_ids, the ids of Function items, on a project with Function items turned on (find them with atoms_list_items type 'function', or create one with ${p_}); seed a security risk analysis with source_assets, its asset names. ${f_}`},atoms_propose_rows:{source_function:`Pass source_function_id, the id of a Function item, on a project with Function items turned on (find it with atoms_list_items type 'function', or create one with ${p_}). ${f_}`},atoms_mutate_scenario_catalog:{function_tags:`Pass function_ids, the ids of the Function items the entry applies to, on a project with Function items turned on (find them with atoms_list_items type 'function', or create one with ${p_}). A project without Function items takes function_ids: [] (every function); a person tags an entry by function tag on the Scenario catalogs page of the ATOMS app, or an ATOMS administrator converts the project to Function items.`}},g_="Function items are not turned on for this project, so a catalog entry cannot name a Function by id (function_ids) yet. Nothing was written.",y_=["To apply the entry to every function, send function_ids: [] or leave function_ids out","To tag the entry with one of the project's function tags, a person opens the project's Scenario catalogs page in the ATOMS app and ticks the tag on the entry (MCP tools do not tag by function name)","Or ask an ATOMS administrator to convert the project to Function items, then send the Function ids","Do not retry the same call: the answer stays the same until the project is converted"],w_='Function items are not turned on for this project, so source_function_id "" cannot clear the row\'s Function over MCP: on this project a row names its function by function tag, and MCP tools do not change function tags. Nothing was written.',v_=["To clear the row's Function, a person opens the row panel in the ATOMS app (the row's ID in the analysis grid opens it) and empties the Function field in its Analysis section; the grid's Function cell is read-only",'Or ask an ATOMS administrator to convert the project to Function items, then send source_function_id "" again',"Do not retry the same call: the answer stays the same until the project is converted"],b_=50}});function J_(e){return e?W_.indexOf(e):-1}function G_(e,t){const n=e?.[t];return"string"==typeof n?[n]:Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}function Q_(e){return[...G_(e,"event_hazard"),...G_(e,"event_goal")]}function K_(e){const t=e.analysis_props;return"requirement"===e.type&&!!t&&"object"==typeof t}function Y_(e){return!!e&&!e.deleted_at}function Z_(e,t){const n=e.verified?"verified":"not verified";return 0===e.viaRows.length?`${e.id} ${n}`:`${e.id} ${n} via ${e.viaRows.map(t).join(", ")}`}var X_,ef,tf,nf,rf,af,sf,of,lf,df,cf,uf,pf,mf,_f,ff,hf,gf,yf,wf,vf=D({"src/core/safety-index.ts"(){pd(),zm(),B_(),W_=["QM","A","B","C","D"],V_=new WeakMap}});function bf(e){return"safety_goal"===e?"goal":e}function kf(e){return"hazard"===e||"goal"===e}async function jf(e,t){try{const{data:n,error:r}=await e.from("metadata").select("industry").eq("project_id",t).maybeSingle();if(r)return null;const a=ll(n),i="automotive"===(a??"automotive")&&await $i(e,t,"automotive"),{data:s,error:o}=await e.rpc("rollout_state",{p_project_id:t});if(o||!s||"object"!=typeof s)return null;const l=s;return{industry:a,holdsAnalysisOutsideAutomotive:i,hazardGoalItemsOn:!0===l.hazard_goal_items,multiuserSavingOn:!0===l.multiuser_saving}}catch{return null}}function Sf(e){if(!e)return{status:"error",message:uf,next_steps:["Send the same call again in a moment"],code:"hazard_goal_unreadable",retryable:!0};const t=xi(e);return null===t?null:t===ki?Hs():Cs()}async function Af(e,t){return Sf(await jf(e,t))}function $f(e){const t={},n={};for(const[r,a]of Object.entries(e??{})){const e=mf[r];if(!e){n[r]=a;continue}if("string"!=typeof a)return{picks:{},rest:{},error:`${r} must be the id of a ${"goal"===_f[e]?"Safety goal":"Hazard"} item (or "" to clear it)`};const i=a.trim();t[e]=""===i?null:i}return{picks:t,rest:n,error:null}}function xf(e){return Object.keys(e).length>0}function If(e,t){const n=`${e}: hazard_id and goal_id apply only to the hazardous event rows of a stamped ISO 26262 HARA (one that uses Hazard and Safety goal items)`,r=So[t];return r.includes("hazard")&&r.includes("safety_goal")?`${n}, and this analysis is not one. Write the row's hazard or safety_goal text instead. Nothing was written.`:`${n}. A ${Xo[t].parent} row has no hazard or safety_goal field and cites no Hazard or Safety goal item. Write its own fields with atoms_fill_row (${[...r,"effect"].join(", ")}) and link the requirement that mitigates it with atoms_link_mitigation. Nothing was written.`}function qf(e,t,n){const r=_f[e];if(n&&n.type===r&&(null===n.deleted_at||void 0===n.deleted_at))return null;const a="goal"===r?"Safety goal":"Hazard";return`${hf[e]} ${t} is not a live ${a} item of this project. Create one with atoms_create_item type "${r}", or name an existing one. Nothing was written.`}function Of(e,t,n,r={}){for(const a of["event_hazard","event_goal"]){const i=ff[a];if(!n.includes(i))continue;const s=void 0!==r[a]?r[a]:G_(t,a)[0]??null;if(!s)continue;const o="goal"===_f[a]?"Safety goal":"Hazard";return`${e} names its ${o} as an item (${s}), so its ${i} text is read-only. Pick another ${o} with ${hf[a]}, or change the item itself with atoms_update_item. Nothing was written.`}return null}function Ef(e,t){const n=[];for(const r of["event_hazard","event_goal"]){if(void 0===t[r])continue;const a=G_(e,r),i=t[r];for(const e of a)e!==i&&n.push({kind:"remove",path:["relationships",r],value:e});i&&!a.includes(i)&&n.push({kind:"add",path:["relationships",r],value:i})}return n}async function zf(e,t,n,r,a,i,s,o){if(!xf(i))return null;if(!a)return{kind:"validation",message:If(n,r)};const l=Ef(s,i).filter(e=>"add"===e.kind);if(0===l.length)return null;const d=Sf(await jf(e,t));if(d)return{kind:"tool",error:d};for(const e of l){const t=qf(e.path[1],e.value,await o(e.value));if(t)return{kind:"validation",message:t}}return null}function Mf(e,t){const n={};for(const r of["event_hazard","event_goal"])void 0!==t[r]?n[hf[r]]=t[r]??null:G_(e,r).length>0&&(n[hf[r]]=G_(e,r)[0]);return n}function Rf(e){return e.filter(e=>gf.has(e.trim().toLowerCase().replace(/[\s-]+/g,"_")))}function Tf(e,t){return`${e} is a Safety goal item: its safe state and FTTI are recorded on the hazardous event rows that cite it (atoms_fill_row on each row), never on the goal. ${t.join(", ")} was not saved.`}function Cf(e,t){const n=Xo[e];return"hara_iso26262"===e&&"hazard_goal"===t?{...n,row:yf}:n}function Df(e,t){return"hara_iso26262"===e&&"hazard_goal"===Al(t)}function Hf(e){return/^SG-/.test(e)?`Event ${e}`:e}function Nf(e){return{event_label:yf,display_id:Hf(e)}}function Pf(e){return"requirement"===e.type&&e.data?.req_type===wf}function Ff(e,t){if(!Pf(e)||"analysis"!==t?.type)return!1;const n=t.data??null,r=n?.analysis_props?.variant;return Df(dl("dfmea"===n?.analysis?.subtype?"dfmea":"hara","string"==typeof r?r:null,null),{analysis_props:n?.analysis_props})}function Uf(e,t,n){return"goal"===t||"hazard"===t?`${e} is a ${"goal"===t?"Safety goal item":"Hazard item"}, not a hazardous event row.${"atoms_link_mitigation"===n?" A mitigation links to a Safety goal item (SG-n), or to a hazardous event row, which redirects the link to the row's Safety goal.":""} Change its title or text with atoms_update_item; ${"goal"===t?"its ASIL, safe state and FTTI are recorded on the hazardous event rows that cite it (atoms_fill_row on each row)":"its highest ASIL comes from the hazardous event rows that cite it"}. Nothing was written.`:`Item ${e} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`}function Lf(e){return e.map(e=>{const t=e.data??{};return{id:e.id,type:e.type,title:e.title??null,req_type:t.req_type,analysis_props:t.analysis_props??null,relationships:t.relationships??null,deleted_at:e.deleted_at??null}})}function Wf(e){const t=Lf(e);return function(e,t){const n=V_.get(e);if(n&&n.links===t)return n.index;const r=function(e,t){const n=new Map;for(const t of e)n.set(t.id,t);const r=e=>Y_(n.get(e)),a=e=>r(e)&&"goal"===n.get(e)?.type,i=new Map,s=new Map;for(const t of e){if(!K_(t))continue;const e=G_(t.relationships,"event_goal")[0],r=e?n.get(e):void 0;!e||r&&"goal"!==r.type||i.set(t.id,e);const a=G_(t.relationships,"event_hazard")[0];a&&s.set(t.id,a)}const o=(t,r,a)=>{for(const i of[...e].sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0))if(i.type===t)for(const e of G_(i.relationships,r)){const t=n.get(e);t&&K_(t)&&!a.has(e)&&a.set(e,i.id)}};o("goal","goal_events",i),o("hazard","hazard_events",s);const l=e=>{const t=new Map;for(const[n,a]of e){if(!r(n))continue;let e=t.get(a);e||t.set(a,e=[]),e.push(n)}for(const e of t.values())e.sort();return t},d=l(i),c=l(s),u=e=>Tl(n.get(e)?.analysis_props),p=e=>{let t=-1;for(const n of e)t=Math.max(t,J_(u(n)));return t<0?"QM":W_[t]},m=new Set;for(const t of e)if(Y_(t))if("test-case"===t.type)for(const e of G_(t.relationships,"verifies"))m.add(e);else for(const e of G_(t.relationships,"verified_by")){const r=n.get(e);Y_(r)&&"test-case"===r.type&&m.add(t.id)}const _={get:e=>n.get(e)},f=e=>{const t=new Set;for(const r of e){const e=n.get(r);if(!e)continue;const a=$_(e,"hara_iso26262",_);"live"===a.state&&a.id&&t.add(a.id)}return[...t].sort()},h=t=>e.filter(e=>e.type===t&&Y_(e)).map(e=>e.id).sort(),g=e=>a(e)?[...t.byRow.get(e)??[]].filter(r).sort():[];return{goalOf:e=>i.get(e)??null,hazardOf:e=>s.get(e)??null,rowsOfGoal:e=>d.get(e)??[],rowsOfHazard:e=>c.get(e)??[],goalAsil:e=>p(d.get(e)??[]),hazardAsil:e=>{const t=c.get(e)??[];return{level:p(t),count:t.length}},satisfiers:g,goalCoverage:(e,n)=>{const i=g(e),s=a(e)?d.get(e)??[]:[],o=n?s.filter(e=>n.includes(e)):s,l=new Set(i),c=new Set,p=[],_=[];for(const e of o){const n=(t.byRow.get(e)??[]).filter(r);for(const e of n)l.has(e)||c.add(e);J_(u(e))<=0||(0===i.length&&0===n.length?p.push(e):[...n,...i].some(e=>m.has(e))||_.push(e))}return{satisfiers:i,rowMitigators:[...c].sort(),uncoveredRows:p,untestedRows:_}},goalVerification:e=>{const n=g(e),i=new Set(n),s=new Map;for(const n of a(e)?d.get(e)??[]:[])for(const e of t.byRow.get(n)??[]){if(!r(e)||i.has(e))continue;let t=s.get(e);t||s.set(e,t=new Set),t.add(n)}const o=[...n,...s.keys()].sort((e,t)=>e<t?-1:e>t?1:0).map(e=>({id:e,verified:m.has(e),viaRows:[...s.get(e)??[]].sort()}));return{requirements:o,verified:o.filter(e=>e.verified).length,total:o.length}},directMitigators:e=>[...t.byRow.get(e)??[]],rowMitigated:e=>{if((t.byRow.get(e)??[]).length>0)return!0;const n=i.get(e);return!!n&&g(n).length>0},requirementVerified:e=>m.has(e),hazardFunctions:e=>f(c.get(e)??[]),goalFunctions:e=>f(d.get(e)??[]),hazardGoals:e=>[...new Set((c.get(e)??[]).map(e=>i.get(e)).filter(e=>!!e&&a(e)))].sort(),hazardIds:h("hazard"),goalIds:h("goal"),isLiveId:r}}(e,t);return V_.set(e,{links:t,index:r}),r}(t,function(e){const t=[],n=[];for(const r of e)if(Y_(r)){t.push({id:r.id,type:r.type,data:{req_type:r.req_type,analysis_props:r.analysis_props}});for(const e of G_(r.relationships,"mitigated_by"))n.push({from_id:r.id,to_id:e,type:"mitigated_by"});for(const e of G_(r.relationships,"mitigates"))n.push({from_id:r.id,to_id:e,type:"mitigates"})}return{byRow:ym(t,n)}}(t))}async function Vf(e,t){return await An(()=>e.from("items").select("id, title, type, data").eq("project_id",t).is("deleted_at",null),pn)}async function Bf(e,t,n,r){const a=G_(n,"event_goal")[0];if(!a)return[];const i=await r(a);if(!i||"goal"!==i.type)return[];const s=[];for(const e of G_(i.data?.relationships,"mitigated_by")){const t=await r(e);t&&s.push(t)}const o=await bm(e,t),l=[{id:i.id,type:i.type,data:{}}],d=[];for(const e of s)l.push({id:e.id,type:e.type,data:{req_type:e.data?.req_type}}),d.push({from_id:i.id,to_id:e.id,type:"mitigated_by"});const c=new Set(l.map(e=>e.id));for(const e of o){c.has(e.id)||(c.add(e.id),l.push({id:e.id,type:e.type,data:{req_type:e.req_type}}));for(const t of G_({mitigates:e.mitigates},"mitigates"))d.push({from_id:e.id,to_id:t,type:"mitigates"})}const u=[];for(const e of ym(l,d).get(i.id)??[]){const t=s.find(t=>t.id===e)??await r(e);t?.data?.asil_source===a&&u.push(e)}return u}var Jf,Gf,Qf,Kf,Yf,Zf,Xf,eh,th,nh=D({"src/core/hazard-goal-tools.ts"(){Yi(),pd(),ol(),Js(),vf(),kr(),zm(),ef=["requirement","test-case","note","function","hazard","goal","safety_goal"],tf=`Item type. function only where Function items are on. ${X_="hazard and goal: ISO 26262 (automotive) projects only; in a medical device project hazards are rows of the ISO 14971 risk analysis"}; a Standard project takes neither. safety_goal is another name for goal (a Safety goal item, SG-n); a hazard is HAZ-n.`,nf="ISO 26262 HARA only, where Hazard and Safety goal items are on (automotive only): the Hazard item (HAZ-n) every new row cites. Refused on any other analysis.",rf="ISO 26262 HARA only, where Hazard and Safety goal items are on (automotive only): the Safety goal item (SG-n) every new row cites. Refused on any other analysis.",af='Hazard and Safety goal items (ISO 26262, automotive only, where they are on): a HARA created there is stamped (event_model hazard_goal) and its rows are hazardous events with HE-n ids. On such a row, hazard_id and goal_id name its Hazard item (HAZ-n) and its Safety goal item (SG-n), one each ("" clears it); the row\'s hazard and safety_goal text is then read-only. A write that changes either on an approved row clears the approval and answers approval_cleared: true. hazard_id and goal_id are refused on any other row: an unstamped HARA, an ISO 14971 risk analysis (it keeps its hazardous situations as row text) and a security risk analysis keep a hazard and a safety_goal text, and a DFMEA, PFMEA, Software FMEA or Use FMEA row has neither field.',sf='On a stamped HARA (event_model hazard_goal) each row also carries hazard_id, goal_id and goal_asil (the highest event ASIL over the live rows citing the goal), goal_display, event_label ("Hazardous event") and display_id ("Event SG-n" for a row that kept its SG id). A row rated ASIL A to D is a gap (is_gap true, and is_critical true at C or D) when no requirement covers it: none is linked to the row itself and none satisfies its live Safety goal; gap_rule then names the goal. A covered row is not a gap, whether or not a test case verifies its requirements (atoms_get_gaps reports a covered untested row under its goal). A row with no live goal (no goal, or its goal in Trash) is covered only by a requirement linked to it. counts.gaps is the number of rows whose own gap rule matched (is_gap true, the rows atoms_get_gaps lists in gaps) and counts.critical the critical ones; it is not the number of gap lines, so a Safety goal with 3 uncovered rows adds 3 to counts.gaps and 1 to the count of atoms_get_gaps. atoms_get_analysis returns no gap_kinds list: it returns gap_rule per row and, in acceptance.open_gaps_at_acceptance, the kinds that were open when the analysis was accepted; for the gap kinds open now and their total call atoms_get_gaps.',of="On a stamped HARA (event_model hazard_goal) the gap kinds are row_no_goal, goal_no_safety_req, goal_no_test, hazard_uncited and goal_trashed (the last two informational, not counted), beside the HARA's own no_parent, catalog_draft and not_accepted. A goal is judged row by row over the analysis's rows rated ASIL A to D that cite it: a row is covered by a requirement satisfying the goal or one linked to the row itself, and tested when one of those is verified by a test case. goal_no_safety_req lists the uncovered rows and goal_no_test the covered untested ones; a goal with both raises both, 1 gap each. A row with no live goal (no goal, or its goal in Trash) stands as its own goal: row_no_goal when no requirement is linked to it, goal_no_test when none of those is verified; a row whose goal is in Trash is also listed under goal_trashed. A row's own test case never counts on a stamped HARA. On a stamped HARA, count is the sum of the gap_count of the counted kinds, so it is neither a row count nor a goal count: row_no_goal counts rows, goal_no_safety_req and goal_no_test count goals, once per goal per kind (a goal with both uncovered and covered untested rows counts once in each, and each kind names the rows that raise it, so 3 rows citing 1 goal are 1), goal_no_test also counts each row with no live goal that is linked to requirements none of which is verified, no_parent counts requirements, and catalog_draft and not_accepted count 1 each and name nothing. gaps lists only the rows whose own gap rule matched, so count can differ from gaps.length, and counts.gaps of atoms_get_analysis is that row number, not count. A gaps entry carries no hazard_id or goal_id: read them with atoms_get_analysis.",lf="row_id may name a Safety goal item (SG-n, where Hazard and Safety goal items are on): the safety requirement then satisfies the goal and takes its ASIL (asil and asil_source in the answer). A link added to a hazardous event row that cites a live Safety goal goes to that goal (redirected_from names the row). A hazardous situation row of an ISO 14971 risk analysis links as before.",df='A Hazard item (HAZ-n) also carries safety: { highest_asil, event_count, events, functions, goals } and a Safety goal item (SG-n) safety: { asil, source_rows, events, functions, satisfied_by, verified_satisfiers, row_mitigators, uncovered_rows, untested_rows }, derived from the hazardous event rows that cite it. satisfied_by and verified_satisfiers are the goal\'s own links; row_mitigators are the requirements linked to its rows directly. uncovered_rows are the rows rated ASIL A to D that neither a requirement satisfying the goal nor one linked to the row covers (goal_no_safety_req); untested_rows are the covered ones with none of those requirements verified by a test case (goal_no_test, raised beside goal_no_safety_req when the goal also has uncovered rows). A row\'s own test case is not a test of its goal. verification: { verified, total, requirements } is the goal\'s verification rollup: every live requirement linked to the goal or to a live row citing it, each once, verified when a live test case verifies it; each entry is { id, verified, via_rows, text }, via_rows naming the rows it was counted through (empty for a requirement linked to the goal itself) and text saying so ("REQ-020 verified via Event SG-001"). satisfied_by and verified_satisfiers keep counting the goal\'s own links. A hazardous event row of a stamped HARA (a requirement, req_type safety-goal) also carries event_label ("Hazardous event") and display_id ("Event SG-n" for a row that kept its SG id), so it is not read as the Safety goal item with the same id.',cf=["requirement","test-case","note","table","analysis","function","hazard","goal"],uf="Could not read whether this project takes Hazard and Safety goal items, so nothing was written. Send the same call again in a moment.",pf=["event_hazard","hazard_events","event_goal","goal_events"],mf={hazard_id:"event_hazard",goal_id:"event_goal"},_f={event_hazard:"hazard",event_goal:"goal"},ff={event_hazard:"hazard",event_goal:"safety_goal"},hf={event_hazard:"hazard_id",event_goal:"goal_id"},gf=new Set(["safe_state","ftti"]),yf="Hazardous event",wf="safety-goal"}});function rh(e){if(e.title)return e.title;const t=e.data??{},n=t.req_type;if("requirement"!==e.type||"safety-goal"!==n&&"failure-mode"!==n)return e.title??"";const r=t.analysis_props??{};return["safety-goal"===n?r.source_function:r.source_req,r.failure_mode].filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim()).join(", ")||e.id}function ah(e,t){return"mitigated_by"===e.type&&"goal"===t(e.from_id)||"mitigates"===e.type&&"goal"===t(e.to_id)?{...e,from_id:e.to_id,to_id:e.from_id}:e}function ih(e,t){const n=ro(e.data);return Ff(e,n?t.get(n):void 0)?Nf(e.id):{}}function sh(e){return Math.min(Math.max(e??5,1),10)}var oh,lh,dh,ch,uh,ph,mh,_h=D({"src/core/trace-graph.ts"(){ol(),Ud(),nh(),Jf=new Set(["parent","verifies","mitigated_by","allocated_to","event_hazard","goal_events"]),Gf=new Set(["child","verified_by","mitigates","allocated_from","hazard_events","event_goal"]),Qf=["allocated_to","allocated_from"],Kf={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",allocated_to:"allocated_from",allocated_from:"allocated_to",event_hazard:"hazard_events",hazard_events:"event_hazard",event_goal:"goal_events",goal_events:"event_goal",related:"related"},Yf=["parent","verifies","mitigated_by","traces_to","allocated_to","decomposed_from","event_hazard","goal_events"],Zf=["child","verified_by","mitigates","allocated_from","decomposes_to","traced_by","hazard_events","event_goal"],Xf={...Kf,traces_to:"traced_by",traced_by:"traces_to",allocated_to:"allocated_from",allocated_from:"allocated_to",decomposes_to:"decomposed_from",decomposed_from:"decomposes_to",event_hazard:"hazard_events",hazard_events:"event_hazard",event_goal:"goal_events",goal_events:"event_goal"},eh="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_to and decomposed_from upstream, traced_by, allocated_from and decomposes_to downstream, so a Function is upstream of the requirements allocated to it. The Hazard and Safety goal lanes of an ISO 26262 project are followed too: event_hazard and goal_events upstream, hazard_events and event_goal downstream (a Hazard leads to its hazardous events, an event to its Safety goal), and the safety requirements that satisfy a Safety goal are downstream of it. 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.",th="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. allocated_to and allocated_from links (a requirement and its Function) are followed only when relationship_types names them: a requirement's Function is upstream of it. The Hazard and Safety goal lanes are followed by default: a hazardous event's Hazard is upstream of it (event_hazard), its Safety goal downstream (event_goal), and the safety requirements that satisfy a Safety goal are downstream of the goal. A node that is a hazardous event row of a stamped HARA also carries event_label (\"Hazardous event\") and display_id (\"Event SG-n\" for a row that kept its SG id), so it is not read as the Safety goal item with the same id. affects and affected_by links are not followed yet, so a relationship_types filter of only those returns just the starting item."}});function fh(e){return"string"!=typeof e||""===e.trim()||lh.has(e)?null:e}function hh(e){return!e||"object"!=typeof e||Array.isArray(e)?null:fh(e.reason)}function gh(e){return"string"==typeof e&&""!==e.trim()?e:null}function yh(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}function wh(e){return e.diff_summary&&"object"==typeof e.diff_summary?e.diff_summary:{}}function vh(e,t){const n=wh(e).author;if(n&&"object"==typeof n){const{kind:e,client:t}=n;if("agent"===e){const e="string"==typeof t?t.trim().toLowerCase():"";return["claude","cursor","copilot"].includes(e)?`mcp_${e}`:"mcp_claude"}if("person"===e)return"user"}if("mcp"===e.event_source||"restore"===e.event_source&&e.event_session_id){const n=e.event_session_id?t?.get(e.event_session_id):void 0;return n&&mh.has(n)?n:"mcp_claude"}return"user"}function bh(e,t,n){return e.flatMap((r,a)=>{const i=e[a+1]??null,s=1===r.revision_number||null===i,o="system"===r.event_source?"system_normalization":1===r.revision_number?"created":"updated",l=s?["(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}(yh(i?.fields_snapshot),yh(r.fields_snapshot)),d=function(e){const t=function(e){if(!e||"object"!=typeof e)return null;const t=e.migration;return t&&"object"==typeof t&&!Array.isArray(t)?t:null}(e);if(!t)return null;const n=gh(t.from_tag),r=gh(t.function_id);return"function_items"===t.kind&&n?`Created from function tag "${n}"`:"function_items_link"===t.kind&&r?`Function linked to ${r} by conversion`:"function_items_unlink"===t.kind&&r?`Function link to ${r} removed by revert`:"hazard_goal_model"===t.kind?ch:"hazard_goal_model_revert"===t.kind?uh:gh(e.history)??dh}(r.diff_summary),c=hh(r.diff_summary)??n?.get(r.id)??null,u={id:r.id,event_type:o,changed_by:null===d?r.changed_by??null:null,changed_at:r.valid_from,actor:null!==d?"system":vh(r,t),session_id:r.event_session_id??null,fields_changed:l,...null!==d?{summary:d}:{},...null!==c?{reason:c}:{}},p=function(e){const t=wh(e),n=function(e){return Array.isArray(e.ops)?e.ops.flatMap(e=>{if(!e||"object"!=typeof e)return[];const{kind:t,status:n}=e;return"string"!=typeof t||void 0!==n&&"applied"!==n&&"replaced"!==n?[]:[t]}):null}(t);return{trashed:"trashed"===t.lifecycle||(n?.includes("trash_item")??!1),restored:"restored"===t.lifecycle||(n?.includes("restore_item")??!1)||null===n&&!0===t.restored&&void 0===t.baseline_id,otherOps:null===n?null:n.some(e=>!ph.has(e))}}(r);if(null!==d||!p.trashed&&!p.restored)return[u];const m=1===r.revision_number||(p.otherOps??(null!==i&&l.length>0)),_=(e,t)=>({...u,id:`${r.id}:${e}`,event_type:e,changed_at:t,fields_changed:[`(${e})`]});return[...p.trashed?[_("deleted",r.valid_to??r.valid_from)]:[],...m?[u]:[],...p.restored?[_("restored",r.valid_from)]:[]]})}function kh(e,t,n,r=0){const a=n>t;return{total_count:n>0?Math.max(e,r+Math.min(n,t)):e,limit:t,offset:r,has_more:a,...a?{next_offset:r+t}:{}}}var jh,Sh,Ah=D({"src/core/history.ts"(){oh="Change rationale, shown with the change in atoms_get_history and on its History line in the app",lh=new Set(["item_deleted","endpoint_deleted","endpoint_restored","endpoint_removed_by_change"]),dh="Changed by a data migration run",ch="Moved to the Hazard and Safety goal model by conversion",uh="Moved back from the Hazard and Safety goal model by revert",ph=new Set(["trash_item","restore_item"]),mh=new Set(["mcp_claude","mcp_cursor","mcp_copilot"])}});function $h(e){return`Paging: offset (integer, optional, default 0) and limit (integer, optional, 1 to 1000, default 1000) page ${e}; meta carries total_count, offset, has_more and, when more remain, next_offset. Call again with offset=next_offset until has_more is false to read every entry; a page the 25,000-character cap cuts says so the same way.`}var xh=D({"src/core/tool-descriptions.ts"(){fm(),zm(),Hm(),Um(),o_(),_h(),Ah(),B(),zs(),nh(),jh="Paging: meta carries next_offset while more remain. Call again with offset=next_offset (not offset + limit) until has_more is false: a page the 25,000-character cap cuts holds fewer rows than limit, and its next_offset starts right after the last row it returned.",Sh={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"|"viewer_only", 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 required.\n\nReturns:\n { status: "success", data: [{ id, name, description, org_id, org_name, created_at }], meta }\n\n${$h("the project list (newest first)")}\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|analysis|function\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, needs_rerun? }], meta: { total_count, limit, offset, has_more, next_cursor?, next_offset? } }\n next_offset (on an offset page while more remain) is the offset of the next page; next_cursor pages by after.\n\n${Qm}\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. meta.relationship_counts says how many ids each\n non-empty lane of relationships holds. An item with thousands of links answers a text preview (meta.truncated true):\n the lanes are still counted there, and atoms_trace (depth 1, paged by next_offset) or atoms_impact_analysis reads them.\n\n${Qm}\n\n${Ep}\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. ${j}\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")\n\n${df}`,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 },\n covered_by_document?: { count, ids }, uncovered_items: [...] }, meta\n The counts are the whole project's (or filter's); uncovered_items is one page.\n\n${$h("uncovered_items")}\n\n${mm}\n\n${Om}\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, or a model design's MD id (MD-001) for that design's history\n - limit (number, optional): Max entries (default 20, max 100)\n - offset (number, optional): How many revisions to skip from the newest (default 0)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed, newest first;\n meta { total_count, limit, offset, has_more, next_offset? }. offset and next_offset count revisions: a revision\n that moved the item to Trash or restored it gives more than one entry, and a page never splits one.\n For an MD id: entries newest first with changed_by_name, version, source (web or mcp), agent_label,\n summary (what changed: boxes, arrows and groups added, removed or renamed, links added or removed, the name,\n the description, editors, Trash) and summary_line, the sentence the app's History shows.\n\n${jh}`,atoms_export_mermaid:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Every edge is labelled with what it is\n(parent of, verified by, mitigates, cites hazard, cites goal, allocated to, related to).\nA solid edge is a link the project expects; a dotted edge adds context.\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, note or Function 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|function. atoms_create_item type 'function' creates a Function item (FN-nnn), the function a HARA or risk analysis row names by its id, in a project with Function items turned on; it takes no req_type (REQ-MCS-425) hazard|goal|safety_goal: ${X_}. safety_goal is the same as goal (a Safety goal item, SG-n); a hazard is HAZ-n\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 function tag 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} ${q}`,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 function tag is not a domain and is rejected), level?, status?, req_type?, fields?, steps?, params?, expected_updated_at?\n - ${Tp}\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). ${Op}\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): ${oh}\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?: the same rationale for every item 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: ${j}\nidempotency_key: ${S}\n${q}`,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|function (a Function only in a project with Function items turned on; its parent_id must be a Function); hazard|goal|safety_goal: ${X_}\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 function tag 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 An item takes only these fields: any other, such as runs, is refused by name and nothing is written.\n\nReturns:\n { created: number, items: [{ id, title, type }], errors: [], link_warnings?: [{ child_id, parent_id, message }], warning? }\n items names every created item, in input order (REQ-MCS-670); when the answer is large, title is left out of\n each entry (it is the title you sent) and only errors may be shortened. link_warnings names each created item\n not yet listed under its parent_id (another writer held the link): relink it with atoms_link_items, do not\n import it again. An import whose every row names a parent locked for agents creates nothing and is an error.\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} ${q}`,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. A release_note\n when no release_id was sent: ${vp}\n\n${Sp}\n\n${Ap}\n\n${jp}\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. A release_note (with no_release_entries) when any entry\n carried no release_id: that run counts toward no Release.\n\n${Sp}\n\n${Ap}\n\n${jp}\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${th}\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], edges, total_count }, meta\n total_count counts the whole trace; items is one page (root first) and edges holds the links whose two ends are the\n root or an item of the page.\n\n${$h("items")}\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, next_offset? }\n\n${jh}`,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, already_referenced_by_items, warning? }\nReturns (array): { batch_id, created, variables, message, already_referenced_by_items, warning? }\nalready_referenced_by_items counts the live items whose body already cites the new name: they now read its value,\nand warning says so. Tell the user before relying on it.',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\nOnly an org admin of the project\'s organization can create a field definition.\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|function); 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, rerun: { requirements, test_cases }, recent_changes, last_updated }\n\n${Km}\n\n${_m}\n\n${Em}\n\n${Dm}\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, analysis, function)\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, next_offset? } }\n\n${jh}\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, default true): also list the items that share a {variable} with the item (no relationship needed), each with shared_variables naming every variable it shares.\n\n${eh}\n\nReturns:\n { root: { item_id, title, type }, impacted_items: [{ item_id, title, type, depth, relationship_path, shared_variables }], summary: { total_impacted, by_type, max_depth_reached } }\n shared_variables is the sorted names of the variables the item shares with the root: an empty list when it shares none or include_variable_refs is false.\n summary counts the whole impact set; impacted_items is one page.\n\n${$h("impacted_items")}\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)\n\nReturns:\n { baselines: [...], total, offset, limit }, meta: { total_count, limit, offset, has_more, next_offset? }\n\n${jh}`,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\nWhen your organization requires confirmation for this tool, the preview also returns\n{ status: \"confirmation_required\", confirmation_token }, and confirm=true executes only\nwith that confirmation_token; without it confirm=true returns the preview again.\n\nArgs:\n - baseline_id (string, UUID)\n - confirm (boolean, optional, default false)\n - confirmation_token (string, optional): Token from the preview, when confirmation is required\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 naming the Function items it applies to by id (function_ids; a Function is created\nwith atoms_create_item type 'function'), or, for an entry written before the project turned Function\nitems on, the function tags it applies to (function_tags).\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, function_ids?}], acceptance }],\n meta: { total_count, limit, offset, has_more, next_offset? } }\n\n${jh}`,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_ids (string[]): the ids of the Function items this entry applies to (e.g. \"FN-001\"),\n each a live Function of this project (add_entry, edit_entry, tag_entry). [] means the entry\n applies to every function and is accepted on any project: with Function items turned on it\n stores function_ids [] and clears any function tags the entry still holds from before the\n conversion; without them it stores the entry untagged (function_tags []), as the app does,\n and writes no Function id. A list that names ids leaves those old tags as they are (the ids\n decide). A list that names ids needs Function items turned on: a project\n without them refuses it (function_items_off); a person tags such an entry by function tag on\n the app's Scenario catalogs page. A Function is created with\n atoms_create_item type 'function'. function_tags, the name input, was removed in 0.62.0; an\n entry written before keeps the function_tags it holds.\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. rename_catalog does not; tag_entry does when it changes the entry's\n function_ids.",atoms_list_domains:"List the domain tags of a project's taxonomy, with item counts.\n\nA function tag (metadata.function_tags: the function names of a project that has not turned Function\nitems on, kept unchanged once it has) is not a domain: it is left out of this list, exactly as the\napp's domain picker leaves it out, because atoms_create_item, atoms_update_item and atoms_bulk_import\nrefuse it as a domain. A function is an item: list them with atoms_list_items type 'function' and\ncreate one with atoms_create_item type 'function', in a project with Function items turned on.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { domains: [{ name, registered, item_count }], total, registered_count, unregistered_count, note? }\n registered: false marks a tag found on items but not in the taxonomy (an orphan); a function tag\n an item still carries is never counted as an orphan.",atoms_create_domain:'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 tag is refused (a function is not a domain tag). A function is an\nitem: create one with atoms_create_item type \'function\', in a project with Function items turned on.\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 }',atoms_update_domain:'Rename a domain tag.\n\nUpdates 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\nA domain never becomes a function: a function is an item, created with atoms_create_item type \'function\' in a project with Function items turned on.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Current domain name\n - new_name (string): New domain name\n - dry_run (bool, optional): If true, return the impact without making changes (default false)\n\nReturns (dry_run=false):\n { domain: { name }, renamed_from, items_updated, message }\n\nReturns (dry_run=true):\n { dry_run: true, rename: { from, to }, items_affected, message }',atoms_delete_domain:"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 }",atoms_create_analysis:`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 or a risk analysis is seeded from FUNCTIONS, never from requirements: a requirement is an\noutput of the analysis. A Function is an item: atoms_create_item type 'function' creates one, in a\nproject with Function items turned on, and its id seeds a row (source_function_ids). A security\nrisk analysis is seeded from its asset names (source_assets), which stay text. A dfmea (DFMEA or\nFMEA) is seeded from requirements / 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);\n Standard offers no analyses, so every analysis is refused there. 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, and so is a Standard one.\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_function_ids (string[], HARA or risk analysis only, max 50): the ids of the Function items\n to seed rows from (e.g. "FN-001"), one row each. Each must be a live Function of this project\n (atoms_list_items type 'function'); a project without Function items turned on refuses them\n (function_items_off). Each row stores the id and the Function's title as its label. Nothing is\n written to the project's tags. Rejected for dfmea and for a security risk analysis.\n - source_assets (string[], security risk analysis only, max 50): the asset names to seed rows\n from, kept as text on each row (an asset is never a Function). Rejected for every other scheme.\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, source_function_id?, source_function_title? }] (hara) | [{ id, source_req }] (dfmea),\n link_warnings?: [{ row_id, source_function | source_req, message }], warning? }\n A row seeded from a Function carries its id and title; a row seeded from an asset its name.\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 - Writes nothing to the project's tags or function tags (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\n${af}`,atoms_fill_row:`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,\nsecurity_control (the names the app's columns carry; they write the same fields as failure_mode,\noperating_scenario, effect, hazard and safety_goal, which are accepted too, and sending both names of\none field in one call is refused),\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, rationale and title. It\nrefuses p1, p2, occurrence and detection by name (those belong to the other schemes).\n\nA medical risk analysis row (RSK-n) accepts harm, hazardous_situation, sequence_of_events (the\nnames its columns carry; they write the same fields as hazard, effect and operating_scenario, which\nare accepted too, and sending both names of one field in one call is refused). Note that the stored\nkey hazard is the Harm column: the hazard itself is failure_mode.\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_id, 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_id,\n safety_goal (the risk control statement), s_rationale, p1_rationale, p2_rationale,\n residual_s, residual_p1, residual_p2, benefit_note, effect, title\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 and medical risk analysis source_function_id: the id of the Function item the row analyzes\n (e.g. "FN-001"), a live Function of this project (atoms_list_items type 'function'; create one\n with atoms_create_item type 'function'). The row stores the id and the Function's title as its\n label. "" clears both (the row's Function) only on a project with Function items turned on.\n A project without them refuses an id and "" alike (function_items_off): there a row names its\n function by function tag, which MCP does not change, so a person clears it in the row panel's\n Function field in the ATOMS app. source_function, the name input, was removed in 0.62.0 and is\n refused on these rows; a security risk analysis row keeps source_function as its asset name (text).\n\nReturns:\n { row_id, subtype, written_fields, written_columns, computed_level, asil_propagated_to?, asil_propagation_failed?,\n approval_cleared?, source_function_id?, source_function_title? }\n written_columns pairs each written stored key with the column it filled ([{ key, label }], e.g.\n { key: "hazard", label: "Harm" } on a medical risk analysis row).\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 asil_propagation_failed names the requirements whose ASIL did not update although the row was\n saved (with a warning); repeat the same call to push the ASIL again.\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\n${af}`,atoms_get_analysis:`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 source_function_id?, source_function_title? (a HARA or risk analysis row that names a\n Function item: its id, and that Function's title while it is live, else null) }],\n counts: { rows, gaps, critical, stale, approved, linked } }, meta\n The vocabulary lists are given once per analysis, never repeated per row. counts are the whole analysis's;\n rows is one page.\n\n${$h("rows")}\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.\n\n${sf}`,atoms_propose_rows:`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_id (string, HARA or risk analysis only): the id of the Function item these rows\n analyse (e.g. "FN-001"), a live Function of this project (create one with atoms_create_item\n type 'function'); each row stores the id and the Function's title as its label. A project\n without Function items turned on refuses it (function_items_off). A security risk analysis\n row names its asset in its own source_function key.\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 medical risk analysis row also takes harm, hazardous_situation,\n sequence_of_events for hazard, effect and operating_scenario). 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 source_function_id?, source_function_title?,\n rows: [{ id, written_fields, written_columns, 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\n${af}`,atoms_suggest_field:"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, so on a\n medical risk analysis row also harm, hazardous_situation, sequence_of_events)\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, written_columns, source_function_id?, source_function_title?,\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 - A HARA or risk analysis row takes its Function by id: field source_function_id, as\n atoms_fill_row takes it (create a Function with atoms_create_item type 'function'). \"\" clears\n the row's Function only on a project with Function items turned on; a project without them\n refuses it (function_items_off), and a person clears it in the row panel's Function field in\n the ATOMS app. The field source_function, removed in 0.62.0, is refused on these rows.",atoms_link_mitigation:`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), asil_not_written? / control_type_not_written? and warning? (the link is\n saved but that write after it was refused because another write was on the item: call this\n tool again with the same arguments to finish) }\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\n\n${lf}`,atoms_get_gaps:`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 differ from gaps.length either way, which lists only the per-row gap rules (greater when a kind counts what no row rule lists, smaller when one goal line names several gap rows).\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 security: unmitigated, unassessed, not_verified, no_residual, no_justification, safety_no_hazard,\n safety_no_reason, no_parent, no_scope (no threat model method), no_overall (every row is\n controlled and residual-rated but the overall residual risk is not judged) and not_accepted\n (the analysis holds rows and is still a draft)\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 Functions (a HARA or medical risk analysis on a project in Function items mode only):\n function_not_analysed (each live Function no row names, in function_ids; gap_count is\n how many) and function_missing (rows naming a Function that is in Trash or gone)\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.\nA row of a stamped HARA that cites a live Safety goal is also covered by a requirement that\nsatisfies the goal. One rated ASIL A to D that neither covers is in the gaps list (its rule naming\nthe goal; atoms_get_analysis reads it is_critical at C or D) and is named by its goal's\ngoal_no_safety_req; a covered row whose\nrequirements no test case verifies is not in the gaps list (goal_no_test names it). So the gaps\nlist, is_gap, is_critical, counts and gap_kinds agree with the app row by row.\n\n${of}`,...fs}}});async function Ih(e,t,n){const{data:r,error:a}=await e.rpc("verification_accepted_failures",{p_project_id:t,p_release_id:n});if(a)throw a;const i=r??{};return!0!==i.enabled?null:(Array.isArray(i.accepted_failures)?i.accepted_failures:[]).map(e=>{const t=e;return{test_case_id:String(t.test_case_id??""),requirement_ids:Array.isArray(t.requirement_ids)?t.requirement_ids.map(String):[],label:String(t.label??""),reason:String(t.reason??""),link:"string"==typeof t.link?t.link:null,accepted_by:String(t.accepted_by??""),accepted_at:String(t.accepted_at??"")}})}function qh(e,t){const n=new Set(t.acceptedTestIds),r=t.testsOf.get(e)??[];if(!r.some(e=>n.has(e)))return null;const a=r.filter(e=>!n.has(e));if(0===a.length)return{state:"accepted",stale:!1};const i=new Map(t.states.map(e=>[e.tc_id,e]));let s=0,o=0,l=0,d=0;for(const e of a){const t=i.get(e);t&&(s+=Number(t.leaves)||0,o+=Number(t.passed)||0,l+=Number(t.failed)||0,d+=Number(t.blocked)||0)}const c=l+d>0?"failing":0===o?"not-run":o===s?"verified":"incomplete",u=new Set(t.rerunOf.get(e)??[]),p=("verified"===c||"incomplete"===c)&&a.some(e=>u.has(e));return"verified"!==c||p?{state:c,stale:p}:{state:"accepted",stale:!1}}function Oh(e,t){const n=[];return"accepted"===e?["accepted"]:("verified"!==e||t||n.push("verified"),"failing"===e&&n.push("failing"),"incomplete"!==e||t||n.push("incomplete"),"not-run"===e&&n.push("not_run"),t&&n.push("stale"),n)}function Eh(e,t,n,r=new Set){if(!n)return e;const a={verified:0,failing:0,incomplete:0,not_run:0,stale:0,accepted:0};for(const e of t){if(r.has(e.requirement_id))continue;const t=qh(e.requirement_id,n);if(t){for(const t of Oh(e.state,!0===e.stale))a[t]-=1;for(const e of Oh(t.state,t.stale))a[e]+=1}}const i={...e};for(const[t,n]of Object.entries(a))"accepted"!==t&&0!==n&&(i[t]=(Number(e[t]??0)||0)+n);return i.accepted=a.accepted,i}var zh,Mh,Rh,Th,Ch=D({"src/core/accepted-failures.ts"(){}});function Dh(e){const t=e.source_item_id??"";switch(e.kind){case"parent_changed":return t?`Parent ${t} changed`:"Parent changed";case"hazard_changed":return t?`Hazard ${t} changed`:"Hazard changed";case"interface_changed":return t?`Interface ${t} changed`:"Interface changed";case"asil_raised":return t?`Hazard ${t} ASIL raised`:"ASIL raised";case"reparented":return"Parent link changed"}}function Hh(e,t){const n=t?` in Release ${t}`:"";if(e.failed>0)return t?{id:e.id,action:"failed",reason:`Failed in Release ${e.failedFrom??t}`}:{id:e.id,action:"failed",reason:"Latest run failed"};const r=[];if(e.rerunFor.length>0&&r.push(`${function(e){const t=[...e].sort(),n=t.slice(0,3).join(", ");return t.length>3?`${n} +${t.length-3} more`:n}(e.rerunFor)} changed after its counted pass`),e.changedAfterPass&&r.push("The test changed after its counted pass"),r.length>0&&e.passed>0)return{id:e.id,action:"rerun",reason:r.join("; ")};if(e.leaves>0&&e.passed===e.leaves)return null;if(e.blocked>0)return{id:e.id,action:"not_run",reason:t?`Blocked${n}`:"Latest run blocked"};if(e.passed>0){const t=e.leaves-e.passed;return{id:e.id,action:"not_run",reason:`${t} of ${e.leaves} points not run${n}`}}return{id:e.id,action:"not_run",reason:t?`No counted run${n}`:"No run recorded"}}async function Nh(e,t){try{const{data:n,error:r}=await e.rpc("rollout_state",{p_project_id:t});return!r&&!0===n?.[zh]}catch{return!1}}async function Ph(e,t){const n=await An(()=>e.from("items").select("id, req_type:data->req_type, verified_by:data->relationships->verified_by").eq("project_id",t).eq("type","requirement").is("deleted_at",null),pn),r=await An(()=>e.from("items").select("id, verifies:data->relationships->verifies").eq("project_id",t).eq("type","test-case").is("deleted_at",null),pn),a=new Set(r.map(e=>e.id)),i=new Map,s=(e,t)=>{if(!a.has(t))return;let n=i.get(e);n||i.set(e,n=new Set),n.add(t)},o=new Set(n.map(e=>e.id));for(const e of n)for(const t of Rh(e.verified_by))s(e.id,t);for(const e of r)for(const t of Rh(e.verifies))o.has(t)&&s(t,e.id);return{requirements:n,testsOf:i}}async function Fh(e,t,n){const{requirements:r,testsOf:a}=await Ph(e,t),i=new Set(r.map(e=>e.id)),s=[...new Set([...a.values()].flatMap(e=>[...e]))].sort(),o=await En(s,r=>e.rpc("needs_attention_test_states",{p_project_id:t,p_release_id:n.releaseId,p_test_case_ids:r})),l=i.size>0?await t_(e,t,i,n.releaseId):[],d=new Map;for(const e of l)for(const t of e.test_case_ids??[]){const n=d.get(t);n?n.push(e.requirement_id):d.set(t,[e.requirement_id])}const c=await An(()=>e.from("change_review_flags").select("id, item_id, kind, source_item_id").eq("project_id",t).is("cleared_at",null),["id"]),u=n.releaseId?await Ih(e,t,n.releaseId):null,p=await Mm(e,t);return function(e){const t=new Map;for(const n of e.flags){const e=t.get(n.item_id);e?e.push(n):t.set(n.item_id,[n])}const n=new Map(e.tests.map(e=>[e.id,e])),r=new Set;for(const t of e.requirements)for(const e of t.testIds)n.has(e)&&r.add(e);const a=new Set(e.acceptedTestIds??[]),i=new Set(e.closedRequirementIds??[]),s=new Map;for(const t of e.requirements)if(t.plain)for(const e of t.testIds){const n=s.get(e);n?n.push(t.id):s.set(e,[t.id])}const o=e=>{const t=s.get(e)??[];return t.length>0&&t.every(e=>i.has(e))},l=[],d=new Set;for(const t of[...r].sort()){if(a.has(t)||o(t))continue;const r=Hh(n.get(t),e.releaseVersion);r&&(l.push(r),d.add(t))}let c=0,u=0;for(const r of e.requirements){const e=(t.get(r.id)??[]).slice().sort((e,t)=>(e.kind+(e.source_item_id??"")).localeCompare(t.kind+(t.source_item_id??""))),a=r.testIds.filter(e=>n.has(e)),s=[...new Set(e.map(Dh))],o=i.has(r.id),p=r.plain&&0===a.length&&!o;e.length>0?l.push({id:r.id,action:"review",reason:[...s,...p?["No linked test case"]:[]].join("; ")}):p&&l.push({id:r.id,action:"no_test",reason:"No linked test case"}),r.plain&&(c+=1,0===e.length&&(o||a.length>0&&a.every(e=>!d.has(e)))&&(u+=1))}return{items:l.sort(Mh),requirementsTotal:c,requirementsDone:u}}({releaseVersion:n.releaseVersion,...u?{acceptedTestIds:u.map(e=>e.test_case_id)}:{},...p?{closedRequirementIds:p.map(e=>e.requirement_id)}:{},requirements:r.map(e=>({id:e.id,plain:!("string"==typeof e.req_type&&Uu.includes(e.req_type)),testIds:[...a.get(e.id)??[]].sort()})),tests:o.map(e=>({id:e.tc_id,leaves:Number(e.leaves)||0,passed:Number(e.passed)||0,failed:Number(e.failed)||0,blocked:Number(e.blocked)||0,rerunFor:d.get(e.tc_id)??[],changedAfterPass:!0===e.changed_after_pass,failedFrom:e.failed_from??null})),flags:c.filter(e=>i.has(e.item_id)).map(e=>({item_id:e.item_id,kind:e.kind,source_item_id:e.source_item_id??null}))})}async function Uh(e,t){try{const{data:n,error:r}=await e.from("baselines").select("id, release_version, release_status, snapshot_at").eq("project_id",t).is("deleted_at",null);if(r)return null;const a=Xm(n);return a?{id:a.id,release_version:a.release_version??null,release_status:a.release_status??null}:null}catch{return null}}async function Lh(e,t,n){if(!await Nh(e,t))return{};const r=n?{releaseId:n.id,releaseVersion:n.release_version}:await async function(e,t){const n=await Uh(e,t);return n?{releaseId:n.id,releaseVersion:String(n.release_version??"")}:{releaseId:null,releaseVersion:null}}(e,t);return{needs_attention:(a=await Fh(e,t,r),a.items.map(e=>({id:e.id,action:e.action,reason:e.reason})))};var a}var Wh,Vh,Bh,Jh,Gh,Qh,Kh,Yh,Zh,Xh,eg,tg,ng,rg,ag,ig,sg,og,lg,dg=D({"src/core/needs-attention.ts"(){kr(),Yu(),o_(),Ch(),Hm(),zh="needs_attention",Mh=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,Rh=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):"string"==typeof e?[e]:[],Th="needs_attention (only where the project's Needs attention worklist is switched on; absent otherwise): the app's Needs attention list, one entry per item that is not done in the scope read (the current Release, or every recorded run when the project has none, as the Matrix reads it; release_id picks another Release): {id, action, reason}. action is review (a requirement flagged because its parent, its hazard, its interface or its parent link changed, or its ASIL rose), rerun (a test case whose counted pass a change made out of date), failed (its counted run failed), not_run (no counted run, or not every point run) or no_test (a requirement with no linked test case). Its length is the count the app's sidebar shows beside Needs attention."}});function cg(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return String(e);const n=new Date(t).toISOString();return`${n.slice(0,10)} ${n.slice(11,16)} UTC`}function ug(e){if(!e)return"";const t=Date.parse(e);return Number.isNaN(t)?String(e):new Date(t).toISOString().slice(0,10)}function pg(e){return String(e??"").replace(/\s+/g," ").trim()}function mg(e,t){return`Tested in ${e}: ${t.map(e=>`${e.id} passed${e.build?`, Build ${pg(e.build)}`:""}`).join("; ")}`}function _g(e){return`Unchanged since run ${e.test_case_id?`${e.test_case_id} (${ug(e.run_at)})`:`of ${ug(e.run_at)}`} on ${e.version}, Build ${e.build?pg(e.build):"(none)"}`}function fg(e){return`Closed by document "${pg(e.document_name)}" (${e.link?`link ${pg(e.link)}, `:""}closed by ${pg(e.closed_by)} on ${cg(e.closed_at)})`}function hg(e){const t=pg(e.reason),n=e.link?`${t.replace(/\.$/,"")}. Bug: ${pg(e.link)}`:t;return`${e.label}. Reason: ${n} (accepted by ${pg(e.accepted_by)} on ${cg(e.accepted_at)})`}function gg(e,t){const n=function(e){return{verified:e.verified.tested.length+e.verified.earlier.length+e.verified.documents.length,anomalies:e.known_anomalies.tests.length,notDone:e.not_done.requirements.length+e.not_done.tests.length}}(e),r=e.release_version,a=[`# Release ${r} report: ${pg(e.project_name)}`,""];a.push(`- **Release:** ${r} (snapshot "${pg(e.release_name)}")`),a.push(`- **Project:** ${pg(e.project_name)}`),a.push(`- **Generated:** ${cg(e.generated_at)}`),a.push(`- **Status:** ${function(e){return`Final, stored ${cg(e.stored_at)} (server time). SHA-256 of the stored report: ${e.sha256}`}(t)}`);for(const t of e.notes)a.push("",`_Note: ${pg(t)}_`);a.push("",`## ${Bh[0]} (${n.verified})`),a.push("",`### Tested in this Release (${e.verified.tested.length})`,""),0===e.verified.tested.length&&a.push(Kh);for(const t of e.verified.tested)a.push(Qh(t.id,t.title,mg(r,t.tests)));a.push("",`### Verified in an earlier Release (${e.verified.earlier.length})`,""),0===e.verified.earlier.length&&a.push(Kh);for(const t of e.verified.earlier)a.push(Qh(t.id,t.title,_g(t)));a.push("",`### Closed by document (${e.verified.documents.length})`,""),0===e.verified.documents.length&&a.push(Kh);for(const t of e.verified.documents)a.push(Qh(t.id,t.title,fg(t)));a.push("",`## ${Bh[1]} (${n.anomalies})`,""),0===e.known_anomalies.tests.length&&a.push(Kh);for(const t of e.known_anomalies.tests)a.push(Qh(t.test_case_id,t.title,hg(t)));if(e.known_anomalies.requirements.length>0){a.push("",`Requirements accepted for ${r} (${e.known_anomalies.requirements.length}):`,"");for(const t of e.known_anomalies.requirements)a.push(Qh(t.id,t.title,t.label))}a.push("",`## ${Bh[2]} (${n.notDone})`),a.push("",`### Requirements (${e.not_done.requirements.length})`,""),0===e.not_done.requirements.length&&a.push(Kh);for(const t of e.not_done.requirements)a.push(Qh(t.id,t.title,`${t.mark}. ${pg(t.reason)}`));a.push("",`### Tests (${e.not_done.tests.length})`,""),0===e.not_done.tests.length&&a.push(Kh);for(const t of e.not_done.tests)a.push(Qh(t.id,t.title,`${t.mark}. ${pg(t.reason)}`));return a.push("",`## ${Bh[3]}`,""),a.push(e.regression_note&&e.regression_note.trim()?e.regression_note.trim().split(/\r\n|[\r\n\u0085\u2028\u2029]/).map(e=>e.trim()?`> ${e}`:">").join("\n"):Gh),a.push("","---","",Jh),a.join("\n")}async function yg(e,t,n,r){if(!r)return{};if(!n){const{data:n,error:r}=await e.rpc("rollout_state",{p_project_id:t});if(r)throw r;return!0===n?.[Wh]?{release_report:null}:{}}const a=await async function(e,t,n){const{data:r,error:a}=await e.rpc("release_report_stored",{p_project_id:t,p_release_id:n});if(a)throw a;const i=r??{};return!0!==i.enabled?{enabled:!1}:{enabled:!0,release_id:String(i.release_id??n),release_version:Yh(i.release_version)?i.release_version:null,release_status:Yh(i.release_status)?i.release_status:null,regression_note:Yh(i.regression_note)?i.regression_note:null,final_report:i.final_report??null,final_report_sha256:Yh(i.final_report_sha256)?i.final_report_sha256:null,final_report_at:Yh(i.final_report_at)?i.final_report_at:null}}(e,t,n.id);if(!a.enabled)return{};const i={release_id:n.id,release_version:a.release_version??null};if(null!=a.final_report){const e=function(e){if(!eg(e)||e.format!==Vh)return null;const{verified:t,known_anomalies:n,not_done:r}=e;return Yh(e.release_id)&&Yh(e.release_version)&&Yh(e.release_name)&&Yh(e.project_name)&&Yh(e.generated_at)&&eg(t)&&Xh(t.tested,ng)&&Xh(t.earlier,rg)&&Xh(t.documents,ag)&&eg(n)&&Xh(n.tests,ig)&&Xh(n.requirements,sg)&&eg(r)&&Xh(r.requirements,og)&&Xh(r.tests,og)&&Zh(e.regression_note)&&Xh(e.notes,Yh)?e:null}(a.final_report);if(!e||!a.final_report_sha256||!a.final_report_at)throw new Error(`release_report: the stored report of Release ${n.id} could not be read`);return{release_report:{...i,status:"final",stored_at:a.final_report_at,sha256:a.final_report_sha256,report_text:gg(e,{stored_at:a.final_report_at,sha256:a.final_report_sha256})}}}return{release_report:{...i,status:"released"===a.release_status?"draft":"not_stored",stored_at:null,sha256:null,report_text:null}}}var wg,vg,bg=D({"src/core/release-report.ts"(){Wh="release_report",Vh=1,Bh=["1. Verified","2. Known anomalies","3. Not done","4. Regression note"],Jh="ATOMS records names and server times. This is not a Part 11 signature.",Gh="No Regression note was written when this Release was promoted.",Qh=(e,t,n)=>`- ${pg(`${e} ${t}`)}: ${n}`,Kh="_None._",Yh=e=>"string"==typeof e,Zh=e=>null===e||"string"==typeof e,Xh=(e,t)=>Array.isArray(e)&&e.every(t),eg=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),tg=e=>eg(e)&&Yh(e.id)&&Zh(e.build)&&Zh(e.run_at),ng=e=>eg(e)&&Yh(e.id)&&Yh(e.title)&&Xh(e.tests,tg),rg=e=>eg(e)&&Yh(e.id)&&Yh(e.title)&&Zh(e.test_case_id)&&Yh(e.version)&&Zh(e.build)&&Yh(e.run_at)&&Zh(e.tester),ag=e=>eg(e)&&Yh(e.id)&&Yh(e.title)&&Yh(e.document_name)&&Zh(e.link)&&Yh(e.closed_by)&&Yh(e.closed_at),ig=e=>eg(e)&&Yh(e.test_case_id)&&Yh(e.title)&&Yh(e.label)&&Yh(e.reason)&&Zh(e.link)&&Yh(e.accepted_by)&&Yh(e.accepted_at),sg=e=>eg(e)&&Yh(e.id)&&Yh(e.title)&&Yh(e.label),og=e=>eg(e)&&Yh(e.id)&&Yh(e.title)&&Yh(e.mark)&&Yh(e.reason),lg="include_report (only where the project's Release report is switched on; release_report is absent otherwise): release_report is the Release report of the Release read, {release_id, release_version, status, stored_at, sha256, report_text}. status final: the report was stored when the next Release was promoted, and report_text is that stored report as the Markdown the app downloads (sections 1. Verified, 2. Known anomalies, 3. Not done, 4. Regression note), with the server's stored_at and the database's SHA-256 of it. status draft: the current Release, whose report the app builds when a member downloads it and stores at the next promotion, so report_text is null. status not_stored: a replaced Release whose report was never stored, report_text null. release_report is null when there is no Release to read."}});function kg(e,t,n=wg){return(r,a)=>{if("unrecognized_keys"!==r.code)return{message:a.defaultError};const i=(r.keys??[]).join(", ");return{message:`${e} takes no ${i} on an entry of ${t}. Nothing was written. ${n}`}}}var jg,Sg=D({"src/core/list-entry-fields.ts"(){wg="Send the entry again with only the fields this tool's schema lists.",vg="Create the items first, then set other fields with atoms_update_item and record each run with atoms_record_test_results (a run is stamped with server time; past run dates come in through an import in the ATOMS app)."}});var Ag,$g,xg,Ig=D({"src/apps/register.ts"(){jg={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});async function qg(e,t,n){if(!e||"function"!=typeof e.rpc)return null;if(($g.get(t)??0)>Date.now())return null;const r=await e.rpc(t,n);if(a=r?.error,a&&("PGRST202"===a.code||"42883"===a.code||/Could not find the function public\.mcp_/i.test(String(a.message??""))))return $g.set(t,Date.now()+Ag),null;var a;if(r?.error)throw new Error(r.error.message??`${t} failed`);return r}function Og(e){return e.replace(/\*/g,"%")}async function Eg(e,t,n){const r=await qg(e,"mcp_count_items",{p_project_id:t,p_type:n.type??null,p_domain_pattern:void 0!==n.domainPattern?Og(n.domainPattern):null,p_level_pattern:void 0!==n.levelPattern?Og(n.levelPattern):null,p_search_pattern:void 0!==n.search?(a=n.search,Og(`*${on(a)}*`)):null});var a;return r?xg(r.data):null}var zg=D({"src/core/project-read-counts.ts"(){Sn(),Ag=6e5,$g=new Map,xg=e=>{const t="string"==typeof e?Number(e):e;return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null}}});function Mg(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString().replace(/Z$/,"999Z")}var Rg=D({"src/core/as-of.ts"(){}});async function Tg(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}))}async function Cg(e,t,n){const r=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||3===t.length&&kn(t[2]))&&"string"==typeof t[0]&&t[0].length>0&&"string"==typeof t[1]&&t[1].length>0)return 3===t.length?{created_at:t[0],id:t[1],total:t[2]}:{created_at:t[0],id:t[1]}}catch{}return null}(n.after):null;if(void 0!==n.after&&null===r)throw new jn;const a=void 0===r?.total,i=null!==r&&a,s=a=>{let i=e.from("items").select("*",a).eq("project_id",t).is("deleted_at",null);return r&&(i=i.or(function(e){return xn(bn,e)}(r))),n.type&&(i=i.eq("type",n.type)),n.domain&&(i=i.filter("data->tags->>domains","ilike",cn(n.domain))),n.level&&(i=i.filter("data->tags->>level","ilike",dn(n.level))),i};let o=s(i?{count:"exact"}:void 0).order("created_at",{ascending:!0}).order("id",{ascending:!0});o=r?o.range(0,n.limit):o.range(n.offset,n.offset+n.limit);const[{data:l,error:d,count:c},u]=await Promise.all([un(o),r?Promise.resolve(null):Eg(e,t,{type:n.type,domainPattern:n.domain?cn(n.domain):void 0,levelPattern:n.level?dn(n.level):void 0})]);if(d)throw new Error(d.message);let p=i?c:u;if(!r&&null===p){const e=await s({count:"exact",head:!0});if(e.error)throw new Error(e.error.message);p=e.count??null}const m=l??[],_=m.slice(0,n.limit),f=m.length>n.limit,h=r?.total??p??0,g=r&&a?void 0:h;return{items:_,totalCount:h,hasMore:f,nextCursor:f?zn(_[_.length-1],g):void 0,cursorTotal:g}}async function Dg(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 Hg(e,t){if(t.baseline_id&&t.as_of)throw new Wt("baseline_id and as_of are mutually exclusive");if(t.as_of)return gn(Mg(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 Wt("Baseline not found");if(n.project_id!==t.project_id)throw new Wt("Baseline does not belong to this project");return yn(t.baseline_id)}return null}async function Ng(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 Pg(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 Fg(e,t,n){return qn(e,t,n).catch(e=>{throw new Error(`projectStateAt: ${e.message}`)})}async function Ug(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 An(()=>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=n=>{let i=e.from("items").select("*",n).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${ln(a)},data->>body.ilike.${ln(a)},data->>summary.ilike.${ln(a)}`);return n?.head||(i=void 0===r.offset?i.limit(r.limit):i.order("id",{ascending:!0}).range(r.offset,r.offset+r.limit-1)),r.type&&(i=i.eq("type",r.type)),r.domain&&(i=i.filter("data->tags->>domains","ilike",cn(r.domain))),r.level&&(i=i.filter("data->tags->>level","ilike",dn(r.level))),i};if(i)return async function(e,t,n){const r=[];let a=0;for(let t=0;t<e.length;t+=wn){const{data:i,error:s,count:o}=await n(e.slice(t,t+wn));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({count:"exact"}).in("id",e));const[{data:o,error:l},d]=await Promise.all([un(s()),Eg(e,t,{type:r.type,domainPattern:r.domain?cn(r.domain):void 0,levelPattern:r.level?dn(r.level):void 0,search:a})]);if(l)throw new Error(l.message);let c=d;if(null===c){const e=await s({count:"exact",head:!0});if(e.error)throw new Error(e.error.message);c=e.count??null}return{items:o??[],totalCount:c??0}}function Lg(e,t,n){return async function(){dm>=lm?await new Promise(e=>cm.push(e)):dm+=1;try{return await async function(e,t,n){let r,a,i;if(n.moment){const s=(await Fg(e,t,n.moment)).map(Pg);r=s.filter(e=>"requirement"===e.type),a=s.map(e=>({id:e.id,type:e.type,data:e.data})),i=[]}else a=(await An(()=>e.from("items").select(om).eq("project_id",t).is("deleted_at",null),pn)).map(vm),r=a.filter(e=>"requirement"===e.type),i=await An(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t),mn);const s=r.filter(e=>!(n.domain&&!(e.data?.tags?.domains??[]).some(e=>Ml(e)===Ml(n.domain))||n.level&&ml(e.data?.tags?.level)!==ml(n.level))),o=Vm(a,i),l=gm(a,o),d=s.filter(e=>l.has(e.id)),c=s.filter(e=>!l.has(e.id)),u=wm(a,o);return{covered:d,uncovered:c,total:s.length,mitigators:u}}(e,t,n)}finally{const e=cm.shift();e?e():dm-=1}}()}var Wg=D({"src/db/queries.ts"(){Sn(),zg(),pd(),zm(),kr(),Ym(),Rg(),an()}}),Vg={};async function Bg(e={}){try{const{projects:t,viewerOrgs:n}=await gu(async()=>{const e=await _u(),t=se(await ae(e,yu()));return{projects:await Tg(e),viewerOrgs:t}}),r=$e(),a=xe(),i=function(e,t){const n=(e,t)=>null===e||e.includes(t);if(0===e.orgs.length||1===e.orgs.length&&""===e.orgs[0].orgId){const r=(e.orgs[0]?.effective??P).project_scope;return t.filter(e=>n(r,e.id))}return t.filter(t=>{const r="string"==typeof t.org_id?ge(e,t.org_id):ye(e);return n(r.project_scope,t.id)})}(Fe(),function(e,t){return 0===t.size?e:e.filter(e=>!("string"==typeof e.org_id&&t.has(e.org_id)))}(t,n)).filter(e=>!a||e.org_id===a).filter(e=>!r||e.id===r).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})),s=qd(i,e.offset,e.limit);return Kc(bc(s.rows,s.meta),{paging:{}})}catch(e){return Yc(Uc(e,{read:!0}))}}H(Vg,{listProjectsHandler:()=>Bg});var Jg=D({"src/tools/list-projects.ts"(){xu(),_e(),Wg(),Ie(),We(),Ae(),Ud(),tu()}}),Gg={};async function Qg(e){try{const t=await _u();let n,r,a=null;try{a=await Hg(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Yc(Uc(e,{read:!0}))}let i=null;if(a){const i=(await Fg(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=>Ml(t)===Ml(e.domain)))return!1}return!e.level||ml(n?.tags?.level)===ml(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 Cg(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=i?await n_(t,e.project_id,n):null,o=s?.flags??new Map,l=n.map(e=>({id:e.id,title:e.title,type:e.type,status:Xp(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type,...o.has(e.id)?{needs_rerun:o.get(e.id)}:{}})),d=kc(r,e.limit,void 0!==e.after?0:e.offset);i&&"boolean"==typeof i.hasMore&&(d.has_more=i.hasMore,i.nextCursor&&(d.next_cursor=i.nextCursor),i.hasMore&&void 0===e.after&&(d.next_offset=e.offset+n.length)),s?.scope&&(d.rerun_scope=s.scope.label);const c=i?{resume:t=>({meta:{next_cursor:zn(n[t-1],i?.cursorTotal),...void 0===e.after?{next_offset:e.offset+t}:{}},next:"after=meta.next_cursor"})}:{};return Kc(bc(l,d),{paging:c})}catch(e){return e instanceof jn?Yc(Ic(e.message)):e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(Gg,{listItemsHandler:()=>Qg});var Kg=D({"src/tools/list-items.ts"(){xu(),Wg(),tu(),kr(),pd(),fm(),o_()}});var Yg=D({"src/core/get-item-links.ts"(){Ym(),kr()}});function Zg(e,t){return Ra(e,t)}function Xg(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 ey(e,t){if(t&&Ca(e,t))throw Xg(t)}async function ty(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 vu(e)}catch{t=null}return function(e){const t=Ha(e.clientName);return{kind:"agent",user_id:e.userId,session_id:e.sessionId,label:Na(t,e.name,e.email),client:t}}({userId:yu(),sessionId:WA(),name:t,email:wu(),clientName:BA()})}(e),l=async n=>{const a=function(e,t){return function(e,t,n,r){const a={surface:"mcp",delivery:"npm",package_version:SA,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:d,error:c}=await e.rpc("apply_item_ops",{p_project_id:t,p_ops:n,p_author:o,p_client:l});if(c)throw Xg(c);return d??{answers:[]}};let d;if(!1===r.chunk)try{const e=await l([...n]);d={answers:e.answers??[],results:[e],notSent:[]}}catch(e){d={answers:[],results:[],notSent:[...n],error:e}}else d=await async function(e){const t=e.isTooManyItems??za,n=function(e,t=mr,n=_r){return Oa(xa(e),t,n)}(e.ops);let r=n.length;const a=[],i=new Map;let s,o=0,l=0,d=[],c=0;for(;c<n.length;){const u=n[c];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);c+=1}catch(e){l+=1;const a=xa(u);if(t(e)&&a.length>1){const e=Math.ceil(a.length/2),t=[Oa(a.slice(0,e),1/0,1/0)[0],Oa(a.slice(e),1/0,1/0)[0]];n.splice(c,1,...t),r+=1;continue}if(t(e)&&u.length>1){const e=Math.ceil(u.length/2);n.splice(c,1,u.slice(0,e),u.slice(e)),r+=1;continue}s=e,d=n.slice(c).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:d,...void 0!==s?{error:s}:{}}}({ops:n,send:e=>l(e)});return void 0!==d.error&&0===d.results.length&&ey("ops",d.error),d}function ny(e){return{...e.chunks?{chunks:e.chunks}:{},...void 0!==e.error?{error:Uc(e.error).message}:{}}}function ry(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 ay(e){const t=e.relooked?[...e.answers]:await Ja(e.client,e.projectId,e.answers,e.ops),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 Qr(e.client,e.projectId,n)),ia({answers:t,ops:e.ops,skippedItems:ry(e.results??[]),openRevisions:r,labels:e.labels})}function iy(e){const t=e.suggestion;return"number"==typeof t?.sg_number?t.sg_number:null}function sy(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!==iy(e)?{change:{sg_number:iy(e)}}:{}})),r={...e,applied:[...e.applied,...n]},{isError:a,result:i}=fa(r,t);return a?Yc(i):Kc(i)}async function oy(e,t,n,r,a,i={}){const s=[...new Set(r.filter(e=>["applied","noop","replaced","captured"].includes(e.status)&&!e.replayed&&e.item_id).map(e=>e.item_id))].filter(e=>n.some(t=>t.item_id===e));if(0===s.length)return;const o=s.map(e=>({item_id:e,project_id:t,changed_by:yu(),event_type:a,old_data:null,new_data:Ga(n,r,e),actor:VA(),session_id:WA(),...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 ly(e){return e&&0!==e.length?"tags"===e[0]?"level"===e[1]?"level":"domains"===e[1]?"domains":"tags":e[0]:null}function dy(e){return"set"===e.kind?e.path:[...e.path,e.kind,String(e.row_id??Tr(e.value??null))]}function cy(e){return null==e?[]:"string"==typeof e?[e]:[...e]}var uy,py=D({"src/tools/_agent-ops.ts"(){xu(),JA(),ai(),tu()}}),my={};function _y(e,t){if(!t)return e;const n={...e};for(const e of uy){const r=t[e];null!=r&&("evidence_url"===e&&"string"==typeof r&&""===r.trim()||(n[e]=r))}return n}async function fy(e){try{const r=await _u();let a=null;try{a=await Hg(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Yc(Uc(e,{read:!0}))}let i=null;if(!a&&!0===await Zg(r,e.project_id)){i={head:await Yr(r,e.project_id),revision:(await Qr(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?Pg(e):null):await Dg(r,e.project_id,e.item_id);if(!s)return Yc(Sc("Item",e.item_id));const o=Object.fromEntries(Fm.map(e=>[e.lane,[]]));if(a){const t=s.data?.relationships??{};for(const e of Object.keys(o)){const n=t[e];Array.isArray(n)&&(o[e]=n.slice())}const n=await async function(e,t,n,r){return function(e,t){const n={};for(const r of t){if(!r||r.id===e)continue;const t=r.data?.relationships;if(t&&"object"==typeof t)for(const a of Fm){const i=t[a.lane];if(!Array.isArray(i)||!i.includes(e))continue;const s=n[a.incoming]??=[];s.includes(r.id)||s.push(r.id)}}return n}(n,await qn(e,t,r))}(r,e.project_id,e.item_id,a);for(const[e,t]of Object.entries(n))if(e in o)for(const n of t)o[e].includes(n)||o[e].push(n)}else{const t=await async function(e,t,n){const r=r=>An(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq(r,n),mn),[a,i]=await Promise.all([r("from_id"),r("to_id")]);return[...a,...i.filter(e=>e.from_id!==n)]}(r,e.project_id,e.item_id),n=(e,t)=>{if(!e||!(e in o))return;const n=o[e];n.includes(t)||n.push(t)},a=new Set([e.item_id]);for(const e of t)a.add(e.from_id),a.add(e.to_id);const i=s.data?.relationships??{};for(const e of Object.keys(o)){const t=i[e];if(Array.isArray(t))for(const e of t)"string"==typeof e&&a.add(e)}const l=await async function(e,t,n,r){const a=[...new Set(n)].filter(e=>e!==r),i=await En(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 s.add(r),s}(r,e.project_id,a,e.item_id),d=e=>l.has(e);for(const r of t)if(r.from_id===e.item_id){if(!d(r.to_id))continue;n(Lm(r.type,!0),r.to_id)}else{if(!d(r.from_id))continue;n(Lm(r.type,!1),r.from_id)}for(const t of Object.keys(o)){const r=i[t];if(Array.isArray(r))for(const a of r)"string"==typeof a&&a!==e.item_id&&d(a)&&n(t,a)}}const l=s.data?.relationships??{},d={};for(const e of pf){const t=Array.isArray(l[e])?l[e].filter(e=>"string"==typeof e):[];t.length>0&&(d[e]=t)}let c=[];if("test-case"===s.type)if(a)c=(im(s.data)??[]).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)=>Pp(String(e.base.run_at),String(t.base.run_at))).slice(0,20).map(e=>_y(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)throw n;if(t){const e=new Map;for(const t of s.data?.runs??[])"string"==typeof t?.date&&e.set(t.date,t);c=t.map(t=>_y(t,e.get(String(t.run_at))))}}const u=i&&function(e){return"requirement"===e.type&&null!==Hu(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,p=a?void 0:await n_(r,e.project_id,[s]),m={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:{...Wm(o),...d},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:Xp(s),...r_(p,s.id),...Nu(s,{live:null!==i,since:u}),..."test-case"===s.type?{...Qp(s.data),latest_result:c[0]?.result??"not-run",test_results:c}:{},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}};let _;if(!a&&kf(s.type)){const t=await Vf(r,e.project_id),n=Wf(t);_="hazard"===s.type?function(e,t){const{level:n,count:r}=e.hazardAsil(t);return{highest_asil:n,event_count:r,events:[...e.rowsOfHazard(t)],functions:[...e.hazardFunctions(t)],goals:[...e.hazardGoals(t)]}}(n,s.id):function(e,t,n){const r=e.goalVerification(t),a=new Map(n.map(e=>[e.id,e])),i=[...e.rowsOfGoal(t)],s=i.filter(e=>Tl((a.get(e)?.data??{}).analysis_props??null)!==_o),o=[...e.satisfiers(t)],l=e.goalCoverage(t);return{asil:e.goalAsil(t),source_rows:s,events:i,functions:[...e.goalFunctions(t)],satisfied_by:o,verified_satisfiers:o.filter(t=>e.requirementVerified(t)).length,row_mitigators:[...l.rowMitigators],uncovered_rows:[...l.uncoveredRows],untested_rows:[...l.untestedRows],verification:{verified:r.verified,total:r.total,requirements:r.requirements.map(e=>({id:e.id,verified:e.verified,via_rows:[...e.viaRows],text:Z_(e,Hf)}))}}}(n,s.id,t)}_&&Object.assign(m,{safety:_}),a||Object.assign(m,await async function(t){if(!Pf(t))return{};const n=ro(t.data);return Ff(t,n?await(a=n,Dg(r,e.project_id,a)):null)?Nf(t.id):{};var a}(s));const f=function(e){const t={};if(e&&"object"==typeof e)for(const[n,r]of Object.entries(e))Array.isArray(r)&&r.length>0&&(t[n]=r.length);return{relationship_counts:t}}(m.relationships);if(i){const n=s.data?.steps,a=Array.isArray(n)?n:[],o=(await Zr(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 Kc(bc({...m,...i.revision?{base_token:await Wr(i.revision,"item")}:{},seq:i.head,editing_now:o,...l?{presence:l}:{}},f))}return Kc(bc(m,f))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}var t,n}H(my,{getItemHandler:()=>fy});var hy,gy,yy=D({"src/tools/get-item.ts"(){Wu(),xu(),fm(),o_(),Wg(),Ym(),Yg(),tu(),ai(),py(),nh(),uy=["point","release_id","build","environment","tooling","evidence_url","step_results"]}}),wy={};function vy(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:Xr(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 by(e){try{const t=await _u(),n=await Zg(t,e.project_id);if(null===n)return Yc(Ta());if(!n)return Yc(Ic(gy));if(void 0===e.since_seq){const n=await Yr(t,e.project_id);return Kc(bc({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??hy});if(a)throw a;const i=r??{},s=(i.changes??[]).map(vy);return Kc(bc({project_id:e.project_id,changes:s,last_seq:Number(i.last_seq??e.since_seq),has_more:!0===i.more}),{paging:{list:"changes",resume:e=>({data:{last_seq:s[e-1].seq,has_more:!0},next:`since_seq=${s[e-1].seq}`})}})}catch(e){return Yc(Uc(e,{read:!0}))}}H(wy,{LIST_CHANGES_DEFAULT_LIMIT:()=>hy,LIST_CHANGES_NOT_NUMBERED:()=>gy,listChangesHandler:()=>by,listedChange:()=>vy});var ky=D({"src/tools/list-changes.ts"(){xu(),ai(),tu(),py(),hy=100,gy="This project does not number its changes yet. Use atoms_get_history for one item."}}),jy=D({"src/core/snapshot-search.ts"(){}}),Sy={};async function Ay(e){try{const t=await _u();let n,r,a=null;try{a=await Hg(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return Yc(Uc(e,{read:!0}))}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 Fg(t,e.project_id,a),e.query,{type:e.type,limit:e.limit});r=i.totalCount,n=i.items}else{const a=await Ug(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});n=a.items,r=a.totalCount}return Kc(bc(n.map(e=>({id:e.id,title:e.title,type:e.type,status:Xp(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),kc(r,e.limit,0)),{paging:{resume:"none"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(Sy,{searchHandler:()=>Ay});var $y=D({"src/tools/search.ts"(){xu(),Wg(),jy(),tu(),fm()}}),xy={};async function Iy(e){try{const t=await _u(),{access_token:n}=await Ct(),{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(()=>(It(),bt)),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:d}=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(d)throw new Error(d.message);return{items:l??[],totalCount:(l??[]).length,method:"semantic"}}(t,e.project_id,e.query,{type:e.type,limit:e.limit,accessToken:n});return Kc(bc(r.map(e=>({id:e.id,title:e.title,type:e.type,status:Xp(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),kc(a,e.limit,0)),{paging:{resume:"none"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(xy,{semanticSearchHandler:()=>Iy});var qy=D({"src/tools/semantic-search.ts"(){xu(),Pt(),Wg(),tu(),fm()}}),Oy={};async function Ey(e){try{if(e.baseline_id&&e.as_of)return Yc(Ic("baseline_id and as_of are mutually exclusive"));const t=await _u();let n;if(e.baseline_id){const r=await Ng(t,e.baseline_id);if(!r)return Yc(Ic("Baseline not found"));if(r.project_id!==e.project_id)return Yc(Ic("Baseline does not belong to this project"));n=yn(e.baseline_id)}else e.as_of&&(n=gn(Mg(e.as_of)));const r=await Lg(t,e.project_id,{domain:e.domain,level:e.level,moment:n}),{total:a,mitigators:i}=r,s=n?null:await Mm(t,e.project_id),{covered:o,uncovered:l,coveredByDocument:d}=Tm(r.covered,r.uncovered,s),c=qd(l,e.offset,e.limit),u=c.rows.map(e=>{const t=function(e,t){if(hm(e))return[...t?.get(e.id)??[]]}(e,i);return{id:e.id,title:e.title,type:e.type,status:Xp(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,...t?{mitigated_by:t}:{}}});return Kc(bc({covered:o.length,uncovered:l.length,total:a,coverage_percent:Nm(o.length,a),covered_via_mitigation:Im(l,i),...d?{covered_by_document:d}:{},uncovered_items:u},c.meta),{paging:{list:"uncovered_items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(Oy,{getCoverageHandler:()=>Ey});var zy,My,Ry=D({"src/tools/get-coverage.ts"(){xu(),Wg(),Rg(),kr(),tu(),fm(),Ud(),Um(),zm(),Hm()}}),Ty=D({"src/core/accepted-readiness.ts"(){kr(),o_(),dg()}}),Cy={};async function Dy(e,t,n){const r=await An(()=>e.from("items").select("id").eq("project_id",t).eq("type","requirement").is("deleted_at",null),pn);return(await En(r.map(e=>e.id),r=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:n,p_requirement_ids:r}))).sort(My)}async function Hy(e){try{const t=await _u();let n=null;if(e.release_id){const r=await Ng(t,e.release_id);if(!r)return Yc(Ic(`Release ${e.release_id} not found`));if(r.project_id!==e.project_id)return Yc(Ic("Release does not belong to this project"));if(null===r.release_version)return Yc(jc(`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 Yc(Uc(a,{read:!0}));n=r,n||(n=await async function(e,t){return await Nh(e,t)?Uh(e,t):null}(t,e.project_id))}const r=await Mm(t,e.project_id);if(!n)return Kc(bc({release:null,rerun:await Dy(t,e.project_id,null),...r?{document_closures:r}:{},hint:zy,...await Lh(t,e.project_id,null),...await yg(t,e.project_id,null,e.include_report)}),{complete:!0});const{data:a,error:i}=await t.rpc("verification_readiness",{p_project_id:e.project_id,p_release_id:n.id});if(i)return Yc(Uc(i,{read:!0}));const s=n.id,o=await An(()=>t.from("verification_status").select("requirement_id, state, stale, points_total, points_run, verified_in").eq("project_id",e.project_id).eq("release_id",s),["requirement_id"]),l=function(e,t){if(!t)return e.slice();const n=new Set(t.map(e=>e.requirement_id));return e.map(e=>({...e,closed_by_document:n.has(e.requirement_id)}))}(o.slice().sort(My),r),d=await Ih(t,e.project_id,s),c=await async function(e,t,n,r){if(!r)return null;const a=[...new Set(r.map(e=>e.test_case_id))],i={acceptedTestIds:a,testsOf:new Map,states:[],rerunOf:new Map};if(0===a.length)return i;const{testsOf:s}=await Ph(e,t),o=new Set(a),l=new Map;for(const[e,t]of s)[...t].some(e=>o.has(e))&&l.set(e,[...t].sort());if(0===l.size)return i;const d=[...new Set([...l.values()].flat().filter(e=>!o.has(e)))].sort(),c=d.length>0?await En(d,r=>e.rpc("needs_attention_test_states",{p_project_id:t,p_release_id:n,p_test_case_ids:r})):[],u=d.length>0?await t_(e,t,l.keys(),n):[],p=new Map;for(const e of u)p.set(e.requirement_id,[...p.get(e.requirement_id)??[],...e.test_case_ids??[]]);return{acceptedTestIds:a,testsOf:l,states:c,rerunOf:p}}(t,e.project_id,s,d),u={release:{id:n.id,version:n.release_version,status:n.release_status},readiness:Eh(Rm(a??{},o,r),o,c,new Set((r??[]).map(e=>e.requirement_id))),requirements:l,rerun:await Dy(t,e.project_id,s),...await Lh(t,e.project_id,n),...d?{accepted_failures:d}:{},...r?{document_closures:r}:{},...await yg(t,e.project_id,n,e.include_report),...0===l.length?{hint:"projection empty; an admin may need to run rebuild_verification_from_runs for this project"}:{}};return e.include_gaps&&(u.gaps=await An(()=>t.rpc("verification_notrun_points",{p_project_id:e.project_id,p_release_id:s}),["tc_id","asset","point_key"])),Kc(bc(u),{complete:!0})}catch(e){return Yc(Uc(e,{read:!0}))}}H(Cy,{verificationStatusHandler:()=>Hy});var Ny,Py,Fy,Uy,Ly=D({"src/tools/verification-status.ts"(){xu(),Wg(),kr(),dg(),Ch(),Ty(),Hm(),bg(),tu(),zy="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).",My=(e,t)=>e.requirement_id<t.requirement_id?-1:e.requirement_id>t.requirement_id?1:0}});function Wy(e,t,n){const r=e?.count??0,a=(e?.items??[]).slice(0,Ny).map(e=>""===String(e).trim()?`an unnamed ${t}`:String(e));if(0===a.length)return Fy(r,`a ${t}`,n);const i=r-a.length;return i>0?`${a.join(", ")} and ${i} more`:1===a.length?a[0]:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`}function Vy(e,t,n,r){if(!e||e.count<=0)return[];const a=e=>""===String(e??"").trim()?`an unnamed ${t}`:String(e),i=(e.items??[]).slice(0,Ny);if(0===i.length)return[`${r} ${Fy(e.count,`a ${t}`,n)}`];const s=i.map(e=>"arrow"===t?`${r} an arrow to ${a(e.to)}`:`${r} ${"group"===t?"group ":""}${a(e.from)} to ${a(e.to)}`),o=e.count-i.length;return o>0&&s.push(`${r} ${Fy(o,`1 more ${t}`,`more ${n}`)}`),s}function By(e){const t=e.summary??{};if("trashed"===e.event_type)return"Moved to Trash";if("restored"===e.event_type)return"Restored";const n=[];if("editors"===e.event_type){for(const r of t.editors_added??[])n.push(r.user_id===e.changed_by?"added themselves as editor":`added ${r.name} as editor`);for(const r of t.editors_removed??[])n.push(r.user_id===e.changed_by?"removed themselves as editor":`removed ${r.name} as editor`)}else if("created"===e.event_type){const e=[t.boxes_added?.count?Fy(t.boxes_added.count,"1 box","boxes"):null,t.arrows_added?.count?Fy(t.arrows_added.count,"1 arrow","arrows"):null,t.groups_added?.count?Fy(t.groups_added.count,"1 group","groups"):null].filter(e=>null!==e);n.push(0===e.length?"created":`created with ${1===e.length?e[0]:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}`),t.links_added?.count&&n.push(`linked ${Wy(t.links_added,"item","items")}`)}else{void 0!==t.name?.from&&n.push(`renamed the design to ${t.name.to}`),t.description_changed&&n.push("changed the description"),t.boxes_added?.count&&n.push(`added ${Wy(t.boxes_added,"box","boxes")}`),t.boxes_removed?.count&&n.push(`removed ${Wy(t.boxes_removed,"box","boxes")}`),n.push(...Vy(t.boxes_renamed,"box","boxes","renamed")),t.boxes_moved?.count&&n.push(`moved or resized ${Fy(t.boxes_moved.count,"a box","boxes")}`),t.arrows_added?.count&&n.push(`added ${Fy(t.arrows_added.count,"an arrow","arrows")}`),t.arrows_removed?.count&&n.push(`removed ${Fy(t.arrows_removed.count,"an arrow","arrows")}`),n.push(...Vy(t.arrows_relabelled,"arrow","arrows","relabelled"));const e=e=>`${(e.items??[]).length>0?"group ":""}${Wy(e,"group","groups")}`;t.groups_added?.count&&n.push(`added ${e(t.groups_added)}`),t.groups_removed?.count&&n.push(`removed ${e(t.groups_removed)}`),n.push(...Vy(t.groups_renamed,"group","groups","renamed")),t.groups_moved?.count&&n.push(`moved or resized ${Fy(t.groups_moved.count,"a group","groups")}`),t.links_added?.count&&n.push(`linked ${Wy(t.links_added,"item","items")}`),t.links_removed?.count&&n.push(`unlinked ${Wy(t.links_removed,"item","items")}`),0===n.length&&t.canvas_changed&&n.push("changed the drawing"),0===n.length&&n.push("saved with no change")}const r=n.join(", ");return r.charAt(0).toUpperCase()+r.slice(1)}function Jy(e){if("mcp"!==e.source)return"user";const t=String(e.agent_label??"Claude").split(" ")[0].toLowerCase();return`mcp_${["claude","cursor","copilot"].includes(t)?t:"claude"}`}function Gy(e){return{id:String(e.id),event_type:e.event_type,changed_by:e.changed_by,changed_by_name:e.changed_by_name,changed_at:e.changed_at,actor:Jy(e),source:e.source,agent_label:e.agent_label,version:e.version,fields_changed:Object.keys(e.summary??{}).filter(e=>"truncated"!==e),summary_line:By(e),summary:e.summary??{}}}var Qy=D({"src/core/model-design-history.ts"(){hs(),Ae(),Sn(),Ny=3,Py="id, design_id, version, changed_by, changed_by_name, changed_at, event_type, source, agent_label, summary",Fy=(e,t,n)=>1===e?`${t}`:`${e} ${n}`,Uy=e=>Ri.test(e)}}),Ky={};async function Yy(e){const t=e.offset??0;try{const n=await _u();if(Uy(e.item_id)){const r=function(e,t){return ve(e,"atoms_get_model_design",t)}(ke(Fe(),e.project_id),e);if(r)return Yc(r);const a=await async function(e,t,n,r,a=0){const i=await e.from("model_designs").select("id, display_id").eq("project_id",t).eq("display_id",n.trim().toUpperCase()).maybeSingle();if(i.error)throw i.error;const s=i.data;if(!s)return{design:null};const o=await un(e.from("model_design_history").select(Py,{count:"exact"}).eq("design_id",s.id).order("id",{ascending:!1}).range(a,a+r));if(o.error)throw o.error;return{design:s,rows:o.data??[],total:"number"==typeof o.count?o.count:(o.data??[]).length}}(n,e.project_id,e.item_id,e.limit,t);return null===a.design?Yc({status:"error",code:"not_found",retryable:!1,message:`${e.item_id} is not a model design of this project.`,next_steps:["Use atoms_list_model_designs to see this project's model designs and their MD ids"]}):Kc(bc(a.rows.slice(0,e.limit).map(Gy),kh(a.total,e.limit,a.rows.length,t)))}const{rows:r,total:a}=await async function(e,t,n,r,a=0){const{data:i,error:s,count:o}=await un(e.from("item_revisions").select("id, revision_number, fields_snapshot, valid_from, valid_to, changed_by, event_source, event_session_id, diff_summary",{count:"exact"}).eq("item_id",n).eq("project_id",t).order("revision_number",{ascending:!1}).range(a,a+r));if(s)throw new Error(s.message);const l=i??[];return{rows:l,total:o??a+l.length}}(n,e.project_id,e.item_id,e.limit,t);if(r.length>0||t>0&&a>0){const i=r,s=function(e,t,n,r,a){const i=e.slice(0,n),s=new Map(i.map((e,t)=>[String(e.id),t])),o=i.map(()=>[]);for(const e of t){const t=s.get(String(e.id).split(":")[0]);void 0!==t&&o[t].push(e)}const l=[],d=[];for(const e of o){if(d.length>0&&l.length+e.length>n)break;l.push(...e),d.push(l.length)}const c=d.length,u=e.length>c;return{entries:l,meta:{total_count:c>0?Math.max(a,r+c):a,limit:n,offset:r,has_more:u,...u?{next_offset:r+c}:{}},resume:e=>{const t=r+Math.max(1,d.filter(t=>t<=e).length);return{meta:{next_offset:t},next:`offset=${t}`}}}}(i,bh(i,await async function(e,t,n,r){const a=new Map,i=function(e){const t=new Set;for(const n of e){const e=wh(n).author;e&&"object"==typeof e||!n.event_session_id||"mcp"!==n.event_source&&"restore"!==n.event_source||t.add(n.event_session_id)}return[...t].sort()}(r);if(0===i.length)return a;try{const{data:r,error:s}=await e.from("change_history").select("session_id, actor").eq("project_id",t).eq("item_id",n).in("session_id",i).like("actor","mcp_%").limit(1e3);if(s)return a;for(const e of r??[])"string"!=typeof e.session_id||"string"!=typeof e.actor||a.has(e.session_id)||a.set(e.session_id,e.actor)}catch{}return a}(n,e.project_id,e.item_id,i),await async function(e,t,n,r){const a=r.filter(e=>null===hh(e.diff_summary)&&"user"!==vh(e));if(0===a.length)return new Map;try{const i=a[a.length-1].valid_from,{data:s,error:o}=await e.from("change_history").select("changed_at, changed_by, actor, reason").eq("project_id",t).eq("item_id",n).like("actor","mcp_%").not("reason","is",null).gte("changed_at",i).order("changed_at",{ascending:!1}).limit(1e3);return o?new Map:function(e,t){const n=new Map,r=t.filter(e=>"string"==typeof e.actor&&e.actor.startsWith("mcp_")&&null!==fh(e.reason)).map(e=>({at:Date.parse(e.changed_at),by:e.changed_by,reason:e.reason})).sort((e,t)=>t.at-e.at);return e.forEach((t,a)=>{if(null!==hh(t.diff_summary)||"user"===vh(t))return;const i=Date.parse(t.valid_from),s=a>0?Date.parse(e[a-1].valid_from):1/0,o=r.find(e=>e.by===t.changed_by&&e.at>=i&&e.at<s);o&&n.set(t.id,o.reason)}),n}(r,s??[])}catch{return new Map}}(n,e.project_id,e.item_id,i)),e.limit,t,a);return Kc(bc(s.entries,s.meta),{paging:{resume:s.resume}})}const{rows:i,total:s}=await async function(e,t,n,r,a=0){const{data:i,error:s,count:o}=await un(e.from("change_history").select("*",{count:"exact"}).eq("item_id",n).eq("project_id",t).order("changed_at",{ascending:!1}).range(a,a+r));if(s)throw new Error(s.message);const l=i??[];return{rows:l,total:o??a+l.length}}(n,e.project_id,e.item_id,e.limit,t);return Kc(bc(i.slice(0,e.limit).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)");const a=fh(e.reason);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,...null!==a?{reason:a}:{}}}),kh(s,e.limit,i.length,t)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(Ky,{getHistoryHandler:()=>Yy});var Zy,Xy,ew=D({"src/tools/get-history.ts"(){xu(),Wg(),Ah(),tu(),Qy(),Ae(),We()}}),tw=D({"src/core/link-kinds.ts"(){Zy={parent:{word:"parent of",required:!0},verifies:{word:"verified by",required:!0},related:{word:"related to",required:!1},mitigates:{word:"mitigates",required:!0,turnedWord:"mitigated by"},allocated_to:{word:"allocated to",required:!1,turnedWord:"allocated from"},event_hazard:{word:"cites hazard",required:!0,turnedWord:"cited by"},event_goal:{word:"cites goal",required:!0},affects:{word:"affects",required:!1},traces_to:{word:"traces to",required:!1,turnedWord:"traced by"},decomposes_to:{word:"decomposes to",required:!0}},Xy={child:"parent",verified_by:"verifies",mitigated_by:"mitigates",allocated_from:"allocated_to",hazard_events:"event_hazard",goal_events:"event_goal",affected_by:"affects",traced_by:"traces_to",decomposed_from:"decomposes_to"}}});function nw(e){return"parent"===e.type?{from_id:e.to_id,to_id:e.from_id,type:"child"}:"verifies"===e.type?{from_id:e.to_id,to_id:e.from_id,type:"verified_by"}:e}function rw(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function aw(e){const t=lw(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:"function"===e.type?`{{"${t}"}}`:"hazard"===e.type?`>"${t}"]`:"goal"===e.type?`[/"${t}"/]`:`["${t}"]`}function iw(e){const t="child"===e.type?"parent":"verified_by"===e.type?"verifies":Xy[e.type];return t&&"child"!==e.type&&"verified_by"!==e.type?{kind:t,from:e.to_id,to:e.from_id}:t?{kind:t,from:e.from_id,to:e.to_id}:Zy[e.type]?{kind:e.type,from:e.from_id,to:e.to_id}:null}function sw(e){const t=iw(e);if(!t)return null;const{word:n,required:r}=Zy[t.kind],a=rw(t.from),i=rw(t.to);return"related"===t.kind?`${a} -.-|${n}| ${i}`:`${a} ${r?"--\x3e":"-.->"}|${n}| ${i}`}function ow(e){const t=iw(e);return t?`${t.from}:${t.kind}:${t.to}`:`${e.from_id}:${e.type}:${e.to_id}`}function lw(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var dw=D({"src/core/mermaid.ts"(){tw()}}),cw={};async function uw(e){try{if(e.baseline_id&&e.as_of)return Yc(Ic("baseline_id and as_of are mutually exclusive"));const t=await _u();let n,r,a;if(e.baseline_id){const r=await Ng(t,e.baseline_id);if(!r)return Yc(Ic("Baseline not found"));if(r.project_id!==e.project_id)return Yc(Ic("Baseline does not belong to this project"));n=yn(e.baseline_id)}else e.as_of&&(n=gn(Mg(e.as_of)));if(n){r=(await Fg(t,e.project_id,n)).map(Pg).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),a=Vm(r,[])}else r=await An(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn),a=Vm(r,await An(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn));return Kc(bc(function(e){const t=e.items,n=(e.relationships??[]).map(nw),r=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${lw(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,d=[],c=[];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),d.push(` ${rw(t)}${aw(u)}`);for(const d of n){if(d.from_id!==t)continue;const n=a.get(d.to_id);if(!n)continue;if(!e.includeTests&&"test-case"===n.type)continue;if(i+1>r)continue;const u=sw(d);if(!u)continue;const p=ow(d);l.has(p)||(l.add(p),c.push(` ${u}`),o.has(d.to_id)||s.push({id:d.to_id,depth:i+1}))}}}return{mermaid:["graph TD",...d,...c].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")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(cw,{exportMermaidHandler:()=>uw});var pw,mw,_w=D({"src/tools/export-mermaid.ts"(){xu(),Wg(),tu(),dw(),Rg(),kr()}}),fw=D({"src/core/item-types.ts"(){pw={requirement:{idPrefix:"REQ",label:"Requirement"},"test-case":{idPrefix:"TC",label:"Test Case"},note:{idPrefix:"NOTE",label:"Note"},table:{idPrefix:"TABLE",label:"Table"},analysis:{idPrefix:null,label:"Analysis"},function:{idPrefix:"FN",label:"Function"},hazard:{idPrefix:"HAZ",label:"Hazard"},goal:{idPrefix:"SG",label:"Safety goal"}}}});function hw(e){const t=function(e){return Object.prototype.hasOwnProperty.call(pw,e)?pw[e]:void 0}(e);if(!t)throw new Error(`Unknown item type "${e}": it has no id prefix`);if(null===t.idPrefix)throw new Error(`Item type "${e}" has no single id prefix (its ids come from its scheme)`);return t.idPrefix}function gw(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 yw(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>mw)throw new Error(`ID generation failed: at most ${mw} 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 ww=D({"src/core/item-id-reservation.ts"(){fw(),mw=1e3}});async function vw(e,t){const n=await Ra(e,t);return null===n?"unreadable":n?"ops":"main"}function bw(){return Yc(Ta())}async function kw(e){const t=[...e.ops];let n=e.preFound??new Map;!e.preFound&&e.deterministic&&t.length>0&&(n=await Ba(e.client,e.projectId,t));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 ty(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 Ja(e.client,e.projectId,a.answers,t),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,...Ma(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 d;return l.length>0&&(d=await Qr(e.client,e.projectId,l)),{outcome:await ia({answers:s,ops:t,skippedItems:o,...d?{openRevisions:d}:{},...e.labels?{labels:e.labels}:{}}),answers:s,results:a.results,chunks:a.chunks,...void 0!==a.error?{error:a.error}:{},found:n}}function jw(e,t,n,r){if(0===e.not_applied.length)return Kc(bc({...t,...r??{},...ha(e),...n?.chunks?{chunks:n.chunks}:{}}));const{isError:a,result:i}=fa(e,{...r??{},...ny(n??{})});return a?Yc(i):Kc(i)}function Sw(e,t,n){return e&&!t?Ca(e,n):null}function Aw(e){return null==e?[]:(Array.isArray(e)?[...e]:[e]).filter(e=>"string"==typeof e&&e.length>0)}function $w(e){return e.some(e=>void 0!==e.acceptance_revoked&&null!==e.acceptance_revoked&&!1!==e.acceptance_revoked)}async function xw(e){const t=await ta({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(ea(t.path));a&&r.push(ra({op_id:ya(),kind:"set",item_id:e.itemId,path:[...t.path],value:t.value},a))}return{ops:r,refusals:t.refusals}}async function Iw(e){const t=yu(),n=WA(),r=Sa(e.contents),a=[],i=[],s=e.key?await Promise.all(e.contents.map(e=>Ua(e))):e.contents.map(()=>{});for(let s=0;s<e.contents.length;s+=1)a.push(await ga(e.key?va({userId:t,projectId:e.projectId,family:ja(e.tool),key:e.key,itemIdOrK:s}):wa({userId:t,projectId:e.projectId,content:e.contents[s],k:r[s],sessionId:n}))),i.push(await ga(e.key?va({userId:t,projectId:e.projectId,family:ja(e.tool),key:e.key,itemIdOrK:`link:${s}`,path:["relationships","children"]}):[t,e.projectId,"create_link",a[s]]));return{create:a,link:i,hash:s,createRefs:a.map((e,t)=>({op_id:e,content_hash:s[t]}))}}function qw(e,t){for(const n of e){const e=t.create.indexOf(n.op_id);e>=0&&t.hash[e]&&(n.content_hash=t.hash[e])}return e}async function Ow(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{tokens:a,unread:!1};let i;try{i=await Kr(e,t,r.map(e=>e.revision_id))}catch{return{tokens:a,unread:!0}}for(const e of r){const t=i.get(e.revision_id);t&&a.set(e.item_id,await Wr(t,"all"))}return{tokens:a,unread:!1}}async function Ew(e){let t=0,n=0;for(;;){let r;try{r=await kw({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 zw(e,t,n){return e.answers.find(e=>e.status===t&&(void 0===n||e.reason===n))}var Mw,Rw,Tw=D({"src/tools/_ops.ts"(){xu(),JA(),ai(),tu(),py()}});function Cw(e,t){const n=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(n){const t=n.toLowerCase();if("1"===t||"true"===t||"all"===t)return!0;if(n.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!ke(Fe(),t).require_confirmation_for.includes(e)}function Dw(e,t=Mw){const n=Date.now()+t,r={...e,exp:n},a=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${a}.${R.default.createHmac("sha256",Rw).update(a).digest("base64url")}`,expires_at:new Date(n).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function Hw(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=R.default.createHmac("sha256",Rw).update(n).digest("base64url"),i=Buffer.from(r,"utf8"),s=Buffer.from(a,"utf8");if(i.length!==s.length||!R.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 Nw(e){if(Array.isArray(e))return e.map(Nw);if(null!==e&&"object"==typeof e){const t={};for(const n of Object.keys(e).sort())t[n]=Nw(e[n]);return t}return e}function Pw(e){const t=JSON.stringify(Nw(e));return R.default.createHash("sha256").update(t).digest("base64url").slice(0,16)}var Fw,Uw=D({"src/middleware/confirmation.ts"(){We(),Ae(),Mw=6e4,Rw=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:R.default.randomBytes(32).toString("base64url")})()}});function Lw(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=>ml(e)===ml(i))??s.find(e=>r(e)===a)??t}function Ww(e,t){return"locked"===t?`Level "${e}" is not in the project's level list, and the MCP policy of this project's organization does not let you 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 Vw=D({"src/core/levels.ts"(){pd(),kd(),Fw="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."}}),Bw={};function Jw(e){const t=vc(e??"");return"sub-system"===t?"subsystem":t}async function Gw(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 Qw(e,t){return{levels:await Gw(e,t)}}async function Kw(e,t){return(await An(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn)).map(e=>e.data?.tags?.level)}async function Yw(e,t,n){const r=vc(n);return r?Lw(n,r,await Gw(e,t),Jw):r}async function Zw(e,t,n){const r=vc(n??""),a=Jw(r);if(!r)return"none";try{const{levels:n}=await Qw(e,t);if(n.some(e=>Jw(e)===a))return"present";if(!G(ke(Fe(),t),"atoms_create_level").allowed)return"locked";if(!0===await Ra(e,t)){const n={op_id:ya(),kind:"add",item_id:null,path:["taxonomy","levels"],value:r},{run:a}=await Ew({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 Xw(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 ev(e){try{const t=await _u(),{levels:n}=await Qw(t,e.project_id),r=function(e,t,n){const r=new Set(e.map(e=>ml(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(ml(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 Kw(t,e.project_id),Jw),a=r.some(e=>void 0!==e.items_not_shown);return Kc(bc({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?` ${Fw}`:"")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}async function tv(e,t){let n;try{const r=await _u();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const a=t??await vw(r,e.project_id);if("unreadable"===a)return bw();n=a;const{levels:i}=await Qw(r,e.project_id),s=vc(e.name),o=Jw(s);if(!s)return Yc(Ic("Level name cannot be empty."));if(i.some(e=>Jw(e)===o))return Yc(Ic(`Level "${s}" already exists in this project.`));if("ops"===a){const t={op_id:ya(),kind:"add",item_id:null,path:["taxonomy","levels"],value:s},{run:n}=await Ew({client:r,projectId:e.project_id,op:t});if(n.answers.some(e=>"noop"===e.status))return Yc(Ic(`Level "${s}" already exists in this project.`));if(n.outcome.not_applied.length>0)return jw(n.outcome,{},n);const a=(await Gw(r,e.project_id)).findIndex(e=>Jw(e)===o),l=`L${a>=0?a:i.length}`;return jw(n.outcome,{level:{name:s,prefix:l},message:`Level "${s}" registered as ${l}. Tag items with level="${s}".`},n)}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=>Jw(e)===o);if(void 0!==l){const e=`L${a.indexOf(l)}`;return Kc(bc({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 d=a.indexOf(s),c=`L${d>=0?d:i.length}`;return Kc(bc({level:{name:s,prefix:c},message:`Level "${s}" registered as ${c}. Tag items with level="${s}".`}))};return await l()}catch(r){const a=Sw(n,t,r);return a?tv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}async function nv(e,t){let n;try{const r=await _u();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const a=t??await vw(r,e.project_id);if("unreadable"===a)return bw();n=a;const i=Jw(Jc(e.name));if(!i)return Yc(Ic("Level name cannot be empty."));const{levels:s}=await Qw(r,e.project_id),o=s.filter(e=>Jw(e)===i),l="ops"===a?0:(await Kw(r,e.project_id)).filter(e=>Jw(e)===i).length;if(0===o.length&&0===l&&"ops"!==a)return Yc(Sc("Level",e.name));const d=o[0]??e.name;if(l>0)return Yc(Ic(`Level "${d}" is used by ${l} item${l>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`));if(Cw("atoms_delete_level",e.project_id)){const t={tool:"atoms_delete_level",project_id:e.project_id,target:i};if(!e.confirmation_token){const e=Dw(t);return Kc(bc({status:"confirmation_required",preview:{level_name:d,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=Hw(e.confirmation_token,t);if(!n.valid)return Yc(Ic(`confirmation_token rejected: ${n.reason}`))}if("ops"===a){const t={op_id:ya(),kind:"remove",item_id:null,path:["taxonomy","levels"],value:d},{run:n}=await Ew({client:r,projectId:e.project_id,op:t}),a=zw(n,"invalid","level_in_use");if(a){const e="number"==typeof a.count?a.count:1;return Yc(Ic(`Level "${d}" is used by ${e} item${e>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`))}if(zw(n,"deleted"))return Yc(Sc("Level",e.name));if(n.outcome.not_applied.length>0)return jw(n.outcome,{},n);const i=await Gw(r,e.project_id),o=_l(s,i);return jw(n.outcome,{level:{name:d},remaining_levels:i,message:`Level "${d}" deleted. Every later level's L# shifts down by one.`+(o?" "+o:"")},n)}const c=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=_l(s,a);return Kc(bc({level:{name:d},remaining_levels:a,message:`Level "${d}" deleted. Every later level's L# shifts down by one.`+(i?" "+i:"")}))};return await c()}catch(r){const a=Sw(n,t,r);return a?nv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}async function rv(e,t){let n;try{const r=await _u();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const a=t??await vw(r,e.project_id);if("unreadable"===a)return bw();n=a;const i=Array.isArray(e.names)?e.names.map(e=>Jc(String(e??"")).trim()).filter(e=>e.length>0):[];if(0===i.length)return Yc(Ic("names must be a non-empty array of the project's existing levels, in the order you want them."));const{levels:s}=await Qw(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=>ml(t)===ml(e))??a(t=>""!==n(t)&&n(t)===n(e));if(null===t)return null;i.push(t)}return i}(s,i,Jw);if(!o)return Yc(Ic(`names must list every existing level exactly once. Levels: ${s.length>0?s.join(", "):"(none)"}`));if("ops"===a){const t=Xw(s,o);if(t.length>0){const n=t.map(e=>({op_id:ya(),kind:"move_row",item_id:null,path:["taxonomy","levels"],row_id:e.level,value:{after:e.after}})),a=await kw({client:r,projectId:e.project_id,ops:n});if(zw(a,"deleted"))return Yc(Sc("Level",e.names.join(", ")));if(a.outcome.not_applied.length>0)return jw(a.outcome,{},a)}const n=await Gw(r,e.project_id),a=_l(s,n);return Kc(bc({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=_l(s,a);return Kc(bc({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=Sw(n,t,r);return a?rv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}H(Bw,{createLevelHandler:()=>tv,deleteLevelHandler:()=>nv,ensureLevelRegistered:()=>Zw,getProjectLevels:()=>Gw,levelKey:()=>Jw,levelMoves:()=>Xw,listLevelsHandler:()=>ev,reorderLevelsHandler:()=>rv,storedLevelSpelling:()=>Yw});var av,iv,sv,ov,lv,dv,cv,uv,pv=D({"src/tools/levels.ts"(){xu(),ai(),Tw(),Uw(),tu(),pd(),re(),Ae(),We(),kr(),Vw()}});function mv(e,t,n){const[r,a]="affects"===n?[e,t]:[t,e];return r.startsWith(ov)&&a.startsWith(lv)?null:`affects/affected_by links a security risk analysis row (${ov}n) to an ISO 14971 risk row (${lv}n) only: "${e}" -> "${t}" is not that pair.`}function _v(e,t,n){const r=[t,n].filter(dv);if(0===r.length)return null;const a=`"${t.id}" -> "${n.id}"`;if(cv(e)){const r=dv(t)?n:t;return dv(r)?`${e} links a requirement and a Function: ${a} joins two Functions. Decompose a Function with parent and child links between Functions instead.`:"requirement"!==r.type?`${e} links a requirement and a Function: "${r.id}" is a ${r.type}, not a requirement. Only requirements are allocated to a Function.`:r.isAnalysisRow?`${e} links a requirement and a Function: "${r.id}" is an analysis row. An analysis row names its Function in analysis_props.source_function_id, not by an allocation link.`:null}if("parent"===e||"child"===e){if(dv(t)&&dv(n))return null;const r=dv(t)?n:t;return`${e} links between Functions only: ${a} joins a Function to "${r.id}", a ${r.type}. To tie a requirement to a Function, use atoms_link_items with type allocated_to.`}return uv(e)?`${e} links never have a Function at either end: "${r[0].id}" is a Function (${a}). A Function is not verified, mitigated or affected directly: link its allocated requirements instead.`:null}function fv(e,t,n,r){return _v("parent",{id:e,type:t},{id:n,type:r})}async function hv(e,t,n,r){const a=[...new Set(n)],i=await r(a,n=>e.from("items").select("id, type, data").eq("project_id",t).is("deleted_at",null).in("id",n)),s=e=>{const t=e.data?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]},o=i.filter(e=>"requirement"===e.type).flatMap(s),l=new Map;if(o.length>0){const n=await r([...new Set(o)],n=>e.from("items").select("id, type").eq("project_id",t).in("id",n));for(const e of n)l.set(e.id,e.type)}const d=new Map;for(const e of i)d.set(e.id,{id:e.id,type:e.type,isAnalysisRow:"requirement"===e.type&&s(e).some(e=>"analysis"===l.get(e))});return d}async function gv(e,t,n,r){const a=n.filter(e=>"add"===e.action),i=a.filter(e=>cv(e.type)||uv(e.type)||"parent"===e.type||"child"===e.type);if(0===i.length)return null;const s=e=>e.startsWith(av),o=a.some(e=>cv(e.type));if(!o&&!i.some(e=>s(e.from_id)||s(e.to_id)))return null;if(o){const n=c_(await l_(e,t));if(n)return{toolError:n}}const l=await async function(e,t,n,r){const a=n.filter(e=>"add"===e.action&&(cv(e.type)||uv(e.type)||"parent"===e.type||"child"===e.type));if(0===a.length)return null;const i=await hv(e,t,a.flatMap(e=>[e.from_id,e.to_id]),r);for(const e of a){const t=i.get(e.from_id),n=i.get(e.to_id);if(!t||!n)continue;const r=_v(e.type,t,n);if(r)return r}return null}(e,t,n,r);return l?{validation:l}:null}var yv=D({"src/core/link-pairs.ts"(){k_(),pd(),av="FN-",iv=["allocated_to","allocated_from"],sv=["verifies","verified_by","mitigated_by","mitigates","affects","affected_by"],ov=`${Ro.security_tir57}-`,lv=`${Ro.hazard_iso14971}-`,dv=e=>"function"===e.type,cv=e=>iv.includes(e),uv=e=>sv.includes(e)}});async function wv(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 async function(e,t){const n=await qg(e,"mcp_field_value_counts",{p_project_id:t});if(!n)return null;const r=n.data;if(null===r||"object"!=typeof r||Array.isArray(r))return null;const a=[];for(const[e,t]of Object.entries(r)){const n=xg(t);if(null===n)return null;a.push({key:e,items:n})}return a}(e,t);if(i){for(const{key:e,items:t}of i){const n=a.get(e.toLowerCase());n&&(r[n]+=t)}return r}const s=await An(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn);for(const e of s){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}var vv,bv,kv,jv,Sv=D({"src/core/project-field-counts.ts"(){kr(),zg()}});function Av(e){if(!Array.isArray(e))return;const t=new Set(e.filter(e=>"string"==typeof e&&kv.has(e)));return 0!==t.size?vv.filter(e=>t.has(e)):void 0}var $v,xv,Iv,qv=D({"src/core/field-scope.ts"(){vv=["requirement","test-case","note","table","function"],bv=["requirement","test-case","note","table"],kv=new Set(vv),jv=e=>JSON.stringify({type:e.type,options:e.options??[],appliesTo:e.appliesTo??null})}}),Ov={};async function Ev(e,t){const{data:n,error:r}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(r)throw r;return zv(n?.fields)}function zv(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&&xv.has(e.type)?e.type:"text",o=Array.isArray(e.options)?Lv(e.options):[],l=Av(e.appliesTo??e.applies_to);t.push({name:a,type:s,..."select"===s?{options:o}:{},...l?{appliesTo:l}:{}})}return t}function Mv(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(!xv.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=Lv(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 Rv(e,t){const n=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!n.has(e.toLowerCase()))}function Tv(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 Cv(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 Dv(e,t,n=new Set,r){const a=Rv(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(Cv(r,e,a)){a.trim()&&(i[t.name]=a);continue}const o=Pv(t,a,n);if(o.error)return{error:o.error};o.value&&(i[t.name]=o.value)}return{fields:i}}function Hv(e){return/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function Nv(e,t){const n=t??{};let r=`Field "${e}" defined. Set values with atoms_update_item fields={"${e}": "<value>"}.`;if("number"==typeof n.values_outside_options&&n.values_outside_options>0){const t=n.values_outside_options;r+=` Note: ${t} ${1===t?"item holds a":"items hold"} ${e} ${1===t?"value":"values"} that ${1===t?"is":"are"} not one of its options; ${1===t?"it is":"they are"} kept.`}const a=(Array.isArray(n.skipped_projects)?n.skipped_projects:[]).filter(e=>!!e&&"object"==typeof e&&"number"==typeof e.incompatible_items);return a.length>0&&(r+=` Not added to ${a.map(e=>`${String(e.name)} (${e.incompatible_items} items)`).join(", ")}: items there hold ${e} values this type cannot take.`),r}function Pv(e,t,n){const r=t.trim();if(!r)return{value:""};if(r.length>Iv)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 Uv(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 Hv(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);if(!function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(t.url))return{error:`${e.name} must be an http(s) URL.`};const n=function(e,t){const n=t.trim();return n?JSON.stringify({label:e.trim(),url:n}):""}(t.label,t.url);return n.length>Iv?{error:`${e.name} is too long.`}:{value:n}}}}async function Fv(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(Cv(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(!Uv(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:yu()});if(i)return{error:i.message};!0===a&&o.add(n)}return Dv(n,r,o,a)}function Uv(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 Lv(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 Wv(e){try{const t=await _u(),n=await Ev(t,e.project_id),r=await wv(t,e.project_id,n),a=qd(n,e.offset,e.limit);return Kc(bc({fields:a.rows.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},a.meta),{paging:{list:"fields"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}async function Vv(e,t){let n;try{const r=await _u();try{await Su(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Yc(tn("project"));throw e}const a=t??await vw(r,e.project_id);if("unreadable"===a)return bw();n=a;const{data:i}=await r.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),s=zv(i?.fields),o=Av(e.appliesTo),l={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:Lv(e.options??[])}:{},...o?{appliesTo:o}:{}},d=Mv(l,function(e,t,n){if(!n)return e;const r=t.name.toLowerCase();return e.some(e=>e.name.toLowerCase()===r&&jv(e)===jv(t))?e.filter(e=>e.name.toLowerCase()!==r):e}(s,l,"ops"===a));if(d)return Yc(Ic(d));const c=function(e,t){return"organization"!==e?null:t&&0!==t.length?bv.every(e=>t.includes(e))?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(c)return Yc(Ic(c));if(o?.includes("function")){const t=c_(await l_(r,e.project_id));if(t)return Yc(t)}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:yu()}):await r.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"create",p_field:"ops"===a?{...l,op_id:ya()}:l,p_field_name:null,p_actor_user_id:yu()});if(p)throw p;return Kc(bc({field:u?.field??l,..."organization"===e.scope?{created_projects:u?.created_projects??[],skipped_projects:u?.skipped_projects??[]}:{},..."number"==typeof u?.values_outside_options?{values_outside_options:u.values_outside_options}:{},message:Nv(l.name,u)}))}catch(r){const a=Sw(n,t,r);return a?Vv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(r))}}async function Bv(e,t){let n;try{const r=await _u();try{await Su(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Yc(tn("project"));throw e}const a=t??await vw(r,e.project_id);if("unreadable"===a)return bw();n=a;const i=e.name.trim();if(Cw("atoms_delete_field",e.project_id)){const t={tool:"atoms_delete_field",project_id:e.project_id,target:i};if(!e.confirmation_token){const n=await wv(r,e.project_id,[{name:i}]),a=Dw(t);return Kc(bc({status:"confirmation_required",preview:{field_name:i,items_with_values:n[i]??0},confirmation_token:a.token,expires_at:a.expires_at,expires_in_seconds:a.expires_in_seconds,message:`Re-call atoms_delete_field with the same project_id, name, and confirmation_token within ${a.expires_in_seconds}s to execute.`}))}const n=Hw(e.confirmation_token,t);if(!n.valid)return Yc(Ic(`confirmation_token rejected: ${n.reason}`))}const{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:ya()}:null,p_field_name:i,p_actor_user_id:yu()});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),Kc(bc({deleted:s?.deleted??i}))}catch(r){const a=Sw(n,t,r);return a?Bv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(r))}}async function Jv(e){try{const t=await _u();try{await Su(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Yc(tn("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 Yc(Ic("names must be a non-empty array of existing field names, in the order you want them"));const r=await Ev(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 Yc(Ic(`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:yu()});if(o)throw o;return Kc(bc({fields:zv(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e))}}H(Ov,{PROJECT_FIELD_TYPES:()=>$v,PROJECT_FIELD_VALUE_MAX:()=>Iv,canonicalizeFieldKeys:()=>Tv,createFieldHandler:()=>Vv,createdFieldMessage:()=>Nv,deleteFieldHandler:()=>Bv,findUnknownFieldNames:()=>Rv,getProjectFields:()=>Ev,isProjectFieldNumber:()=>Hv,isStoredFieldValue:()=>Cv,listFieldsHandler:()=>Wv,normalizeProjectFields:()=>zv,reorderFieldsHandler:()=>Jv,validateAndCanonicalizeFieldValues:()=>Dv,validateProjectFieldDefinition:()=>Mv,validateProjectFieldValuesForWrite:()=>Fv});var Gv=D({"src/tools/fields.ts"(){xu(),tu(),Ud(),Sv(),an(),ai(),Uw(),Tw(),k_(),qv(),$v=["text","long","bool","date","person","select","number","link"],xv=new Set($v),Iv=2e3}}),Qv={};async function Kv(e){try{const t=await _u();try{await ju(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const n=await Zg(t,e.project_id);if(null===n)return Yc(Ta());if(e.type=bf(e.type),kf(e.type)){const n=await Af(t,e.project_id);if(n)return Yc(n);const r="goal"===e.type?Rf(Object.keys(e.fields??{})):[];if(r.length>0)return Yc(Ic(Tf("A Safety goal",r),uc))}e.title=Jc(e.title),void 0!==e.body&&(e.body=Jc(e.body)),void 0!==e.summary&&(e.summary=Jc(e.summary)),void 0!==e.level&&(e.level=Jc(e.level)),e.domains&&(e.domains=e.domains.map(e=>Jc(e)));const r=(e.domains??[]).map(vc).filter(e=>e.length>0),a=void 0!==e.level?await Yw(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=od(r,sd(n?.function_tags),vc);if(s.length>0)return Yc(Ic(ld(s),uc));if(i.length>0){const e=new Set(i.map(vc).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return Yc(Ic(`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(()=>(Gv(),Ov)),a=await n(t,e.project_id),s=await r(t,e.project_id,a,e.fields);if(s.error)return Yc(Ic(s.error));i=s.fields}if(void 0!==e.req_type){const t=Bu(e.req_type,e.type);if(t)return Yc(Ic(t,uc))}if("function"===e.type){const n=c_(await l_(t,e.project_id));if(n)return Yc(n);const r=await async function(e,t,n,r,a){if(0===r.length)return null;const i=await hv(e,t,r,a);for(const e of r){const t=i.get(e);if(!t)continue;const r=fv("the new item",n,t.id,t.type);if(r)return r}return null}(t,e.project_id,e.type,e.parent_ids??[],En);if(r)return Yc(Ic(r))}const s={sanitizedDomains:r,sanitizedLevel:a,canonicalFields:i};return await Da(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=yu(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n,o=[...new Set(t.parent_ids??[])],l=$a({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}),d=t.idempotency_key,c=ja("atoms_create_item"),u=await ga(d?va({userId:r,projectId:t.project_id,family:c,key:d,itemIdOrK:0,path:[]}):wa({userId:r,projectId:t.project_id,content:l,k:0,sessionId:WA()})),p=d?await Ua(l):void 0,m=(await Ba(e,t.project_id,[{op_id:u,content_hash:p}])).get(u);if(m&&("applied"===m.status||"noop"===m.status)&&m.item_id)return Kc(bc({id:m.item_id,type:t.type,title:t.title,project_id:t.project_id,replayed:!0,message:yr,seq:m.seq??null}));const _=(await yw(e,t.project_id,{[hw(t.type)]:1}))[hw(t.type)][0],f={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}:{}},h=[{op_id:u,kind:"create_item",item_id:_,path:[],value:{type:t.type,title:t.title,data:f},...p?{content_hash:p}:{}}];for(const e of o)h.push({op_id:d?await ga(va({userId:r,projectId:t.project_id,family:c,key:d,itemIdOrK:0,path:["relationships","parents","add",e]})):ya(),kind:"add",item_id:_,path:["relationships","parents"],value:e});const g=await ty(e,t.project_id,h,{mode:"single"});if(void 0!==g.error&&0===g.results.length)throw g.error;const y=await Ja(e,t.project_id,g.answers,h),w=await ay({client:e,projectId:t.project_id,answers:y,ops:h,results:g.results,relooked:!0});await oy(e,t.project_id,h,y,"created");const v=y.find(e=>e.op_id===u);if("invalid"===v?.status&&"op_id_reused"===v.reason)return Yc(jc(hr,["Send the call again with a new idempotency_key, or without one"],{code:"op_id_reused",retryable:!1}));if(w.not_applied.length>0)return sy(w,{id:_,type:t.type});const b=v?.item_id??_,k=!0===v?.replayed,j=v?.revision_id??null;let S,A;if(j){const n=await Kr(e,t.project_id,[j]).then(e=>e.get(j),()=>null);null===n?A=gr:n&&(S=await Wr(n,"all"))}const $={id:b,type:t.type},x={...S?{base_token:S}:{},...ha(w),...k?{replayed:!0,message:yr}:{},...A?{warning:A}:{}};return!1===t.echo?Kc(bc({...$,...x})):Kc(bc({...$,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,...x}))}(t,e,s):async function(e,t,n){const r=yu(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n;{const n=hw(t.type),l=async()=>(await yw(e,t.project_id,{[n]:1}))[n][0],d=(new Date).toISOString(),c=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:d,created_by:r,updated_at:d,updated_by:r}}),u=n=>Jd(()=>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:WA()??null,p_diff_summary:null}),{scope:t.project_id});let p=await l(),m=c(p),{error:_}=await u(m);if(_&&(o=_)&&/^item_exists\b/.test(String(o.message??"").trim())&&(p=await l(),m=c(p),({error:_}=await u(m))),ey("main",_),_)throw new Error(_.message);const f=i?Ww(i,await Zw(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 Jd(()=>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"}),{scope:t.project_id,afterWrite:!0});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 g=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:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===t.echo?Kc(bc({id:p,type:t.type,...f?{level_note:f}:{},...g})):Kc(bc({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}:{},...g}))}var o}(t,e,s))}catch(e){const t=Lc(e);return Yc(t||Uc(e))}}H(Qv,{createItemHandler:()=>Kv});var Yv=D({"src/tools/create-item.ts"(){xu(),ww(),JA(),tu(),pv(),Vw(),pd(),Yu(),k_(),nh(),yv(),kr(),nc(),ai(),py(),tu()}});function Zv(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 Xv(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 eb,tb=D({"src/core/change-control.ts"(){}});var nb,rb,ab=D({"src/core/content-ids.ts"(){eb={row:"r",column:"c",step:"st",param:"p"}}});function ib(e,t){const n=nb[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)+ib(e.slice(r),t.slice(r))}const r=e?nb.indexOf(e[0]):0,a=null!==t?nb.indexOf(t[0]):nb.length;return a-r>1?nb[Math.round(.5*(r+a))]:t&&t.length>1?t.slice(0,1):nb[r]+ib(e.slice(1),null)}function sb(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 ob(e){if(e.length!==sb(e[0]))throw new Error(`invalid integer part of order key: ${e}`)}function lb(e){const t=sb(e[0]);if(t>e.length)throw new Error(`invalid order key: ${e}`);return e.slice(0,t)}function db(e){if(e===rb)throw new Error(`invalid order key: ${e}`);const t=lb(e);if(e.slice(t.length).slice(-1)===nb[0])throw new Error(`invalid order key: ${e}`)}function cb(e){ob(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=nb.indexOf(n[e])+1;t===nb.length?n[e]=nb[0]:(n[e]=nb[t],r=!1)}if(r){if("Z"===t)return`a${nb[0]}`;if("z"===t)return null;const e=String.fromCharCode(t.charCodeAt(0)+1);return e>"a"?n.push(nb[0]):n.pop(),e+n.join("")}return t+n.join("")}function ub(e,t){if(null!==e&&db(e),null!==t&&db(t),null!==e&&null!==t&&e>=t)throw new Error(`${e} >= ${t}`);if(null===e){if(null===t)return`a${nb[0]}`;const e=lb(t),n=t.slice(e.length);if(e===rb)return e+ib("",n);if(e<t)return e;const r=function(e){ob(e);const t=e[0],n=e.slice(1).split(""),r=nb[nb.length-1];let a=!0;for(let e=n.length-1;a&&e>=0;e-=1){const t=nb.indexOf(n[e])-1;-1===t?n[e]=r:(n[e]=nb[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=lb(e),n=e.slice(t.length),r=cb(t);return null===r?t+ib(n,null):r}const n=lb(e),r=e.slice(n.length),a=lb(t),i=t.slice(a.length);if(n===a)return n+ib(r,i);const s=cb(n);if(null===s)throw new Error("cannot increment any more");return s<t?s:n+ib(r,null)}function pb(e,t,n){return ub(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 mb,_b,fb=D({"src/core/order-key.ts"(){ab(),nb="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rb=`A${"0".repeat(26)}`}});function hb(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gb(e,t){return e<t?-1:e>t?1:0}function yb(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)=>yb(e,t[n]));if(hb(e)&&hb(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=>yb(e[n],t[n]))}return!1}function wb(e){return hb(e)&&"string"==typeof e.id?`id:${e.id}`:`json:${vb(e)}`}function vb(e){return Array.isArray(e)?`[${e.map(vb).join(",")}]`:hb(e)?`{${Object.keys(e).filter(t=>void 0!==e[t]).sort(gb).map(t=>`${JSON.stringify(t)}:${vb(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function bb(e,t,n,r={}){if(r.skip?.(e))return[];if(1===e.length&&"relationships"===e[0]?(hb(t)||(t={}),hb(n)||(n={})):2===e.length&&"relationships"===e[0]&&(Array.isArray(t)||(t=[]),Array.isArray(n)||(n=[])),yb(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(wb)),s=new Set(a.map(wb)),o=[];for(const t of r)s.has(wb(t))||o.push({kind:"remove",path:[...e],value:t});for(const t of a)i.has(wb(t))||o.push({kind:"add",path:[...e],value:t});return o}(e,t,n);if(hb(t)&&hb(n)){const a=new Set([...Object.keys(t),...Object.keys(n)]),i=[];for(const s of[...a].sort(gb))0===e.length&&r.ignoreKeys?.has(s)||i.push(...bb([...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 kb(e){const t={};for(const n of Object.keys(e))mb.has(n)||void 0===e[n]||(t[n]=e[n]);return t}function jb(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[ub(null,t)];{let e=ub(null,t);const r=[e];for(let a=0;a<n-1;a+=1)e=ub(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]),d=!0===r.implicitIds&&t.every(e=>"string"!=typeof e.id),c=t.map((e,t)=>"string"==typeof e.id?e.id:r.implicitIds?`p${t+1}`:""),u=new Map;c.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&&d&&(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`${eb[e]}_${n}`}(_b[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])),g=[],y=new Set(m);t.forEach((t,n)=>{""===c[n]||u.get(c[n])!==n||y.has(c[n])||g.push({kind:s,path:[e],base:t,row_id:c[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=pb(w,r,s);w.push(o),v[t]=o,_[t]<0?g.push({kind:a,path:[e],value:kb(n[t]),row_id:m[t],order_key:o}):g.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||g.push(...bb([e,m[a]],kb(t[_[a]]),kb(n[a]),{skip:r.skip}));return g}var Sb,Ab=D({"src/core/content-ops.ts"(){ab(),fb(),mb=new Set(["id","order_key","created_seq"]),_b={steps:"step",params:"param",rows:"row",columns:"column"}}});function $b(e){const t=e?.analysis_props;return t&&"object"==typeof t&&!Array.isArray(t)?t:null}function xb(e,t){if(!0!==$b(e)?.approved)return!1;const n=$b(t?.data);return null!==n&&!0!==n.approved}var Ib=D({"src/core/human-check.ts"(){Sb="approval cleared (a signature never covers content the approver did not see)"}}),qb={};async function Ob(e){try{const n=await _u();try{await ju(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const r=await Zg(n,e.project_id);if(null===r)return Yc(Ta());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?Yc({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 Da(r?"ops":"main",t=>"ops"===t?async function(e,t){const n=yu(),r=Array.isArray(t.updates);if(!r&&!t.item_id)return Yc(Ic("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:d}of a){void 0!==d.asil_confirm_lower&&l.push(Pu(n));const a=await Eb(e,t.project_id,n,d,s),c=cy(d.base_token??(r?t.base_token:void 0));if("entry"in a){o.push({itemId:n,tokens:c,intent:d.intent??t.intent??"edit",...a.entry});continue}const{message:u,path:p,notFound:m,long:_}=a.refusal;if(!r)return Yc(m?Sc("Item",n):Ic(u,_?uc:void 0));if(!i)return Yc(Ic(`Batch stopped at "${n}": ${u.replace(/\.$/,"")}. Nothing was saved.`,_?uc: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 d=new Set(o.map(e=>e.itemId)).size>1?"bulk":"single",c=o.map(e=>({itemId:e.itemId,tokens:e.tokens,paths:e.paths,values:e.values})),{items:u,refusals:p}=await ta({client:e,projectId:t.project_id,requests:c,mode:d}),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(ea(n));if(a)for(const t of zb(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 ga(va({userId:n,projectId:t.project_id,family:ja("atoms_update_item"),key:t.idempotency_key,itemIdOrK:e.item_id??"",path:dy(e)})):ya(),t.idempotency_key&&await La(e),t.reason&&(e.reason=t.reason);let _={answers:[],results:[],notSent:[]};if(m.length>0&&(_=await ty(e,t.project_id,m,{mode:d}),void 0!==_.error&&0===_.results.length))throw _.error;const f=[...l,...p,..._.answers,...Ma(_.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 g=await ay({client:e,projectId:t.project_id,answers:f,ops:m,results:_.results,labels:{stepNumber:e=>h.get(e)}}),y=r?crypto.randomUUID():void 0;if(await oy(e,t.project_id,m,_.answers,"updated",{batch_id:y,reason:t.reason}),g.not_applied.length>0)return sy(g,{...r?{batch_id:y}:{id:t.item_id},...ny(_)});const w=new Map;for(const e of[...g.applied]){if(!e.item_id)continue;const t=ly(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 g.captured)e.item_id&&v.set(e.item_id,iy(e));const b=$w(_.answers)?{acceptance_revoked:!0}:{},k=new Set(_.answers.filter(e=>!0===e.approval_cleared&&e.item_id).map(e=>e.item_id)),j=e=>k.has(e)?{approval_cleared:!0}:{};if(r){const e=o.map(e=>v.has(e.itemId)?null!==v.get(e.itemId)?Zv(e.itemId,v.get(e.itemId)):Xv(e.itemId):{id:e.itemId,updated_fields:w.get(e.itemId)??[],...j(e.itemId)});return Kc(bc({batch_id:y,updated:e.length,results:!1===t.echo?void 0:e,errors:[],...b,...ha(g),...ny(_)}))}const S=t.item_id;if(v.has(S)){const e=v.get(S);return Kc(bc(null!=e?Zv(S,e):Xv(S)))}const A=w.get(S)??[];if(!1===t.echo)return Kc(bc({id:S,updated_fields:A,...j(S),...b,...ha(g)}));const $=await Qr(e,t.project_id,[S]).then(e=>e.get(S),()=>null);if(null===$)return Kc(bc({id:S,updated_fields:A,...j(S),...b,...ha(g),warning:gr}));const x=$?.fields_snapshot??{},I=x.data??{};return Kc(bc({id:S,type:x.type??o[0]?.type,title:x.title??I.title??"",summary:I.summary??"",body:I.body??"",domains:I.tags?.domains??[],level:I.tags?.level??"",...I.req_type?{req_type:I.req_type}:{},updated_fields:A,...$?{base_token:await Wr($,"core")}:{},...j(S),...b,...ha(g)}))}(n,e):async function(e,t){{const n=yu(),r=async(r,a,i,s)=>{const o=await Dg(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&&em(o))return{updated_fields:[],error:tm(r)};if(void 0!==a.status&&nm(o,a.status))return{updated_fields:[],error:rm(r)};void 0!==a.title&&(a.title=Jc(a.title)),void 0!==a.body&&(a.body=Jc(a.body)),void 0!==a.summary&&(a.summary=Jc(a.summary)),void 0!==a.level&&(a.level=Jc(a.level)),void 0!==a.domains&&(a.domains=a.domains.map(e=>Jc(e))),void 0!==a.steps&&(a.steps=Kp(a.steps,e=>Jc(e))),void 0!==a.params&&(a.params=Zp(Kp(a.params,e=>Jc(e)),o.data.params));const d=void 0!==a.domains?a.domains.map(vc).filter(e=>e.length>0):void 0,c=void 0!==a.level?await Yw(e,t.project_id,a.level):void 0;if(void 0!==d&&d.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=od(d,sd(n?.function_tags),vc);if(i.length>0)return{updated_fields:[],error:ld(i)};if(a.length>0){const e=new Set(a.map(vc).filter(e=>e.length>0)),t=d.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const 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!==d&&_(o.data.tags?.domains??[],d)&&(p.tags={...p.tags,domains:d},m.push("domains")),void 0!==c&&_(o.data.tags?.level,c)&&(p.tags={...p.tags,level:c},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=Bu(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 n="goal"===o.type?Rf(Object.keys(a.fields)):[];if(n.length>0)return{updated_fields:[],error:Tf(o.id,n)};const{getProjectFields:r,validateProjectFieldValuesForWrite:i,canonicalizeFieldKeys:s}=await Promise.resolve().then(()=>(Gv(),Ov)),l=await r(e,t.project_id),d=await i(e,t.project_id,l,a.fields,o.data.fields);if(d.error)return{updated_fields:[],error:d.error};const c=s(l,o.data.fields??{});for(const[e,t]of Object.entries({...s(l,a.fields),...d.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:g}=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:WA()??null,p_diff_summary:s?{reason:s}:null,p_expected_updated_at:a.expected_updated_at??o.updated_at});if(ey("main",g),g)return{updated_fields:[],error:g};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 y=m.includes("level")&&c?Ww(c,await Zw(e,t.project_id,c)):null,w=xb(o.data,h);var v;w&&(p.analysis_props=(v=h,$b(v?.data)));const b={item_id:r,project_id:t.project_id,changed_by:n,event_type:"updated",old_data:u,new_data:p,actor:VA(),session_id:WA()};i&&(b.batch_id=i);const k=function(e,t){return t?e?`${e}; ${Sb}`:Sb:e||void 0}(s,w);if(k&&(b.reason=k),await e.from("change_history").insert(b).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,...y?{levelNote:y}:{},...w?{approvalCleared:w}:{}}};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:d,error:c,levelNote:u,approvalCleared:p}=await r(s.item_id,s,e,t.reason);if(c){if(Wc(c))return Yc(Uc(c));if(!n){const e=c instanceof Error?c.message:String("object"==typeof c&&c&&"message"in c?c.message??"":c),t=K(e);return Yc(null!==t?{...t,message:`Batch stopped at "${s.item_id}": ${t.message} ${a.length} item(s) already updated.`}:Ic(`Batch stopped at "${s.item_id}": ${e.replace(/\.$/,"")}. ${a.length} item(s) already updated.`,e.includes("Function-flagged tag")||Vu(e)?uc:void 0))}i.push({item_id:s.item_id,error:String(c)})}else void 0!==l?a.push(Zv(s.item_id,l)):d?a.push(Xv(s.item_id)):a.push({id:s.item_id,updated_fields:o,...u?{level_note:u}:{},...p?{approval_cleared:!0}:{}})}const s=[...new Set(a.flatMap(e=>"level_note"in e&&e.level_note?[e.level_note]:[]))];return Kc(bc({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 Yc(Ic("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:a,updatedData:i,itemType:s,capturedSg:o,capturedUnknown:l,error:d,levelNote:c,approvalCleared:u}=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(d){const e=d instanceof Error?d.message:String("object"==typeof d&&d&&"message"in d?d.message??"":d);return e.includes("not found")?Yc(Sc("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(Mp)||e.includes(Rp)}(e)?Yc(Ic(e,e.includes("Function-flagged tag")||Vu(e)?uc:void 0)):Cc(e)||Wc(d)?Yc(Uc(d)):Yc(Vc(e))}if(void 0!==o)return Kc(bc(Zv(t.item_id,o)));if(l)return Kc(bc(Xv(t.item_id)));if(!1===t.echo)return Kc(bc({id:t.item_id,updated_fields:a,...c?{level_note:c}:{},...u?{approval_cleared:!0}:{}}));const p=i??{};return Kc(bc({id:t.item_id,type:s,title:p.title??"",summary:p.summary??"",body:p.body??"",domains:p.tags?.domains??[],level:p.tags?.level??"",...p.req_type?{req_type:p.req_type}:{},updated_fields:a,...c?{level_note:c}:{},...u?{approval_cleared:!0}:{}}))}}(n,e))}catch(e){const t=Lc(e);return Yc(t||Uc(e))}var t}async function Eb(e,t,n,r,a){const i=await Dg(e,t,n);if(!i)return{refusal:{message:`Item "${n}" not found`,path:null,notFound:!0}};if(void 0!==r.status&&em(i))return{refusal:{message:tm(n),path:["status"]}};if(void 0!==r.status&&nm(i,r.status))return{refusal:{message:rm(n),path:["status"]}};const s=[],o=[],l=(e,t)=>{s.push(e),o.push(t)};if(void 0!==r.title&&l(["title"],Jc(r.title)),void 0!==r.summary&&l(["summary"],Jc(r.summary)),void 0!==r.body&&l(["body"],Jc(r.body)),void 0!==r.req_type){const e=Bu(r.req_type,i.type);if(e)return{refusal:{message:e,path:["req_type"],long:!0}};l(["req_type"],r.req_type)}if(void 0!==r.status&&l(["status"],r.status),void 0!==r.level&&l(["tags","level"],await Yw(e,t,Jc(r.level))),void 0!==r.domains){const e=r.domains.map(e=>vc(Jc(e))).filter(e=>e.length>0);if(e.length>0){const t=await a.read(),n=od(e,sd(t.function_tags),vc);if(n.length>0)return{refusal:{message:ld(n),path:["tags","domains"],long:!0}};if(t.domains.length>0){const n=new Set(t.domains.map(vc).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 a="goal"===i.type?Rf(Object.keys(r.fields)):[];if(a.length>0)return{refusal:{message:Tf(n,a),path:["fields"],long:!0}};const{getProjectFields:s,validateProjectFieldValuesForWrite:o,canonicalizeFieldKeys:d}=await Promise.resolve().then(()=>(Gv(),Ov)),c=await s(e,t),u=await o(e,t,c,r.fields,i.data.fields);if(u.error)return{refusal:{message:u.error,path:["fields"]}};for(const[e,t]of Object.entries({...d(c,r.fields),...u.fields??{}}))l(["fields",e],""===t?null:t)}return void 0!==r.steps&&l(["steps"],Kp(r.steps,e=>Jc(e))),void 0!==r.params&&l(["params"],Kp(r.params,e=>Jc(e))),{entry:{paths:s,values:o,type:i.type,steps:i.data.steps}}}function zb(e,t,n){const r=e=>Array.isArray(e)?e:[];return 1===e.length&&"steps"===e[0]?function(e,t){return jb("steps",e??[],t??[])}(r(t),r(n)):1===e.length&&"params"===e[0]?function(e,t){return jb("params",e??[],t??[],{implicitIds:!0})}(r(t),r(Zp(n,t))):bb([...e],void 0===t?null:t,n)}H(qb,{updateItemHandler:()=>Ob});var Mb,Rb=D({"src/tools/update-item.ts"(){Wu(),xu(),Wg(),JA(),Yu(),re(),fm(),tu(),pv(),Vw(),tb(),pd(),ai(),Ab(),py(),tu(),nh(),Tw(),Ib()}}),Tb={};async function Cb(e){try{const t=await _u();yu();try{await ju(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const n=await Zg(t,e.project_id);if(null===n)return Yc(Ta());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 Yc(Sc("Item",e.item_id));if(r.deleted_at)return Yc(Ic(`Item ${e.item_id} is already deleted`));if(Cw(Mb,e.project_id)){const t={tool:Mb,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const n=Dw(t);return Kc(bc({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=Hw(e.confirmation_token,t);if(!n.valid)return Yc(Ic(`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 Da(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:ya(),kind:"trash_item",item_id:t.item_id,path:[]}],a=await ty(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await ay({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await oy(e,t.project_id,r,a.answers,"deleted"),i.not_applied.length>0?sy(i,{id:t.item_id}):Kc(bc({...n,...ha(i)}))}(t,e,a):async function(e,t,n,r){const a=yu(),{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:VA(),p_session_id:WA()});if(ey("main",i),i)throw new Error(i.message);return Kc(bc(r))}(t,e,r,a))}catch(e){const t=Lc(e);return Yc(t||Uc(e))}}H(Tb,{deleteItemHandler:()=>Cb});var Db=D({"src/tools/delete-item.ts"(){xu(),Wg(),JA(),Uw(),tu(),ai(),py(),tu(),Mb="atoms_delete_item"}}),Hb={};async function Nb(e){try{const t=await _u(),n=yu();try{await ju(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const r=await Zg(t,e.project_id);if(null===r)return Yc(Ta());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 Yc(Sc("Item",e.item_id));if(!a.deleted_at){if(!r){const n=await Pb(t,e.project_id,e.item_id);if(n.error)return Yc(ac(e.item_id,Fb(n)))}return Yc({status:"error",message:`Item ${e.item_id} is not deleted and cannot be restored.`+(r?"":" Its links were checked and any missing ones rebuilt."),next_steps:["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 Yc(rc());if(!0!==e.confirm)return Kc(function(e){const t=e.days_in_trash??0;return{status:"needs_confirmation",message:`${e.item_id} "${e.title??""}" is in Trash. ${ic(e)} moved it there on ${sc(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:[...Xd],id:e.item_id,title:e.title??"",restored:!1,trashed_by:ic(e),trashed_at:e.deleted_at??null,days_in_trash:t};var n}(l));const d={id:e.item_id,title:a.title,type:a.type,restored:!0,message:oc(l,n)};return await Da(r?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:ya(),kind:"restore_item",item_id:t.item_id,path:[]}],a=await ty(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await ay({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await oy(e,t.project_id,r,a.answers,"restored"),i.not_applied.length>0?sy(i,{id:t.item_id}):Kc(bc({...n,...ha(i)}))}(t,e,d):async function(e,t,n,r){const a=yu(),{error:i}=await async function(e,t){const n=e=>"PGRST202"===e?.code||"42883"===e?.code,r={p_project_id:t.projectId,p_item_ids:[t.itemId],p_user_id:t.userId};let{error:a}=await e.rpc("restore_items_with_revision",t.sessionId?{...r,p_event_session_id:t.sessionId}:r);if(t.sessionId&&n(a)&&({error:a}=await e.rpc("restore_items_with_revision",r)),!n(a))return{error:a??null};const{error:i}=await e.rpc("save_item_with_revision",{p_item_id:t.itemId,p_project_id:t.projectId,p_type:t.item.type,p_title:t.item.title,p_data:t.item.data,p_user_id:t.userId,p_event_source:"restore",p_event_session_id:t.sessionId,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:t.item.updated_at});return{error:i??null}}(e,{projectId:t.project_id,itemId:t.item_id,userId:a,item:n,sessionId:WA()??null});if(ey("main",i),i)throw i;const s=await Pb(e,t.project_id,t.item_id);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:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),s.error?Yc(ac(t.item_id,Fb(s))):Kc(bc(r))}(t,e,a,d))}catch(e){const t=Lc(e);return Yc(t||Uc(e))}}function Pb(e,t,n){return Qd(()=>e.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:t,p_item_id:n}))}function Fb(e){return{message:e.error?.message??"",code:e.error?.code??null,status:e.status}}H(Hb,{restoreItemHandler:()=>Nb});var Ub,Lb,Wb,Vb=D({"src/tools/restore-item.ts"(){xu(),JA(),gc(),nc(),tu(),ai(),py(),tu()}}),Bb=D({"src/core/batch-cycle.ts"(){kr()}});function Jb(e){return!!e&&("PGRST202"===e.code||"42883"===e.code||/Could not find the function public\.apply_link_changes|function public\.apply_link_changes\(.*\) does not exist/i.test(e.message??""))}function Gb(e){const t={from_id:e.from_id,to_id:e.to_id,type:e.type,action:e.action};return e.role&&(t.role=e.role),e.expected_from_updated_at&&(t.expected_from_updated_at=e.expected_from_updated_at),e.expected_to_updated_at&&(t.expected_to_updated_at=e.expected_to_updated_at),t}async function Qb(e){try{return await e()}catch(e){return{error:{message:e instanceof Error?e.message:String(e)}}}}async function Kb(e,t){let n=1,r=await Qb(e);for(const a of t){if(!Ld(r.error??null))break;await Dd.sleep(Math.round(a*Dd.jitter())),r=await Qb(e),n+=1}return{error:r.error??null,calls:n}}async function Yb(e){const t=e.delays??Wb,n=Math.max(1,Math.min(e.chunk??Ub,500)),r=e.eventSource??"mcp",a=[];let i=0,s=!1;for(let o=0;o<e.ops.length;o+=n){const l=e.ops.slice(o,o+n),d=s?null:await Kb(()=>e.client.rpc("apply_link_changes",{p_project_id:e.projectId,p_ops:l.map(Gb),p_user_id:e.userId,p_event_source:r,p_wait_ms:Lb}),t);if(d&&(i+=d.calls),!d||d.error&&Jb(d.error)){s=!0;for(let n=0;n<l.length;n+=1){const d=l[n],c=await Kb(()=>e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:d.from_id,p_to_id:d.to_id,p_type:d.type,p_action:d.action,p_user_id:e.userId,p_event_source:r,...d.expected_from_updated_at?{p_expected_from_updated_at:d.expected_from_updated_at}:{},...d.expected_to_updated_at?{p_expected_to_updated_at:d.expected_to_updated_at}:{},...d.role?{p_role:d.role}:{}}),t);if(i+=c.calls,c.error)return{applied:a,error:c.error,failed:[d],notSent:e.ops.slice(o+n+1),calls:i,fallback:s};a.push(d)}}else{if(d.error)return{applied:a,error:d.error,failed:l,notSent:e.ops.slice(o+n),calls:i,fallback:s};a.push(...l)}}return{applied:a,error:null,failed:[],notSent:[],calls:i,fallback:s}}var Zb,Xb=D({"src/core/link-batch.ts"(){nc(),Ub=100,Lb=3e3,Wb=[250,500,1e3]}}),ek={};async function tk(e){try{const t=await _u(),n=yu();try{await ju(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}let r;const a=async()=>void 0===r?r=await Zg(t,e.project_id):r,i=async(r,a,i)=>{const o=await Yb({client:t,projectId:e.project_id,ops:r,userId:n});return 0===o.applied.length&&ey("main",o.error),o.applied.length>0&&await s(o.applied,a,i),o},s=async(r,a,i)=>{for(const a of r.filter(e=>"affects"===e.type||"affected_by"===e.type))for(const r of[a.from_id,a.to_id]){const a=await Dg(t,e.project_id,r);if(!a)continue;const i=ro(a.data);if(!i)continue;const s=await Dg(t,e.project_id,i);if(!s)continue;const{revoked:o,parentProps:l}=ao(s.data);if(!o)continue;const d={...s.data,analysis_props:l},{error:c}=await t.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:d,p_user_id:n,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});c&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${s.id}': ${c.message}\n`)}const s=r.map(t=>({item_id:t.from_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:null,new_data:{relationship_change:{action:t.action,type:t.type,from:t.from_id,to:t.to_id}},actor:VA(),session_id:WA(),...a?{batch_id:a}:{},...i?{reason:i}:{}}));await t.from("change_history").insert(s).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})},o=e=>Object.assign(new Error(e?.message??"unknown error"),{code:e?.code??void 0});if(e.operations&&Array.isArray(e.operations)){for(const t of e.operations){if(t.from_id===t.to_id)return Yc(Ic(`Self-reference in batch: "${t.from_id}"`));if("affects"===t.type||"affected_by"===t.type){const e=mv(t.from_id,t.to_id,t.type);if(e)return Yc(Ic(e))}}const n=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],r=await En(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)),l=n.filter(e=>!s.has(e));if(l.length>0)return Yc(Sc("Items",l.join(", ")));const d=await gv(t,e.project_id,e.operations,En);if(d)return Yc("toolError"in d?d.toolError:Ic(`${d.validation} No changes applied.`));const c=await async function(e,t,n){const r=e=>"parent"===e.type?[e.from_id,e.to_id]:[e.to_id,e.from_id],a=n.filter(e=>"parent"===e.type||"child"===e.type),i=a.filter(e=>"add"===e.action).map(r);if(0===i.length)return null;const s=new Set(a.filter(e=>"remove"===e.action).map(e=>r(e).join("\0"))),o=new Map;let l=[...new Set(i.flat())];const d=(n,r,a)=>An(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type",n).in(r,a),mn);for(;l.length>0;){for(const e of l)o.set(e,new Set);for(let e=0;e<l.length;e+=wn){const t=l.slice(e,e+wn);for(const e of await d("parent","from_id",t))"parent"===e.type&&o.get(e.from_id)?.add(e.to_id);for(const e of await d("child","to_id",t))"child"===e.type&&o.get(e.to_id)?.add(e.from_id)}const e=new Set;for(const t of l)for(const n of o.get(t))o.has(n)||e.add(n);l=[...e]}const c=new Map;for(const[e,t]of o)c.set(e,new Set([...t].filter(t=>!s.has(`${e}\0${t}`))));for(const[e,t]of i)c.get(e).add(t);for(const[e,t]of i){if(o.get(e).has(t)&&!s.has(`${e}\0${t}`))continue;const n=new Map([[t,e]]),r=[t];for(;r.length>0;){const t=r.shift();if(t===e){const t=[e];for(let r=n.get(e);r!==e;r=n.get(r))t.push(r);return[e,...t.slice(1).reverse(),e].join(" -> ")}for(const e of c.get(t)??[])n.has(e)||(n.set(e,t),r.push(e))}}return null}(t,e.project_id,e.operations);if(c)return Yc(Ic(`Batch would create a cycle: ${c}. No changes applied.`));const u=e.operations,p=await a();return null===p?Yc(Ta()):await Da(p?"ops":"main",async n=>{if("ops"===n)return nk(t,e,u,!0);const r=crypto.randomUUID(),a=[...u.filter(e=>"remove"===e.action),...u.filter(e=>"add"===e.action)],s=e=>`${e.action} ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`,l=await i(a,r,e.reason);if(l.error){const e=l.applied,t=Uc(o(l.error));return Yc({...t,message:`${t.message}\n\nThis batch is not atomic: its operations are applied in calls of up to ${Ub}, each all or nothing. ${e.length} of ${a.length} operation(s) committed before this one failed and were NOT rolled back (batch ${r}). Committed: ${e.length?e.map(s).join("; "):"none"}. Failed (nothing of this call stored): ${l.failed.map(s).join("; ")}.`+(l.notSent.length?` Not sent: ${l.notSent.map(s).join("; ")}.`:""),next_steps:nn(e.length,t)})}return Kc(bc({batch_id:r,processed:u.length,operations:!1===e.echo?void 0:u}))})}if(!(e.from_id&&e.to_id&&e.type&&e.action))return Yc(Ic("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."));if(e.from_id===e.to_id)return Yc(Ic("Cannot create a relationship between an item and itself"));if("affects"===e.type||"affected_by"===e.type){const t=mv(e.from_id,e.to_id,e.type);if(t)return Yc(Ic(t))}const l=await gv(t,e.project_id,[{action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type}],En);if(l)return Yc("toolError"in l?l.toolError:Ic(l.validation));const d={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},c=await a();return null===c?Yc(Ta()):await Da(c?"ops":"main",async n=>{if("ops"===n)return nk(t,e,[d],!1);const r=await En([d.from_id,d.to_id],n=>t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",n));for(const e of[d.from_id,d.to_id])if(!r.some(t=>t.id===e))throw new Error(`Item "${e}" not found`);const a=await i([d],void 0,e.reason);if(a.error)throw o(a.error);return!1===e.echo?Kc(bc({action:d.action,from_id:d.from_id,to_id:d.to_id})):Kc(bc({action:d.action,type:d.type,from_id:d.from_id,to_id:d.to_id,message:`Relationship ${"add"===d.action?"added":"removed"}: ${d.from_id} --[${d.type}]--\x3e ${d.to_id}`}))})}catch(e){const t=Lc(e);return Yc(t||Uc(e))}}async function nk(e,t,n,r){const a=yu(),i=[];for(const e of n){const n={op_id:"",kind:e.action,item_id:e.from_id,path:["relationships",Zb[e.type]],value:e.to_id};n.op_id=t.idempotency_key?await ga(va({userId:a,projectId:t.project_id,family:ja("atoms_link_items"),key:t.idempotency_key,itemIdOrK:e.from_id,path:dy(n)})):ya(),t.reason&&(n.reason=t.reason),i.push(n)}const s=await ty(e,t.project_id,i);if(void 0!==s.error&&0===s.results.length)throw s.error;const o=await ay({client:e,projectId:t.project_id,answers:[...s.answers,...Ma(s.notSent)],ops:i,results:s.results}),l=r?crypto.randomUUID():void 0;if(await oy(e,t.project_id,i,s.answers,"updated",{batch_id:l,reason:t.reason}),o.not_applied.length>0)return sy(o,{...r?{batch_id:l}:{},...ny(s)});if(r)return Kc(bc({batch_id:l,processed:n.length,operations:!1===t.echo?void 0:n,...ha(o),...ny(s)}));const d=n[0];return!1===t.echo?Kc(bc({action:d.action,from_id:d.from_id,to_id:d.to_id,...ha(o)})):Kc(bc({action:d.action,type:d.type,from_id:d.from_id,to_id:d.to_id,message:`Relationship ${"add"===d.action?"added":"removed"}: ${d.from_id} --[${d.type}]--\x3e ${d.to_id}`,...ha(o)}))}H(ek,{linkItemsHandler:()=>tk});var rk=D({"src/tools/link-items.ts"(){xu(),Wg(),kr(),Bb(),JA(),ol(),an(),tu(),ai(),py(),tu(),yv(),Xb(),Zb={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",affects:"affects",affected_by:"affected_by",allocated_to:"allocated_to",allocated_from:"allocated_from"}}});function ak(e){if(0===e.length)return{};const t=e.map(e=>e.child_id);return{link_warnings:e.map(e=>({child_id:e.child_id,parent_id:e.parent_id,message:e.message})),warning:`${e.length} imported item${1===e.length?" was":"s were"} created but not yet listed under ${1===e.length?"its parent":"their parents"}: ${t.join(", ")}. Repair: call atoms_link_items with type 'parent', from_id=<child_id>, to_id=<parent_id> for each entry of link_warnings. Do not import them again.`}}var ik,sk,ok=D({"src/core/bulk-parent-links.ts"(){nc(),Xb()}}),lk={};function dk(e){return!!ck(e)||new Set(["22023","23503","23505","23514"]).has(e.code??"")}function ck(e){return!!e&&null!==Mr(String(e.message??""))}function uk(e,t){return e.items.length>t?Yc(Ic(`Maximum ${t} items per call (received ${e.items.length}). Split into multiple calls.`)):null}async function pk(e){try{if(!e.items||0===e.items.length)return Yc(Ic("items array must contain at least 1 item"));const t=uk(e,ik);if(t)return t;const n=await _u();try{await ju(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const r=await Zg(n,e.project_id);if(null===r)return Yc(Ta());if(!r){const t=uk(e,sk);if(t)return t}if(e.items.some(e=>"function"===e.type)){const t=c_(await l_(n,e.project_id));if(t)return Yc(t);const r=await async function(e,t,n,r){const a=n.map((e,t)=>({item:e,index:t})).filter(({item:e})=>"function"===e.type&&"string"==typeof e.parent_id&&e.parent_id.length>0);if(0===a.length)return null;const i=await hv(e,t,a.map(({item:e})=>e.parent_id),r);for(const{item:e,index:t}of a){const n=i.get(e.parent_id);if(!n)continue;const r=fv("the new item",e.type,n.id,n.type);if(r)return{index:t,message:r}}return null}(n,e.project_id,e.items,En);if(r)return Yc(Ic(`Nothing was imported. items[${r.index}]: ${r.message}`))}if(e.items=e.items.map(e=>({...e,type:bf(e.type)})),e.items.some(e=>kf(e.type))){const t=await Af(n,e.project_id);if(t)return Yc(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=sd(r?.function_tags),o=i.length>0?new Set(i.map(vc).filter(e=>e.length>0)):null,l=Pw(i.map(vc).filter(e=>e.length>0).sort()),d=[],c=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(vc).filter(e=>e.length>0);if(0===r.length)continue;const a=od(r,s,vc);if(a.length>0){c.add(e),d.push({index:e,title:t.title,error:ld(a)});continue}if(!o)continue;const l=r.filter(e=>!o.has(e));l.length>0&&(c.add(e),d.push({index:e,title:t.title,error:`Unknown domain${l.length>1?"s":""}: ${l.join(", ")}. Registered: ${i.join(", ")}.`}))}return{registeredDomains:i,registeredDomainHash:l,invalidDomainIndexes:c,errors:d,typeBreakdown:u}}(n,e.project_id,e.items);if(Cw("atoms_bulk_import",e.project_id)){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:Pw({items:e.items,registered_domain_hash:a.registeredDomainHash})};if(!e.confirmation_token){const n=Dw(t);return Kc(bc({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=Hw(e.confirmation_token,t);if(!n.valid)return Yc(Ic(`confirmation_token rejected: ${n.reason}`))}return await Da(r?"ops":"main",t=>"ops"===t?async function(e,t,n){const r=yu(),a=t.idempotency_key,i=ja("atoms_bulk_import"),s=t.items.some(e=>void 0!==e.level)?await Gw(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(vc).filter(e=>e.length>0),r=void 0!==e.level?Lw(e.level,vc(e.level),s,Jw):void 0;return{input:e,index:t,domains:n,level:r,content:$a({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=Sa(o.map(e=>e.content)),d=[];for(let e=0;e<o.length;e+=1)d.push(await ga(a?va({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:o[e].index,path:[]}):wa({userId:r,projectId:t.project_id,content:o[e].content,k:l[e],sessionId:WA()})));const c=a?await Promise.all(o.map(e=>Ua(e.content))):[],u=await Ba(e,t.project_id,d.map((e,t)=>({op_id:e,content_hash:c[t]}))),p=[],m=[],_=[];o.forEach((e,t)=>{const n=u.get(d[t]);n&&("applied"===n.status||"noop"===n.status)&&n.item_id?(p.push({id:n.item_id,title:e.input.title,type:e.input.type,replayed:!0}),m.push(n)):_.push({v:e,createId:d[t],contentHash:c[t]})});const f=[...n.errors],h=[],g=new Map;if(_.length>0){const n={};for(const{v:e}of _){const t=hw(e.input.type);n[t]=(n[t]??0)+1}const s=gw(await yw(e,t.project_id,n));for(const{v:e,createId:n,contentHash:o}of _){const l=s(hw(e.input.type));g.set(l,{title:e.input.title,type:e.input.type});const d={summary:e.input.summary,body:e.input.body,tags:{domains:e.domains,level:e.level??""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[]},links:[]};h.push({op_id:n,kind:"create_item",item_id:l,path:[],value:{type:e.input.type,title:e.input.title,data:d},...o?{content_hash:o}:{}}),e.input.parent_id&&h.push({op_id:a?await ga(va({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:e.index,path:["relationships","parents","add",e.input.parent_id]})):ya(),kind:"add",item_id:l,path:["relationships","parents"],value:e.input.parent_id})}}let y={answers:[],results:[],notSent:[]};if(h.length>0&&(y=await ty(e,t.project_id,h,{mode:"bulk"}),void 0!==y.error&&0===y.results.length))throw y.error;const w=[...await Ja(e,t.project_id,y.answers,h),...Ma(y.notSent)],v=await ay({client:e,projectId:t.project_id,answers:w,ops:h,results:y.results,relooked:!0});await oy(e,t.project_id,h,w,"created");const b=[...p],k=[...m];for(const e of w){if(!e.item_id||!e.path||0!==e.path.length)continue;if("applied"!==e.status&&"noop"!==e.status)continue;const t=g.get(e.item_id);t&&(b.push({id:e.item_id,title:t.title,type:t.type,...e.replayed?{replayed:!0}:{}}),k.push(e))}const{tokens:j,unread:S}=await Ow(e,t.project_id,k);for(const e of b){const t=j.get(e.id);t&&(e.base_token=t)}const A=b.length>0&&b.every(e=>e.replayed),$={created:b.length,items:b,errors:f,project_id:t.project_id,...y.chunks?{chunks:y.chunks}:{},...void 0!==y.error?{error:Uc(y.error).message}:{},...A?{replayed:!0,message:yr}:{},...S?{warning:Kn}:{}};return v.not_applied.length>0?sy(b.length>0&&0===v.applied.length?{...v,applied:b.map(e=>({item_id:e.id,path:[],status:"applied",seq:null,replayed:!0}))}:v,$):Kc(bc({...$,...ha(v)}),{receipt:"items"})}(n,e,a):async function(e,t,n){const r=yu();{const a=(new Date).toISOString(),i=WA(),s=[],o=[...n.errors],l=[],d=t.items.map((e,t)=>({input:e,index:t})).filter(({index:e})=>!n.invalidDomainIndexes.has(e)),c={};for(const{input:e}of d){const t=hw(e.type);c[t]=(c[t]??0)+1}let u=null,p=null;try{u=gw(await yw(e,t.project_id,c))}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(hw(e))},_=t.items.some(e=>void 0!==e.level)?await Gw(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(vc).filter(e=>e.length>0),i=void 0!==r.level?Lw(r.level,vc(r.level),_,Jw):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 Kc(bc({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 g=f.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:y}=await Jd(()=>e.rpc("bulk_save_items_with_revisions",{p_project_id:t.project_id,p_items:g,p_user_id:r,p_event_source:"mcp"}),{scope:t.project_id});ey("main",y);const w=[];if(y&&dk(y))for(const{itemId:n,input:a,index:d}of l){const l=f.find(e=>e.id===n);if(!l)continue;const{error:c}=await Jd(()=>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}),{scope:t.project_id});if(c){const e=Mr(c.message??"");e&&w.push(c.message??""),o.push({index:d,title:a.title,error:e?.message??c.message})}else s.push({id:n,title:a.title,type:a.type})}else{if(y)throw y;for(const{itemId:e,input:t}of l)s.push({id:e,title:t.title,type:t.type})}const v=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})),b=await async function(e){const t=[],n=e=>({action:"add",from_id:e.from,to_id:e.to,type:"parent"});let r=[...e.links];for(;r.length>0;){const a=await Yb({client:e.client,projectId:e.projectId,userId:e.userId,ops:r.map(n),delays:e.delays});if(!a.error)break;const i=a.error.message??"unknown error",s=a.failed.map(e=>({from:e.from_id,to:e.to_id}));if(!a.fallback&&s.length>1&&!Ld(a.error))for(const r of s){const a=await Yb({client:e.client,projectId:e.projectId,userId:e.userId,ops:[n(r)],delays:e.delays});a.error&&t.push({child_id:r.from,parent_id:r.to,message:a.error.message??"unknown error"})}else for(const e of s)t.push({child_id:e.from,parent_id:e.to,message:i});r=a.notSent.map(e=>({from:e.from_id,to:e.to_id}))}for(const n of t)e.warn(`bulk parent link sync failed for ${n.parent_id} (child ${n.child_id}): ${n.message}`);return t}({client:e,projectId:t.project_id,links:v.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 Qd(()=>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 k=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:VA(),session_id:i}));k.length>0&&await e.from("change_history").insert(k).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const j=new Set(s.map(e=>e.id)),S=new Set(l.filter(({itemId:e,sanitizedLevel:t})=>t&&j.has(e)).map(({sanitizedLevel:e})=>e)),A=[];for(const n of S){const r=Ww(n,await Zw(e,t.project_id,n));r&&A.push(r)}const $=function(e,t,n){return e>0||0===t.length||0===n.length?null:n.length===t.length?n[0]:null}(s.length,o,w);return $?Yc(Uc(new Error($))):Kc(bc({created:s.length,items:s,errors:o.length>0?o:[],project_id:t.project_id,...A.length>0?{level_notes:A}:{},...ak(b)}),{receipt:"items"})}}(n,e,a))}catch(e){const t=Lc(e);return Yc(t||Uc(e))}}H(lk,{BULK_IMPORT_MAIN_MAX:()=>sk,BULK_IMPORT_MAX:()=>ik,bulkImportHandler:()=>pk,canRetryBulkImportPerItem:()=>dk,isItemLockedRefusal:()=>ck});var mk=D({"src/tools/bulk-import.ts"(){xu(),ww(),JA(),Uw(),tu(),nc(),ok(),pv(),Vw(),pd(),ai(),py(),tu(),Tw(),k_(),nh(),yv(),kr(),ik=500,sk=100}}),_k={};async function fk(e){const t=yu(),n=e.idempotencyKey||await async function(e){return null==e.requestId||""===e.requestId?ya():ga(["append_run_key",e.sessionId,String(e.requestId)])}({sessionId:WA(),requestId:e.requestId}),r=await Promise.all(e.entries.map(e=>async function(e){return Cr(Tr(Aa(e)))}(e))),a=Sa(r),i=[];for(let s=0;s<e.entries.length;s+=1){const o=await ga(ba({userId:t,projectId:e.projectId,tool:e.tool,key:n,itemId:e.itemId,runHash:r[s],k:a[s]}));i.push({op_id:o,kind:"append_run",item_id:e.itemId,path:["runs"],value:e.entries[s]})}const s=await kw({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]));let d=null;if(!o)try{d=(await Dg(e.client,e.projectId,e.itemId))?.data?.runs??null}catch{d=null}return{run:s,runs:i.map((t,n)=>{const r=l.get(t.op_id);return{result:Bp(d,t.op_id,e.entries[n]),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 hk(e,t){let n;try{const r=await _u(),a=yu(),i=wu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const s=t??await vw(r,e.project_id);if("unreadable"===s)return bw();n=s;const o=await Dg(r,e.project_id,e.item_id);if(!o)return Yc(Sc("Item",e.item_id));if("test-case"!==o.type)return Yc(Ic(`Item '${e.item_id}' is a ${o.type}, not a test-case`));const l=(e.asset??"").trim(),d=Yp({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=>Jc(e)),c=Wp([e]).length>0?{release_note:vp}:{};if("ops"===s){const t=await fk({client:r,projectId:e.project_id,itemId:e.item_id,entries:[d],tool:"atoms_record_test_result",idempotencyKey:e.idempotency_key,requestId:e.request_id});if(t.refusal)return Yc(Ic(t.refusal,uc));const n=t.runs[0],s=l?` (asset: ${l})`:"",o=n.result;return jw(t.run.outcome,{item_id:e.item_id,result:o,run_at:n.run_at,run_by:i||a,note:d.note??null,asset:l||null,asset_id:n.asset_id,asset_created:n.asset_created,message:t.run.outcome.replayed?wr:`Test result '${o??"recorded"}' recorded for ${e.item_id}${s}`,...null!==o&&o!==e.result?{verdict_note:Gp([0],!0)}:{},...void 0!==e.date&&null!==e.date?{warning:bp}:{},...c},t.run,{idempotency_key_used:t.keyUsed})}const u=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:[d]});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,u="string"==typeof s?.result?s.result:Bp(null,"",d);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:u,run_at:o,note:d.note,asset:l||null},actor:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const p=l?` (asset: ${l})`:"";return Kc(bc({item_id:e.item_id,result:u,run_at:o,run_by:i||a,note:d.note??null,asset:l||null,asset_id:s?.asset_id??null,asset_created:s?.asset_created??!1,message:`Test result '${u??"recorded"}' recorded for ${e.item_id}${p}`,...null!==u&&u!==e.result?{verdict_note:Gp([0],!0)}:{},...void 0!==e.date&&null!==e.date?{warning:bp}:{},...c}))};return await u()}catch(r){const a=Sw(n,t,r);return a?hk(e,a):Yc(Uc(r))}}H(_k,{recordRunsByOps:()=>fk,recordTestResultHandler:()=>hk});var gk=D({"src/tools/record-test-result.ts"(){xu(),Wg(),JA(),tu(),fm(),ai(),Tw(),ai()}}),yk={};async function wk(e,t){let n;try{const r=await _u(),a=yu(),i=wu();if(!Array.isArray(e.results)||0===e.results.length)return Yc(Ic("results must be a non-empty array"));if(e.results.length>100)return Yc(Ic(`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?Np(e.date):NaN;Number.isNaN(a)||(a<n?t.push(r):n=a)}),t}(e.results);if(s.length>0)return Yc(Ic(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),uc));try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const o=t??await vw(r,e.project_id);if("unreadable"===o)return bw();n=o;const l=await Dg(r,e.project_id,e.item_id);if(!l)return Yc(Sc("Item",e.item_id));if("test-case"!==l.type)return Yc(Ic(`Item '${e.item_id}' is a ${l.type}, not a test-case`));if("ops"===o){const t=e.results.map(e=>{const t=Yp(e,e=>Jc(e)),{date:n,...r}=t;return r}),n=await fk({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 Yc(Ic(n.refusal,uc));const a=Up(e.results),i=Wp(e.results),s=Jp(e.results,n.runs);return jw(n.run.outcome,{item_id:e.item_id,count:e.results.length,results:n.runs,...s.length>0?{verdict_note:Gp(s),verdict_differs_entries:s}:{},message:n.run.outcome.replayed?wr:`Recorded ${e.results.length} test results for ${e.item_id}`,...a.length>0?{warning:Lp(a),ignored_date_entries:a}:{},...i.length>0?{release_note:Vp(i),no_release_entries:i}:{}},n.run,{idempotency_key_used:n.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:e.results.map(e=>Yp(e,e=>Jc(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:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const s=Up(e.results),o=Wp(e.results),l=Jp(e.results,t);return Kc(bc({item_id:e.item_id,count:e.results.length,results:t,message:`Recorded ${e.results.length} test results for ${e.item_id}`,...l.length>0?{verdict_note:Gp(l),verdict_differs_entries:l}:{},...s.length>0?{warning:Lp(s),ignored_date_entries:s}:{},...o.length>0?{release_note:Vp(o),no_release_entries:o}:{}}))};return await d()}catch(r){const a=Sw(n,t,r);return a?wk(e,a):Yc(Uc(r))}}H(yk,{recordTestResultsBulkHandler:()=>wk});var vk=D({"src/tools/record-test-results-bulk.ts"(){xu(),Wg(),JA(),tu(),gk(),ai(),Tw(),fm()}}),bk={};async function kk(e){try{const t=sh(e.depth),n=await _u(),r=await Dg(n,e.project_id,e.item_id);if(!r)return Yc(Sc("Item",e.item_id));const a=await An(()=>n.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn),i=Vm(a,await An(()=>n.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn)),s=function(e,t=0,n){const{rows:r,meta:a}=qd(e.items,t,n),i=t=>{const n=new Set([e.root,...t.map(e=>e.id)]);return e.edges.filter(e=>n.has(e.from)&&n.has(e.to))},s={list:"items",resume:e=>({meta:{next_offset:t+e},data:{edges:i(r.slice(0,e))},next:`offset=${t+e}`})};return{data:{...e,items:r,edges:i(r)},meta:a,paging:s}}(function(e){const t=sh(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})},s=e=>r.get(e)?.type;for(const t of e.relationships){const r=ah(t,s),a=r.type;if(n||!Qf.includes(a)){if(("upstream"===e.direction||"both"===e.direction)&&(!Jf.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),Gf.has(a))){const e=Kf[a]??a;n&&!n.has(e)||i(r.to_id,r.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!Gf.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),Jf.has(a))){const e=Kf[a]??a;n&&!n.has(e)||i(r.to_id,r.from_id,e)}"related"!==a||n&&!n.has("related")||(i(r.from_id,r.to_id,"related"),i(r.to_id,r.from_id,"related"))}}const o=new Set([e.rootItemId]),l=[],d=[],c=[];for(const t of a.get(e.rootItemId)??[])c.push({id:t.neighbor,depth:1,relType:t.relType,from:e.rootItemId});for(let e=0;e<c.length;e++){const{id:n,depth:i,relType:s,from:u}=c[e];if(o.has(n)||i>t)continue;o.add(n);const p=r.get(n);if(p&&(l.push({id:n,title:rh(p),type:p.type,relationship:s,depth:i,from:u,...ih(p,r)}),d.push({from:u,to:n,type:s}),i<t))for(const e of a.get(n)??[])o.has(e.neighbor)||c.push({id:e.neighbor,depth:i+1,relType:e.relType,from:n})}const u={id:e.rootItemId,title:rh(e.rootItem),type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId,...ih(e.rootItem,r)};return{root:e.rootItemId,project_id:e.projectId,direction:e.direction,depth_limit:t,items:[u,...l],edges:d,total_count:l.length+1}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown",data:r.data},items:a,relationships:i??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types}),e.offset,e.limit);return Kc(bc(s.data,s.meta),{paging:s.paging})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(bk,{traceHandler:()=>kk});var jk=D({"src/tools/trace.ts"(){xu(),Wg(),kr(),_h(),tu()}}),Sk={};async function Ak(e){try{const t=await _u(),n=await An(()=>{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)},_n);return Kc(bc({assets:n,total:n.length}),{complete:!0})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(Sk,{listAssetsHandler:()=>Ak});var $k=D({"src/tools/assets.ts"(){xu(),kr(),tu()}}),xk={};async function Ik(e,t){try{const t=await gu(e);return t.ok?Kc(bc(t.data),{complete:!0}):Yc(t.error)}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:t}))}}async function qk(e){return Ik(async()=>async function(e,t){try{const n=await vs(e,"model_designs_list",{p_project_id:t.project_id,p_trashed:!1});if(!0!==n?.enabled)return{ok:!1,error:gs()};const r=(n.designs??[]).map(ms);return{ok:!0,data:{model_designs:r,total:r.length}}}catch(e){const t=ys(e);if(t)return{ok:!1,error:t};throw e}}(await _u(),e),!0)}async function Ok(e){return Ik(async()=>async function(e,t){try{if(!Ri.test(t.display_id))return cs("validation_error","Validation error: display_id is an MD id such as MD-001",["Use atoms_list_model_designs to see the MD ids"]);const n=await ks(e,t.project_id,t.display_id);if(!n)return{ok:!1,error:gs()};const r=n.canvas??Ii,a=await bs(e,t.project_id,ts(r).filter(e=>Oi.test(e))),i=e=>a.get(e)?.title??null,s=e=>e.filter(e=>Oi.test(e)).map(e=>({id:e,title:i(e),type:a.get(e)?.type??null}));return{ok:!0,data:{...ms(n),model_mermaid:ds(r,{displayId:n.display_id,name:n.name,description:n.description},i),boxes:r.boxes.filter(e=>e.links.length>0).map(e=>({box_label:e.label,linked_items:s(e.links)})),arrows:r.arrows.filter(e=>e.links.length>0).map(e=>({arrow_label:e.label,linked_items:s(e.links)}))}}}catch(e){const t=ys(e);if(t)return{ok:!1,error:t};throw e}}(await _u(),e),!0)}async function Ek(e){return Ik(async()=>async function(e,t,n={}){try{if(await ws(e,t.project_id))return{ok:!1,error:$r()};const r=Xi(t.name);if(r)return cs("validation_error",`Validation error: ${r}`,["Give the design a name of 1 to 200 characters"]);const a=es(t.description??"");if(a)return cs("validation_error",`Validation error: ${a}`,["Shorten the description to 5000 characters"]);let i,s=Ii;if(void 0!==t.mermaid&&""!==t.mermaid.trim()){const n=await js(e,t.project_id,t.mermaid,Ii);if(!n.ok)return n.error;s=n.canvas;const r=$s(n.parsed,{name:t.name,description:t.description});if(r)return r;if(void 0===t.description&&null!==n.parsed.description){const e=es(n.parsed.description);if(e)return cs("validation_error",`Validation error: ${e}`,["Fix the %% description: line and call again"]);i=n.parsed.description}}const o=await vs(e,"model_design_create",{p_project_id:t.project_id,p_name:t.name,p_description:t.description??i??"",p_canvas:s,p_source:"mcp",p_tool:"atoms_create_model_design",p_agent_client:n.agentClient??"Claude"});return{ok:!0,data:{...ms(o),created:!0}}}catch(e){const t=ys(e);if(t)return{ok:!1,error:t};throw e}}(await _u(),e,{agentClient:Ha(BA())}),!1)}async function zk(e){return Ik(async()=>async function(e,t,n={}){try{if(!Ri.test(t.display_id))return cs("validation_error","Validation error: display_id is an MD id such as MD-001",["Use atoms_list_model_designs to see the MD ids"]);if(await ws(e,t.project_id))return{ok:!1,error:$r()};if(void 0===t.name&&void 0===t.description&&void 0===t.mermaid)return cs("validation_error","Validation error: send at least one of name, description or mermaid",["Name what to change and call again"]);if(void 0!==t.name){const e=Xi(t.name);if(e)return cs("validation_error",`Validation error: ${e}`,["Give the design a name of 1 to 200 characters"])}if(void 0!==t.description){const e=es(t.description);if(e)return cs("validation_error",`Validation error: ${e}`,["Shorten the description to 5000 characters"])}const r=await ks(e,t.project_id,t.display_id);if(!r)return{ok:!1,error:gs()};if(r.version!==t.expected_version){const e=Number.isNaN(Date.parse(r.updated_at))?String(r.updated_at):new Date(r.updated_at).toISOString().slice(0,16).replace("T"," ");return cs("stale_version",`Not saved: ${r.updated_by_name} saved version ${r.version} of ${r.display_id} at ${e} UTC.`,["Read the design again with atoms_get_model_design","Apply your change to that version's Mermaid, then call atoms_update_model_design with its version as expected_version"],!0,{current_version:r.version})}let a,i,s=null;if(void 0!==t.mermaid){const o=await js(e,t.project_id,t.mermaid,r.canvas??Ii);if(!o.ok)return o.error;s=o.canvas;const l=$s(o.parsed,{name:t.name,description:t.description});if(l)return l;if(void 0===t.name&&null!==o.parsed.name&&Zi(o.parsed.name)!==r.name){const e=Xi(o.parsed.name);if(e)return cs("validation_error",`Validation error: ${e}`,["Fix the %% name: line and call again"]);a=o.parsed.name}if(void 0===t.description&&null!==o.parsed.description&&o.parsed.description!==r.description){const e=es(o.parsed.description);if(e)return cs("validation_error",`Validation error: ${e}`,["Fix the %% description: line and call again"]);i=o.parsed.description}if(n.blockDestructive){const e=function(e,t){const n=e=>new Set([...e.boxes,...e.arrows].flatMap(e=>e.links.map(t=>`${e.id}\0${t}`))),r=n(t);if([...n(e)].some(e=>!r.has(e)))return"removing a link";const a=e=>new Set([...e.boxes.map(e=>`b:${e.id}`),...e.arrows.map(e=>`a:${e.id}`),...e.groups.map(e=>`g:${e.id}`)]),i=a(t);return[...a(e)].some(e=>!i.has(e))?"removing a box, arrow or group from a model design":null}(r.canvas??Ii,s);if(e)return{ok:!1,error:As(e)}}}const o=await vs(e,"model_design_save",{p_design_id:r.id,p_expected_version:t.expected_version,p_name:t.name??a??null,p_description:t.description??i??null,p_canvas:s,p_source:"mcp",p_tool:"atoms_update_model_design",p_agent_client:n.agentClient??"Claude"});return{ok:!0,data:{...ms(o),updated:!0,...s?Ss(r.canvas??Ii,s):{}}}}catch(e){const t=ys(e);if(t)return{ok:!1,error:t};throw e}}(await _u(),e,{agentClient:Ha(BA()),blockDestructive:ke(Fe(),e.project_id).block_destructive}),!1)}H(xk,{createModelDesignHandler:()=>Ek,getModelDesignHandler:()=>Ok,listModelDesignsHandler:()=>qk,updateModelDesignHandler:()=>zk});var Mk,Rk=D({"src/tools/model-designs.ts"(){xu(),zs(),tu(),ai(),Ae(),We(),JA()}}),Tk=D({"src/core/bulk-variables.ts"(){kr()}});function Ck(e){const t=e.data?.body;return"string"==typeof t?t.toLowerCase():""}function Dk(e,t){return"string"==typeof e&&e.toLowerCase().includes(`{${t.toLowerCase()}}`)}async function Hk(e,t,n){const r=[...new Set(n.map(e=>e.toLowerCase()))];return 0===r.length?new Map:await async function(e,t,n){const r=await qg(e,"mcp_variable_reference_counts",{p_project_id:t,p_names:[...n]});if(!r)return null;const a=r.data;if(null===a||"object"!=typeof a||Array.isArray(a))return null;const i=new Map;for(const e of n){const t=xg(a[e]??0);if(null===t)return null;i.set(e,t)}return i}(e,t,r)??async function(e,t,n){const r=new Map,a=[...new Set(n.map(e=>e.toLowerCase()))];if(0===a.length)return r;if(a.length<=Mk)return await Promise.all(a.map(async n=>{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->>body","ilike",function(e){return`%{${e.replace(/[\\%_]/g,e=>`\\${e}`)}}%`}(n));if(i)throw new Error(`items reference count: ${i.message}`);r.set(n,a??0)})),r;const i=await An(()=>e.from("items").select("id, body:data->>body").eq("project_id",t).is("deleted_at",null).filter("data->>body","ilike","%{%"),["id"]);for(const e of a)r.set(e,i.filter(t=>Dk(t.body,e)).length);return r}(e,t,r)}function Nk(e,t){const n=e.map(e=>({v:e,n:t.get(e.name.toLowerCase())??0})).filter(({n:e})=>e>0),r=n.reduce((e,{n:t})=>e+t,0);if(0===r)return{already_referenced_by_items:0};const a=n.slice(0,5).map(({v:e,n:t})=>`${t} item${1===t?"":"s"} already contain${1===t?"s":""} {${e.name}}; ${1===t?"it now reads":"they now read"} ${e.value}${e.unit?` ${e.unit}`:""}.`);return n.length>5&&a.push(`And ${n.length-5} more names.`),{already_referenced_by_items:r,warning:a.join(" ")}}var Pk,Fk,Uk=D({"src/core/variable-refs.ts"(){kr(),zg(),Mk=10}}),Lk={};async function Wk(e,t,n,r){if(n&&r)throw new Wt("baseline_id and as_of are mutually exclusive");if(r)return gn(Mg(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 Wt("Baseline not found for this project");return yn(n)}async function Vk(e,t,n){return n?On(e,t,n):An(()=>e.from("project_variables").select("*").eq("project_id",t),fn)}async function Bk(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 Jk(e,t,n){if(0===n.length||!0!==await Ra(e,t))return n;const r=await Qr(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 Wr(t,"variable","variable")}:e}))}async function Gk(e,t,n,r){const a=yu(),i=ja("atoms_create_variable");return n?{rowId:await ga(va({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables","row_id"]})),opId:await ga(va({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables"]}))}:{rowId:await ga(ka({userId:a,projectId:e,name:t,what:"variable"})),opId:await ga(ka({userId:a,projectId:e,name:t,what:"create_variable"}))}}async function Qk(e){try{const t=await _u(),n=await Wk(t,e.project_id,e.baseline_id,e.as_of),r=await Vk(t,e.project_id,n),a=e.limit??50,i=e.offset??0,s=r.slice(i,i+a);return Kc(bc({variables:null===n?await Jk(t,e.project_id,s):s,total:r.length},Od(r.length,a,i)),{paging:{list:"variables"}})}catch(e){return Yc(Uc(e,{read:!0}))}}async function Kk(e){try{const t=await _u(),n=await Wk(t,e.project_id,e.baseline_id,e.as_of),r=(await Vk(t,e.project_id,n)).find(t=>t.name===e.variable_name)??null;if(!r)return Yc(Sc("Variable",e.variable_name));const a=(await An(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn)).filter(t=>Dk(t.data?.body,e.variable_name)),[i]=null===n?await Jk(t,e.project_id,[r]):[r];return Kc(bc({variable:i,referenced_by:a.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:a.length}))}catch(e){return Yc(Uc(e,{read:!0}))}}async function Yk(e,t){let n;try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();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 Yc(Sc("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 ta({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:t,tokens:Aw(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(ea(a[t]));n&&l.push(ra({op_id:ya(),kind:"set",item_id:null,path:a[t],value:e},n))});const d=await kw({client:r,projectId:e.project_id,ops:l,refusals:i.refusals,variableNames:new Map([[t,e.variable_name]])}),c={...s.data};for(const[e,t]of n)c[e]=t;return jw(d.outcome,!1===e.echo?{name:e.variable_name,updated:!0}:{variable:c},d)}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 Bk(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?Kc(bc({name:e.variable_name,updated:!0})):Kc(bc({variable:l}))}catch(r){const a=Sw(n,t,r);return a?Yk(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}async function Zk(e,t){let n;try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();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 Yc(Ic(`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 Yc(Ic(`Duplicate names in batch (case-insensitive): ${[...new Set(l)].join(", ")}`));const d=await Vk(r,e.project_id,null),c=new Set(d.map(e=>e.name.toLowerCase())),u=n.filter(e=>c.has(e.toLowerCase()));if(u.length>0)return Yc(Ic(`Variable(s) already exist (case-insensitive): ${u.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const p=Nk(e.variables,await Hk(r,e.project_id,n));if("ops"===i){const t=e.variables,n=await Promise.all(t.map((t,n)=>Gk(e.project_id,t.name,e.idempotency_key,n))),a=await Promise.all(t.map((t,r)=>Pk(Fk(n[r],t),e.idempotency_key))),i=crypto.randomUUID(),s=await kw({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 jw(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.`,...p},s)}const m=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})),_=await async function(e,t,n,r){const a=[...new Set(n)];if(r.length>=a.length)return[...r];const i=await An(()=>e.from("project_variables").select("*").eq("project_id",t),fn),s=new Map(i.map(e=>[String(e.name),e])),o=a.filter(e=>!s.has(e));if(o.length>0)throw new Error(`atoms_create_variable: ${o.length} saved variable(s) not found on read back: ${o.slice(0,5).join(", ")}`);return a.map(e=>s.get(e))}(r,e.project_id,m.map(e=>e.name),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,m,a));return Kc(bc({batch_id:crypto.randomUUID(),created:(_??[]).length,variables:!1===e.echo?(_??[]).map(e=>({name:e.name})):_??[],message:`${(_??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`,...p}))}if(!e.name||!e.value)return Yc(Ic("Provide either (name, value) for single variable or variables[] for batch."));if(!s.test(e.name))return Yc(Ic(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const o=(await Vk(r,e.project_id,null)).find(t=>t.name.toLowerCase()===e.name.toLowerCase());if(o)return Yc(Ic(`Variable "${o.name}" already exists in this project (names are unique regardless of case).`));const l=Nk([e],await Hk(r,e.project_id,[e.name]));if("ops"===i){const t=await Gk(e.project_id,e.name,e.idempotency_key,0),n=await kw({client:r,projectId:e.project_id,ops:[await Pk(Fk(t,e),e.idempotency_key)],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 jw(n.outcome,!1===e.echo?{name:e.name,...l}:{variable:a,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`,...l},n)}const d=await Bk(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?Kc(bc({name:e.name,...l})):Kc(bc({variable:d,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`,...l}))}catch(r){const a=Sw(n,t,r);return a?Zk(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}async function Xk(e,t){let n;try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();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 Yc(Sc("Variable",e.name));const o=(await Hk(r,e.project_id,[e.name])).get(e.name.toLowerCase())??0;if(o>0&&!e.force)return Yc(Ic(`Variable "${e.name}" is referenced in ${o} item${o>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(Cw("atoms_delete_variable",e.project_id)){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const n=Dw(t);return Kc(bc({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:o,would_orphan_references:o>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=Hw(e.confirmation_token,t);if(!n.valid)return Yc(Ic(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t=["variables",String(s.id)],n=await ta({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:String(s.id),tokens:Aw(e.base_token),paths:[t],values:[null],name:e.name}]}),a=n.items.get(String(s.id))?.bases.get(ea(t)),i=a?[ra({op_id:ya(),kind:"remove",item_id:null,path:["variables"],row_id:String(s.id),value:null},a)]:[],l=await kw({client:r,projectId:e.project_id,ops:i,refusals:n.refusals});return jw(l.outcome,{deleted:!0,name:e.name,referenced_by_items:o,warning:o>0?`${o} item${o>1?"s":""} still contain {${e.name}}. Those references are now unresolved.`:void 0},l)}const l=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 l?Kc(bc({deleted:!0,name:e.name,referenced_by_items:o,warning:o>0?`${o} item${o>1?"s":""} still contain {${e.name}}. Those references are now unresolved.`:void 0})):Yc(Sc("Variable",e.name))}catch(r){const a=Sw(n,t,r);return a?Xk(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}H(Lk,{createVariableHandler:()=>Zk,deleteVariableHandler:()=>Xk,getVariableHandler:()=>Kk,listVariablesHandler:()=>Qk,updateVariableHandler:()=>Yk});var ej,tj,nj=D({"src/tools/variables.ts"(){Ud(),Tk(),xu(),ai(),Tw(),kr(),Rg(),Uk(),an(),Uw(),tu(),Pk=async(e,t)=>t?La(e):e,Fk=(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}})}}),rj={};async function aj(e,t,n,r,a){let i=0,s=ej;for(;;){const{data:o,error:l}=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:s});if(l&&("57014"===l.code||/statement timeout/i.test(l.message??""))&&Math.floor(s/2)>=tj){s=Math.floor(s/2);continue}if(l)throw new Error(i>0?`${l.message} (${i} items were already updated and the registry is unchanged: call again to finish)`:l.message);const d="number"==typeof o?o:0;if(i+=d,d<s)return i}}async function ij(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 sj(e){try{const t=await _u(),{domains:n,functionTags:r}=await ij(t,e.project_id),a=od(n,r),i=new Set(a.map(Ml)),s=new Set(r.map(Ml)),o=n.filter(e=>!i.has(Ml(e))),{counts:l,orphans:d}=await async function(e,t,n){const r=await An(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn),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),c=o.map(e=>({name:e,registered:!0,item_count:l[e]??0})),u=Object.entries(d).filter(([e])=>!s.has(Ml(e))).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),p=[...c,...u];return Kc(bc({domains:p,total:p.length,registered_count:c.length,unregistered_count:u.length,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")?Yc(qc()):Yc(Uc(e,{read:!0}))}}async function oj(e,t){let n;try{const r=await _u();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const a=t??await vw(r,e.project_id);if("unreadable"===a)return bw();n=a;const i=Jc(e.name).trim().toLowerCase();if(!i)return Yc(Ic("Domain name cannot be empty."));const s=await ij(r,e.project_id);if(null!==Rl(i,s.functionTags))return Yc(Ic(hd(i,!0),uc));const o=Rl(i,s.domains);if(null!==o)return Yc(Ic(hd(o,!1),uc));if("ops"===a){const t={op_id:ya(),kind:"add",item_id:null,path:["taxonomy","domains"],value:i},{run:n}=await Ew({client:r,projectId:e.project_id,op:t});return n.answers.some(e=>"noop"===e.status)?Yc(Ic(hd(i,!1),uc)):jw(n.outcome,{domain:{name:i},message:fd(i)},n)}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 ij(r,e.project_id),n=null!==Rl(i,t);return Yc(Ic(hd(i,n),uc))}return Kc(bc({domain:{name:i},message:fd(i)}))};return await l()}catch(r){const a=Sw(n,t,r);return a?oj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}async function lj(e,t){let n;const r=q_("atoms_update_domain",e);if(r)return Yc(r);try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();if(n=i,"string"!=typeof e.new_name)return Yc(Ic("Pass new_name, the domain's new name."));const{domains:s,functionTags:o}=await ij(r,e.project_id),l=Jc(e.name).trim(),d=function(e,t){const n=e.trim();return"ops"===t?n:n.toLowerCase()}(Jc(e.new_name),"ops"===i?"ops":"main");if(!d)return Yc(Ic("new_name cannot be empty."));const{spelling:c,registered:u}=await md(r,e.project_id,l,s);if(null===c)return Yc(Sc("Domain",l.toLowerCase()));if(null!==Rl(d,[c]))return Yc(Ic(function(e,t){return`"${t}" is the same domain as "${e}" (only the case differs), so there is nothing to rename.`}(c,d)));const p=function(e,t,n,r){if(null!==Rl(t,[e]))return null;const a=Rl(t,r);if(null!==a)return{kind:"function",name:a};const i=Rl(t,n);return null!==i?{kind:"domain",name:i}:null}(c,d,s,o);if("function"===p?.kind)return Yc(function(e,t,n){return{status:"error",message:`Cannot rename "${e}" to "${t}": "${n}" is a function tag, and a tag is a domain or a function, never both, so a domain cannot take a function's name. Choose another name.`,next_steps:["Choose a new_name that is not already a domain or a function tag"],details:{code:ud,functions:[n]}}}(c,d,p.name));if("domain"===p?.kind&&u)return Yc(Ic(gd(p.name)));const m="domain"===p?.kind&&!u,_=m&&p?p.name:d,f=await _d(r,e.project_id,[c]);if(e.dry_run)return Kc(bc({dry_run:!0,rename:{from:c,to:_},items_affected:f,message:m?`Dry run: "${c}" is not registered and "${_}" is, so the ${f} item${1!==f?"s":""} carrying "${c}" would be merged into the registered domain "${_}" (the registry is not changed). Call again with dry_run=false to apply.`:`Dry run: renaming "${c}" → "${d}" would update ${f} item${1!==f?"s":""}. Call again with dry_run=false to apply.`}));if("ops"===i){const t={op_id:ya(),kind:"rename",item_id:null,path:["taxonomy","domains"],value:_,base:c},{run:n,retagged:a}=await Ew({client:r,projectId:e.project_id,op:t,repeat:!0});return zw(n,"deleted")?Yc(Sc("Domain",c.toLowerCase())):zw(n,"invalid","name_taken")?Yc(Ic(gd(_))):jw(n.outcome,{domain:{name:_},renamed_from:c,items_updated:a,message:m?`Domain "${c}" merged into the registered domain "${_}". ${a} item${1!==a?"s":""} updated.`:`Domain renamed "${c}" → "${d}". ${a} item${1!==a?"s":""} updated.`},n)}const h=async()=>{const t=await aj(r,e.project_id,c,_,a);return m?Kc(bc({domain:{name:_},renamed_from:c,items_updated:t,message:`Domain "${c}" merged into the registered domain "${_}". ${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,c,d),Kc(bc({domain:{name:d},renamed_from:c,items_updated:t,message:`Domain renamed "${c}" → "${d}". ${t} item${1!==t?"s":""} updated.`})))};return await h()}catch(r){const a=Sw(n,t,r);return a?lj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}async function dj(e,t){let n;try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();n=i;const{domains:s}=await ij(r,e.project_id),o=Jc(e.name).trim(),{spelling:l,registered:d}=await md(r,e.project_id,o,s),c=l??o.toLowerCase(),u=null===l?0:await _d(r,e.project_id,[l]);if(!d&&0===u)return Yc(Sc("Domain",c));if(u>0&&!e.force)return Yc(Ic(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.`}(c,u)));if(Cw("atoms_delete_domain",e.project_id)){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:c};if(!e.confirmation_token){const e=Dw(t);return Kc(bc({status:"confirmation_required",preview:{domain_name:c,items_using_count:u,items_affected:u,would_strip_from_items:u>0,registered:d},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=Hw(e.confirmation_token,t);if(!n.valid)return Yc(Ic(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t={op_id:ya(),kind:"remove",item_id:null,path:["taxonomy","domains"],value:c},{run:n,retagged:a}=await Ew({client:r,projectId:e.project_id,op:t,repeat:!0});return zw(n,"deleted")?Yc(Sc("Domain",c)):jw(n.outcome,{deleted:!0,name:c,items_updated:a,message:u>0?`Domain "${c}" deleted and stripped from ${a} item${1!==a?"s":""}.`:`Domain "${c}" deleted.`},n)}const p=async()=>{const t=u>0?await aj(r,e.project_id,c,null,a):0;if(d){const{error:t}=await r.rpc("mutate_project_domains",{p_project_id:e.project_id,p_action:"remove_domains",p_values:[c]});if(t)throw new Error(t.message)}return Kc(bc({deleted:!0,name:c,items_updated:t,message:u>0?`Domain "${c}" deleted and stripped from ${t} item${1!==t?"s":""}.`:`Domain "${c}" deleted.`}))};return await p()}catch(r){const a=Sw(n,t,r);return a?dj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(r instanceof Error?r.message:String(r)))}}H(rj,{DOMAIN_CHANGE_BATCH:()=>ej,DOMAIN_CHANGE_BATCH_FLOOR:()=>tj,createDomainHandler:()=>oj,deleteDomainHandler:()=>dj,listDomainsHandler:()=>sj,updateDomainHandler:()=>lj});var cj=D({"src/tools/domains.ts"(){xu(),kr(),Uw(),tu(),pd(),ai(),Tw(),kd(),B_(),ej=50,tj=10}}),uj={};async function pj(e){try{const t=await _u(),{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 An(()=>t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn);if(!a&&0===s.length){if(i)throw new Error(i);return Yc(Sc("Project",e.project_id))}const o={requirements:0,test_cases:0,notes:0};let l=0;const d=[];for(const e of s)if("requirement"===e.type){o.requirements++;const t=e.data?.tags?.domains??[];d.push({id:e.id,domains:t})}else"test-case"===e.type?o.test_cases++:"note"===e.type?o.notes++:"function"===e.type&&l++;"items"===await l_(t,e.project_id)&&(o.functions=l);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=Xp(n);"passed"===e?t.passed++:"failed"===e?t.failed++:"blocked"===e?t.blocked++:t.not_run++}return t}(s),u=Vm(s,await An(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn)),p=gm(s,u),m=d.length,_=Tm(d.filter(e=>p.has(e.id)),d.filter(e=>!p.has(e.id)),await Mm(t,e.project_id)),f=new Set(_.covered.map(e=>e.id)),h={covered:_.covered.length,uncovered:_.uncovered.length,total:m,percent:Nm(_.covered.length,m),via_mitigation:qm(d.map(e=>e.id),f,wm(s,u)),..._.coveredByDocument?{covered_by_document:_.coveredByDocument}:{}},g=await e_(t,e.project_id),y=function(e,t){const n=new Set(t.flatMap(e=>e.test_case_ids??[]));let r=0;for(const t of e)"test-case"===t.type&&n.has(t.id)&&"passed"===Xp(t)&&r++;return{requirements:new Set(t.map(e=>e.requirement_id)).size,test_cases:r}}(s,await t_(t,e.project_id,p,g.releaseId)),w=new Map;for(const e of d){const t=e.domains.length>0?e.domains:["(untagged)"],n=f.has(e.id);for(const e of t){w.has(e)||w.set(e,{covered:0,total:0});const t=w.get(e);t.total++,n&&t.covered++}}const v=Array.from(w.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:Nm(t.covered,t.total)})),b=new Date;b.setDate(b.getDate()-7);const k=!0===await Zg(t,e.project_id),j=await async function(e,t,n,r){const a=await qg(e,"mcp_count_recent_changes",{p_project_id:t,p_since:n,p_project_changes:r});return a?xg(a.data):null}(t,e.project_id,b.toISOString(),k),{count:S,error:A}=null!==j?{count:j,error:null}:k?await t.from("project_changes").select("seq",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("committed_at",b.toISOString()):await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",b.toISOString());if(A)throw new Error(A.message);return Kc(bc({project_id:e.project_id,project_name:a??`Project ${e.project_id.slice(0,8)}`,counts:o,test_status:c,coverage:h,coverage_by_domain:v,rerun:y,rerun_scope:g.label,recent_changes:S??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(uj,{projectSummaryHandler:()=>pj});var mj=D({"src/tools/project-summary.ts"(){xu(),Wg(),Um(),o_(),zm(),Hm(),kr(),tu(),py(),k_(),zg()}}),_j={};async function fj(e){try{const t=await _u();let n,r;if(e.query&&e.query.trim().length>0){const a=await Ug(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:Xp(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),r=a.totalCount}else{const a=await Cg(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:Xp(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 An(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn),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 Kc(bc({items:n,filters:{domains:a.domains,levels:a.levels,types:d_(await l_(t,e.project_id))},project_id:e.project_id},Od(r,e.limit,e.offset)),{paging:{list:"items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(_j,{browseHandler:()=>fj});var hj=D({"src/tools/browse.ts"(){Ud(),xu(),Wg(),tu(),fm(),k_()}}),gj={};async function yj(e){try{const t=e.direction??"downstream",n=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await _u(),a=await Dg(r,e.project_id,e.item_id);if(!a)return Yc(Sc("Item",e.item_id));const i=await An(()=>r.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn),s=Vm(i,await An(()=>r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn)),o=new Map;for(const e of i)o.set(e.id,{title:rh(e),type:e.type});const l=new Map,d=(e,t,n)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:n})};for(const e of s){const n=ah(e,e=>o.get(e)?.type),r=n.type;"upstream"!==t&&"both"!==t||(Yf.includes(r)&&d(n.from_id,n.to_id,r),Zf.includes(r)&&d(n.to_id,n.from_id,Xf[r]??r)),"downstream"!==t&&"both"!==t||(Zf.includes(r)&&d(n.from_id,n.to_id,r),Yf.includes(r)&&d(n.to_id,n.from_id,Xf[r]??r)),"related"===r&&(d(n.from_id,n.to_id,"related"),d(n.to_id,n.from_id,"related"))}const c=new Set;c.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(let e=0;e<m.length;e++){const{id:t,depth:r,path:a}=m[e];if(c.has(t))continue;if(null!==n&&r>n)continue;c.add(t);const i=o.get(t);if(i&&(u.push({item_id:t,title:i.title,type:i.type,depth:r,relationship_path:a,shared_variables:[]}),r>p&&(p=r),null===n||r<n))for(const e of l.get(t)??[])c.has(e.neighbor)||m.push({id:e.neighbor,depth:r+1,path:[...a,{from_id:t,to_id:e.neighbor,relationship_type:e.relType}]})}let _=0;if(e.include_variable_refs){const t=await An(()=>r.from("project_variables").select("id, name").eq("project_id",e.project_id),fn),n=function(e,t,n){const r=new Map,a=t.find(t=>t.id===e);if(!a)return r;const i=Ck(a),s=n.filter(e=>"string"==typeof e.name&&e.name&&i.includes(`{${e.name.toLowerCase()}}`));if(0===s.length)return r;for(const n of t){if(n.id===e)continue;const t=Ck(n);if(t)for(const e of s)t.includes(`{${e.name.toLowerCase()}}`)&&(r.has(n.id)||r.set(n.id,new Set),r.get(n.id).add(e.name))}return r}(e.item_id,i,t),a=new Map(u.map(e=>[e.item_id,e]));for(const[t,r]of n){const n=[...r].sort(),i=a.get(t);if(i){i.shared_variables=n;continue}const s=o.get(t);s&&(u.push({item_id:t,title:s.title,type:s.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:t,relationship_type:`variable_ref:${n[0]}`}],shared_variables:n}),_++)}}const f={};for(const e of u)f[e.type]=(f[e.type]??0)+1;const h=o.get(e.item_id),g=qd(u,e.offset,e.limit);return Kc(bc({root:{item_id:e.item_id,title:h?.title??a.title,type:h?.type??a.type},impacted_items:g.rows,summary:{total_impacted:u.length,by_type:f,max_depth_reached:p,..._>0?{variable_impact_count:_}:{}}},g.meta),{paging:{list:"impacted_items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}H(gj,{impactAnalysisHandler:()=>yj});var wj,vj,bj,kj,jj,Sj,Aj,$j,xj,Ij,qj,Oj,Ej,zj=D({"src/tools/impact-analysis.ts"(){xu(),Wg(),_h(),kr(),Uk(),Ud(),tu()}});function Mj(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function Rj(e){return null==e?"":String(e)}function Tj(e){if(null==e||""===e)return"null";if(Array.isArray(e))return 0===e.length?"null":`[${e.map(Tj).join(",")}]`;if("object"==typeof e){const t=e,n=Object.keys(t).filter(e=>"null"!==Tj(t[e])).sort();return 0===n.length?"null":`{${n.map(e=>`${JSON.stringify(e)}:${Tj(t[e])}`).join(",")}}`}return JSON.stringify(e)}function Cj(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function Dj(e){return null==e||""===e?null:e}function Hj(e,t=!0){const n=Dj(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=>Hj(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)}:${Hj(r[e],t)}`).join(",")}}`}function Nj(e,t){return e.some(e=>!t.includes(e))||t.some(t=>!e.includes(t))}function Pj(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 Fj(e){const t=Object.prototype.hasOwnProperty.call(e,"parent"),n=Object.prototype.hasOwnProperty.call(e,"child");if(!t&&!n)return e.relationships;const r=Cj(e.relationships);return{...r,parent:[...Pj(r.parent),...Pj(e.parent)],child:[...Pj(r.child),...Pj(e.child)]}}function Uj(e,t){const n=Cj(e),r="parents"===t?n.parent:"children"===t?n.child:void 0;return Array.from(new Set([...Pj(n[t]),...Pj(r)])).sort()}function Lj(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){const e=Cj(n);if("string"!=typeof e.date||!e.date.trim())continue;const r={};for(const t of Aj){const n=Dj(e[t]);null!==n&&(r[t]=n)}t.set(e.date,r)}return t}function Wj(e,t){const n=Lj(e),r=Lj(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&&Aj.every(e=>Hj(t[e])===Hj(a[e])))});return[Object.fromEntries(a.map(e=>[e,n.get(e)??null])),Object.fromEntries(a.map(e=>[e,r.get(e)??null]))]}function Vj(e,t){const n=[];Dj(e.title)!==Dj(t.title)&&n.push({path:"title"}),Dj(e.type)!==Dj(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 jj)Dj(r[e])!==Dj(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)?Nj(t,n):Hj(t)!==Hj(n))&&i("tags",e)}const l=Cj(r.analysis_props),d=Cj(a.analysis_props);for(const e of Array.from(new Set([...Object.keys(l),...Object.keys(d)])).sort())!wj.has(e)&&Mj(l[e])&&Mj(d[e])&&Rj(l[e])!==Rj(d[e])&&i("analysis_props",e);Hj(r.ownership)!==Hj(a.ownership)&&i("ownership");for(const e of Sj)Nj(Uj(Fj(r),e),Uj(Fj(a),e))&&i("relationships",e);Object.keys(Wj(r.runs,a.runs)[0]).length>0&&i("runs");for(const e of Array.from(new Set([...Object.keys(r),...Object.keys(a)])).sort())$j.has(e)||Hj(r[e],!1)!==Hj(a[e],!1)&&i(e);return n}function Bj(e,t){const n=Vj(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"),(Jj(e)||Jj(t)?Dj(Qj(e))!==Dj(Qj(t)):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=Cj(e),r=Cj(t),a=[],i=Cj(n.analysis_props),s=Cj(r.analysis_props),o=Array.from(new Set([...Object.keys(i),...Object.keys(s)])).sort();for(const e of o){if(wj.has(e))continue;const t=i[e],n=s[e];Mj(t)&&Mj(n)?Rj(t)!==Rj(n)&&a.push(`analysis_props.${e}`):Tj(t)!==Tj(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},d=l(Cj(n.fields)),c=l(Cj(r.fields)),u=Array.from(new Set([...d.keys(),...c.keys()])).sort();for(const e of u)if((d.get(e)?.value??"")!==(c.get(e)?.value??"")){const t=c.get(e)?.key??d.get(e)?.key??e;a.push(`fields.${t}`)}return a}(e.data,t.data).filter(e=>a.has(e.split(".")[0])))),i}function Jj(e){return"test-case"===e.type}function Gj(e){const t=Cj(e.data);return Jj(e)?im(t):t.runs}function Qj(e){const t=Cj(e.data);return Jj(e)?Xp({type:"test-case",data:t})??null:t.status??null}function Kj(e,t){for(const[n,r]of Object.entries(e))if(n.toLowerCase()===t)return"string"==typeof r?r:null;return null}function Yj(e,t,n){const r=Cj(e.data),a=Cj(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:Qj(e),to:Qj(t)};else if("tags.level"===o)s[o]={from:Cj(r.tags).level??null,to:Cj(a.tags).level??null};else if("tags.domains"===o)s[o]={from:Cj(r.tags).domains??null,to:Cj(a.tags).domains??null};else if(o.startsWith("analysis_props.")){const e=o.slice(15);s[o]={from:Cj(r.analysis_props)[e]??null,to:Cj(a.analysis_props)[e]??null}}else if(o.startsWith("fields.")){const e=o.slice(7).toLowerCase();s[o]={from:Kj(Cj(r.fields),e),to:Kj(Cj(a.fields),e)}}else if("data"===o){const n=Vj(e,t),l=new Set(n.map(e=>e.path)),d=Array.from(new Set(n.flatMap(e=>e.lane?[e.lane]:[]))).sort(),c={},u={},p=Jj(e)||Jj(t);for(const n of d){if("status"===n&&p)continue;const[s,o]="runs"===n?Xj(n,Gj(e),Gj(t),i,l):"relationships"===n?Xj(n,Fj(r),Fj(a),i,l):Xj(n,r[n],a[n],i,l);Tj(s)!==Tj(o)&&(c[n]=s??null,u[n]=o??null)}s[o]={from:c,to:u}}else s[o]={from:null,to:null};return s}function Zj(e,t){return null===e||"object"!=typeof e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).filter(([e])=>!t(e)))}function Xj(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[Zj(t,e),Zj(n,e)]}if("relationships"===e){const e=Sj.filter(e=>a.has(`data.relationships.${e}`)),r=t=>Object.fromEntries(e.map(e=>[e,Uj(t,e)]));return[r(t),r(n)]}if("runs"===e)return Wj(t,n);if("analysis_props"===e){const e=e=>r.has(`analysis_props.${e}`);return[Zj(t,e),Zj(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[Zj(t,e),Zj(n,e)]}return Array.isArray(t)&&Array.isArray(n)?function(e,t){const n={},r={},a=eS(e),i=eS(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;Tj(t)!==Tj(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++)Tj(e[a])!==Tj(t[a])&&(n[a]=e[a]??null,r[a]=t[a]??null);return[n,r]}(t,n):[t,n]}function eS(e){const t=[];for(const n of e){const e=Cj(n).id;if("string"!=typeof e||"order"===e)return null;t.push(e)}return new Set(t).size===t.length?t:null}function tS(e){return"string"==typeof e?1:Array.isArray(e)?e.reduce((e,t)=>e+tS(t),0):null!==e&&"object"==typeof e?Object.values(e).reduce((e,t)=>e+tS(t),0):0}function nS(e){const t=JSON.stringify(e,null,2),n=t.split("\n").length;return t.length+n*qj+Ij*tS(e.diff)+2}function rS(e,t,n){if("string"==typeof e){if(e.length<=t+Ej)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=>rS(e,t,n)):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,rS(r,t,n)])):e}function aS(e,t){const n=e.diff??{};for(const r of Oj){const a={n:0},i=rS(n,r,a),s={...e,diff:i,...a.n>0?{diff_clipped:!0}:{}};if(nS(s)<=t)return s}const r={n:0},a=rS(n,Oj[Oj.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]]},d={...e,diff:r,...i,diff_omitted:s.length-n-1};if(nS(d)>t)break;o=r,l=d}return 0===l.diff_omitted&&delete l.diff_omitted,l}var iS,sS=D({"src/core/baseline-diff.ts"(){fm(),wj=new Set(["field_source","approved","approved_at","approved_by","approved_note"]),vj=["approval_state","approver_user_id","rev_label","approved_at","requires_impacted_approval"],bj=["id","title","type","metadata",...vj],kj=["parent","child"],jj=["body","summary","status","level","isLocked","lockedBy","lockedAt"],Sj=["parents","children","related","verifies","verified_by","mitigated_by","mitigates","traces_to","traced_by","allocated_to","allocated_from","decomposes_to","decomposed_from","affects","affected_by","event_hazard","hazard_events","event_goal","goal_events"],Aj=["result","by","note","asset"],$j=new Set(["tags","ownership","relationships","runs",...jj,...bj,...kj]),xj=2e4,Ij=29,qj=6,Oj=[1e3,400,160,60,20],Ej=40}});function oS(e,t){const n=e.filter(e=>"object"==typeof e&&null!==e);if(0===n.length)return"";const r=[];let a=n.length;for(const e of iS){const i=n.filter(e.test).length;0!==i&&(a-=i,r.push(`${i} ${t}(s) ${"variable"===t&&e.variable||e.words}.`))}return a>0&&r.push(`${a} ${t}(s) were left alone for another reason (each entry's reason says which).`),r.push(`They are listed in ${"item"===t?"items_skipped":"variables_skipped"}.`),r.join(" ")}function lS(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 dS,cS,uS,pS,mS=D({"src/core/restore-preview.ts"(){iS=[{test:e=>"changed_since_source"===e.reason||"clash"===e.reason,words:"were left alone because someone changed them after the preview"},{test:e=>"deleted"===e.reason,words:"were left alone because they are in the Trash or no longer exist",variable:"were left alone because someone removed them after the preview"},{test:e=>"refused"===e.reason&&!0!==e.partly_applied,words:"could not be restored: the server refused their version in the snapshot (refused_reason says why)"},{test:e=>"refused"===e.reason&&!0===e.partly_applied,words:"were partly restored: the server refused part of their version in the snapshot (refused_reason says why)"},{test:e=>"link_end_skipped"===e.reason,words:"were left alone because an item linked with them was not restored"},{test:e=>"asil_put_back"===e.reason,words:"were left alone because a row that gives them their ASIL was not restored"},{test:e=>"locked"===e.reason,words:"were left alone because they are locked"},{test:e=>"typing"===e.reason,words:"were left alone because someone was typing in them"},{test:e=>"forbidden"===e.reason,words:"were left alone because a change to them is waiting for approval or is not allowed"},{test:e=>"approved"===e.reason,words:"were left alone because they are approved under change control"}]}}),_S={};function fS(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):null}async function hS(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 gS(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 yS(e,t,n){const{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a)return Yc(Vc(a.message));if(!r)return Yc(Sc("Project",t));if(r.deleted_at)return Yc($r());const{data:i,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?Yc(Vc(s.message)):!0!==(i?.feature_flags??{})[n]?Yc(jc(`Feature '${n}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function wS(e){try{const t=await _u(),n=await async function(e,t){const n=[],r=new Set;for(let a=0;;){const{data:i,error:s}=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}).range(a,a+1e3-1);if(s)throw new Error(`listBaselines: ${s.message}`);const o=i??[];if(0===o.length)return n;let l=0;for(const e of o)r.has(e.id)||(r.add(e.id),n.push(e),l+=1);if(0===l)return n;a+=o.length}}(t,e.project_id),r=Math.max(e.offset??0,0),a=Math.min(Math.max(e.limit??50,1),100);return Kc(bc({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},Od(n.length,a,r)),{paging:{list:"baselines"}})}catch(e){return fS(e)??Yc(Uc(e,{read:!0}))}}async function vS(e){try{const t=await _u(),n=await yS(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?Yc(jc(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):Yc(Uc(a)):Kc(bc({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 fS(e)??Yc(Uc(e))}}async function bS(e){try{const t=await _u(),n=await Ng(t,e.baseline_id);if(!n)return Yc(Sc("Baseline",e.baseline_id));const r=await yS(t,n.project_id,"baselines_enabled");if(r)return r;if(null!==n.locked_at)return Yc(jc("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 Yc(Sc("Project",n.project_id));const{data:i,error:s}=await t.auth.getUser();if(qt(s))return Yc(Ot());const o=i?.user?.id;if(!o)return Yc(qc());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 Yc(jc("Only admins can lock baselines",["Ask an org admin to lock this baseline"]));const{data:d,error:c}=await t.rpc("lock_baseline",{p_baseline_id:e.baseline_id});return c?Yc(Uc(c)):Kc(bc({id:d.id,locked_at:d.locked_at,locked_by:d.locked_by}))}catch(e){return fS(e)??Yc(Uc(e))}}async function kS(e){try{const t=await _u(),[n,r]=await Promise.all([Ng(t,e.baseline_a_id),Ng(t,e.baseline_b_id)]);if(!n||!r)return Yc(Sc("Baseline","one of the baseline_ids"));if(n.project_id!==r.project_id)return Yc(jc("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[a,i]=await Promise.all([Fg(t,n.project_id,yn(n.id)),Fg(t,r.project_id,yn(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(),d=[];let c=0,u=0,p=0;for(const e of l){const t=s.get(e),n=o.get(e);if(!t&&n)c++,d.push({item_id:e,change_type:"added"});else if(t&&!n)u++,d.push({item_id:e,change_type:"removed"});else if(t&&n){const r=Bj(t,n);r.length>0&&(p++,d.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=d.slice(m,m+_);const h={offset:m,limit:_,total:d.length};if(!0===e.detail){const e=function(e,t,n,r,a={}){const i=a.budget??xj,s=a.diffOf??Yj,o=[];let l=0,d=!1,c=!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=nS(e);if(l+a>i){if(o.length>0)break;e=aS(e,i),a=nS(e)}e.diff_clipped&&(d=!0),e.diff_omitted&&(c=!0),o.push(e),l+=a}if(o.length===e.length&&!d&&!c)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.`)),d&&p.push('Long values in an item were clipped to fit, each marked "[clipped, N more characters]".'),c&&p.push("diff_omitted counts the changed fields of an item whose values did not fit; their names are still in fields_changed."),(d||c)&&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 Kc(bc({summary:{added:c,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}}}),{paging:{list:"items",resume:e=>({data:{page_info:{...h,returned:e,next_offset:m+e,truncated:!0}},next:`offset=${m+e}`})}})}catch(e){return fS(e)??Yc(Uc(e,{read:!0}))}}async function jS(e,t){let n;try{const o=await _u(),l=await Ng(o,e.baseline_id);if(!l)return Yc(Sc("Baseline",e.baseline_id));const d=await yS(o,l.project_id,"baselines_enabled");if(d)return d;const{data:c}=await o.from("projects").select("org_id").eq("id",l.project_id).maybeSingle();if(!c)return Yc(Sc("Project",l.project_id));const{data:u,error:p}=await o.auth.getUser();if(qt(p))return Yc(Ot());const m=u?.user?.id;if(!m)return Yc(qc());const{data:_}=await o.from("org_members").select("role").eq("user_id",m).eq("org_id",c.org_id).maybeSingle();if(!_||"admin"!==_.role)return Yc(jc("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const{data:f}=await o.rpc("cc_project_is_controlled",{p_project_id:l.project_id});if(!0===f)return Yc(jc("Change control is on for this project. Release review before restoring a baseline.",["Release review on the project, then run the restore"]));const h=t??await vw(o,l.project_id);if("unreadable"===h)return bw();n=h;const g=await Fg(o,l.project_id,yn(l.id)),y=await En(g.map(e=>e.id),e=>o.from("items").select("*").eq("project_id",l.project_id).in("id",e)),w=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}]})}(g,y),v=await On(o,l.project_id,yn(l.id)),b={tool:"atoms_restore_baseline",project_id:l.project_id,target:l.id},k=Cw(b.tool,l.project_id);if(k&&!0===e.confirm&&e.confirmation_token){const t=Hw(e.confirmation_token,b);if(!t.valid)return Yc(Ic(`confirmation_token rejected: ${t.reason}`))}if(!0!==e.confirm||k&&!e.confirmation_token){const e="ops"===h?await Yr(o,l.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 o.rpc("restore_baseline_preview_counts",{p_baseline_id:l.id})),n=k?Dw(b):null;return Kc(bc({...n?{status:"confirmation_required",confirmation_token:n.token,expires_at:n.expires_at,expires_in_seconds:n.expires_in_seconds,message:(i=n.expires_in_seconds,s=null!==e,`Re-call atoms_restore_baseline with the same baseline_id, confirm true and this confirmation_token${s?", with the source_seq above,":""} within ${i}s to execute.`)}:{},preview:!0,...null!==e?{source_seq:e,items:w.slice(0,dS).map(e=>({id:e.id,type:e.type,title:e.title,changed_fields:e.diff_summary?.changed_fields??[]})),...w.length>dS?{items_truncated:!0}:{}}:{},items_to_restore:w.length,variables_to_restore:v.length,field_definitions_to_restore:l.field_definitions_snapshot?.length??null,items_to_trash:t.items_to_trash,variables_to_archive:t.variables_to_archive,summary:(r=w.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"===h)return"number"!=typeof e.source_seq||!Number.isInteger(e.source_seq)||e.source_seq<0?Yc(Ic("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.",cS)):await async function(e,t){const n=Date.now();let r=t.bulkId??ya(),a=t.afterId??null,i=!1,s=null;const o={restored:0,trashed:0,variables:0,archived:0,fields:0,total:0};let l=!1;const d=[],c=[],u=[],p=ci(e),m=p&&t.bulkId?await async function(e,t,n,r=ti){try{if(!e.supabaseUrl||!e.accessToken||!n)return null;const a=e.fetch??fetch,i=await a(`${di(e,t,n)}&seq=not.is.null&select=seq&order=seq.desc&limit=1`,{method:"GET",headers:si(e),signal:AbortSignal.timeout(r)});if(!i.ok)return console.error(`[embed-on-save] change mark read failed (${i.status})`),null;const s=await i.json(),o=Array.isArray(s)&&s.length>0?Number(s[0].seq):0;return Number.isFinite(o)?o:null}catch(e){return console.error("[embed-on-save] change mark read failed:",e instanceof Error?e.message:e),null}}(p,t.projectId,t.bulkId):null;try{do{const{data:n,error:p}=await Jd(()=>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:pS}),{scope:t.projectId,delays:Fd});if(p&&Ld(p)){s="busy";break}if(p)throw Object.assign(new Error(p.message),{code:p.code});const m=n??{};r=m.bulk_id??r,a=m.next_after_id??null,o.restored+=m.items_restored??0,o.trashed+=m.items_trashed??0,o.variables+=m.variables_restored??0,o.archived+=m.variables_archived??0,o.fields+=m.field_definitions_restored??0,l=l||!0===m.field_definitions_skipped,o.total=Math.max(o.total,m.total??0),d.push(...m.items_skipped??[]),c.push(...m.variables_skipped??[]),u.push(...Array.isArray(m.not_restored)?m.not_restored:[]),i=!0===m.done}while(!i&&Date.now()-n<uS)}finally{p&&ui(async function(e,t,n,r){try{if(!e.supabaseUrl||!e.accessToken||!n)return;const a=e.fetch??fetch,i=[];let s=r;for(;;){const r=`${di(e,t,n)}&item_id=not.is.null`+(null!==s?`&seq=gt.${s}`:"")+`&select=seq,kind,item_id,path&order=seq.asc&limit=${ei}`,o=await a(r,{method:"GET",headers:si(e)});if(!o.ok){console.error(`[embed-on-save] change read failed (${o.status})`);break}const l=await o.json();if(!Array.isArray(l)||0===l.length)break;i.push(...l);const d=Number(l[l.length-1].seq);if(!Number.isFinite(d)||null!==s&&d<=s)break;s=d}const o=li(i);o.length>0&&await oi(e,t,o)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}(p,t.projectId,r,m))}const _=lS({items_restored:o.restored,items_trashed:o.trashed,variables_archived:o.archived}),f=function(e,t=[],n=!1){return[oS(e,"item"),oS(t,"variable"),n?"The field definitions were left as someone changed them after the preview.":""].filter(Boolean).join(" ")}(d,c,l),h=f?` ${f}`:"",g=i?_+h:`Restore not finished. ${_}${h} Call atoms_restore_baseline again with confirm true, source_seq ${t.sourceSeq}, bulk_id ${r} and after_id ${a??""} to continue.`;return Kc(bc({ok:!0,complete:i,bulk_id:r,...i?{}:{next_after_id:a},...s?{paused:s}:{},items_restored:o.restored,variables_restored:o.variables,field_definitions_restored:o.fields,field_definitions_skipped:l,items_trashed:o.trashed,variables_archived:o.archived,items_skipped:d,...c.length>0?{variables_skipped:c}:{},not_restored:u,progress:{items_restored:o.restored,items_total:o.total||null},summary:g}))}(o,{baselineId:l.id,projectId:l.project_id,userId:m,sourceSeq:e.source_seq,bulkId:e.bulk_id,afterId:e.after_id});const j=await hS(o,{baselineId:l.id,projectId:l.project_id,userId:m});return function(e,t,n){const r=ci(e);r&&0!==n.length&&ui(oi(r,t,n))}(o,l.project_id,function(e,t){const n=new Map;for(const e of t)e&&"string"==typeof e.id&&n.set(e.id,e);const r=new Set;for(const t of e){if(!t||"string"!=typeof t.id||""===t.id)continue;const e=n.get(t.id);e&&ii(e.data)===ii(t.data)||r.add(t.id)}return[...r]}(g,y)),Kc(bc({ok:!0,items_restored:j.items_restored,variables_restored:j.variables_restored,field_definitions_restored:j.field_definitions.length,items_trashed:j.items_trashed,variables_archived:j.variables_archived,summary:lS(j)}))}catch(r){const a=Sw(n,t,r);return a?jS(e,a):fS(r)??Yc(Uc(r))}var r,a,i,s}H(_S,{RESTORE_CALL_BUDGET_MS:()=>uS,createBaselineHandler:()=>vS,diffBaselinesHandler:()=>kS,listBaselinesHandler:()=>wS,lockBaselineHandler:()=>bS,restoreBaselineHandler:()=>jS,restoreBaselineStateAtomicallyViaMain:()=>hS,syncRestoredItemRelationships:()=>gS});var SS,AS=D({"src/tools/baselines.ts"(){Ud(),xu(),ai(),nc(),Tw(),Mt(),JA(),tu(),Wg(),Ym(),sS(),mS(),Uw(),kr(),hi(),dS=200,cS=400,uS=2e4,pS=200}});function $S(e){return!!e&&(Ld(e)||Kt(String(e.message??""))||"PT409"===String(e.code??""))}async function xS(e,t=SS){const n=async()=>{try{return await e()}catch(e){return{message:e instanceof Error?e.message:String(e)}}};let r=await n();for(const e of t){if(!$S(r))return r;await Dd.sleep(Math.round(e*Dd.jitter())),r=await n()}return r}function IS(e){const t=[],n={};return e.controlType&&(n.control_type_not_written={row_id:e.rowId,req_id:e.reqId,control_type:e.controlType.value,reason:e.controlType.message},t.push(`the control type ${e.controlType.value} was not written onto ${e.rowId}`)),e.asil&&(n.asil_not_written={req_id:e.reqId,asil:e.asil.level,source_row:e.rowId,reason:e.asil.message},t.push(`ASIL ${e.asil.level} was not written onto ${e.reqId}`)),0===t.length?{}:(n.warning=`The link ${e.rowId} mitigated by ${e.reqId} is saved, but ${t.join(" and ")} because another write was on the item. Call atoms_link_mitigation again with the same arguments to finish; the link is not added twice.`,n)}var qS,OS,ES,zS,MS=D({"src/core/after-link-save.ts"(){nc(),an(),SS=[100,250,500]}});function RS(e){return"string"==typeof e}function TS(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:RS(n.by)?n.by:null,on:RS(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:RS(e.by)?e.by:"",on:RS(e.on)?e.on:"",count:"number"==typeof e.count&&Number.isFinite(e.count)?e.count:0})):[]}}}function CS(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>ES)return{ok:!1,error:`scenario_catalogs accepts at most ${ES} 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(!RS(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),!RS(e.name)||!e.name.trim())return{ok:!1,error:`catalog "${e.id}" must carry a non-empty name`};if(e.name.length>OS)return{ok:!1,error:`catalog "${e.id}" name must be at most ${OS} characters`};if(!Array.isArray(e.entries))return{ok:!1,error:`catalog "${e.id}" entries must be an array`};if(e.entries.length>qS)return{ok:!1,error:`catalog "${e.id}" accepts at most ${qS} 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(!RS(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=RS(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>OS)return{ok:!1,error:`an entry of catalog "${e.id}" must be at most ${OS} characters`};const s=Array.isArray(n.function_tags)?n.function_tags.filter(RS).map(e=>e.trim()).filter(Boolean):[],o=Array.isArray(n.function_ids)?n.function_ids.filter(RS).map(e=>e.trim()).filter(Boolean):null;a.push(null===o?{id:n.id,text:r,function_tags:s}:{id:n.id,text:r,function_tags:s,function_ids:o})}const s=TS(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 DS,HS=D({"src/core/catalogs.ts"(){qS=50,OS=100,ES=200,zS=["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]}}),NS={};function PS(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}function FS(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function US(e){const t=e?.relationships?.verified_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function LS(e){return JSON.parse(JSON.stringify(e??{}))}async function WS(e,t,n,r){const a=await P_(n,Object.keys(r),()=>l_(e,t));if(a)return{ok:!1,result:Yc(Ic(a,uc))};if(!(__ in r))return{ok:!0,rest:r,writes:{},answer:{}};const{[__]:i,...s}=r,o=await async function(e,t,n){if("string"!=typeof n)return{ok:!1,error:{status:"error",message:'Validation error: source_function_id must be a string, the id of a Function item ("" clears it on a project with Function items turned on). Nothing was written.',next_steps:["Find the project's Functions with atoms_list_items type 'function'"],code:"function_id_invalid",retryable:!1}};const r=n.trim(),a=await l_(e,t);if(!r&&"tags"===a)return{ok:!1,error:{status:"error",message:w_,next_steps:[...v_],code:"function_items_off",retryable:!1}};const i=await T_(e,t,r?[r]:[],a);if(!i.ok)return i;const s=i.functions[0];return s?{ok:!0,writes:{source_function_id:s.id,source_function:s.title},answer:{source_function_id:s.id,source_function_title:s.title}}:{ok:!0,writes:{source_function_id:"",source_function:""},answer:{source_function_id:null,source_function_title:null}}}(e,t,i);return o.ok?{ok:!0,rest:s,writes:o.writes,answer:o.answer}:{ok:!1,result:Yc(o.error)}}async function VS(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 ll(n)}function BS(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function JS(e){return Yc("tool"===e.kind?e.error:Ic(e.message,uc))}function GS(e,t,n){return Ef(t,n).map(t=>({op_id:ya(),kind:t.kind,item_id:e,path:[...t.path],value:t.value}))}async function QS(e,t,n,r){const a=BS(r);if(!a)return!1;const i=await Dg(e,t,a);return Df(n,i?.data)}async function KS(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:dl(n,a,a?null:await VS(e,t))}}async function YS(e,t,n,r){const a=BS(r),i=a?await Dg(e,t,a):null;return KS(e,t,n,i?.data)}function ZS(e,t,n,r={}){const a=r.where?`${r.where}: `:"",i=function(e,t){const n=Ao[e];if(!n)return{ok:!0,fields:t};const r=Object.keys(t??{}),a=[];for(const e of r){const i=Object.prototype.hasOwnProperty.call(n.aliases,e)?n.aliases[e]:e;if(i!==e&&r.includes(i))return{ok:!1,message:`${e} and ${i} are the same field on a ${n.row} (${e} is its ${n.kind}); send one of them. Nothing was written.`};a.push([i,t[e]])}return{ok:!0,fields:Object.fromEntries(a)}}(e,n??{});if(!i.ok)return{ok:!1,message:`${a}${i.message}`};n=i.fields;const s=new Set([...So[e],...r.extraKeys??[]]),o=Object.keys(n??{});if(0===o.length)return{ok:!1,message:`${a}fields must contain at least one key`};const l=o.filter(e=>Zo.includes(e));if(l.length>0)return{ok:!1,message:`${a}${Vl(e,l)}`};const d=Bl(e);if(d&&o.includes(d.field))return{ok:!1,message:`${a}${Jl(e)}`};const c=o.filter(e=>!s.has(e));if(c.length>0)return{ok:!1,message:`${a}Unknown field(s) for ${e}: ${c.join(", ")}. Allowed: ${[...s].sort().join(", ")}`};const u=jo[e],p={};for(const r of o){const i=n[r];if(u[r]){const t="number"==typeof i?String(i):i;if("string"!=typeof t||!u[r].includes(t))return{ok:!1,message:`${a}Invalid ${r} value ${JSON.stringify(i)} for ${e}. Allowed: ${u[r].join(", ")}`};p[r]=t}else{if("string"!=typeof i)return{ok:!1,message:`${a}Field '${r}' must be a string`};const e=fl(t,r,i);if(e)return{ok:!1,message:`${a}${e}`};p[r]=i}}return{ok:!0,writes:p}}async function XS(e,t){let n;const r=q_("atoms_create_analysis",e);if(r)return Yc(r);try{const r=await _u(),i=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const s=t??await vw(r,e.project_id);if("unreadable"===s)return bw();n=s;const o="string"==typeof(a=e.subtype)&&Object.prototype.hasOwnProperty.call(No,a)?No[a]:null;if(!o)return Yc(Ic(function(e){return`subtype must be one of: ${Po.join(", ")} (got ${JSON.stringify(e)})`}(e.subtype)));const l=e.source_req_ids??[],d=e.source_function_ids??[],c=(e.source_assets??[]).map(e=>Jc(e));if("hara"===o&&l.length>0)return Yc(Ic("A HARA is seeded from functions, never requirements (a requirement is an output of the analysis): pass source_function_ids (a security risk analysis: source_assets) and omit source_req_ids"));if("dfmea"===o&&(d.length>0||c.length>0))return Yc(Ic("source_function_ids and source_assets apply to hara only; seed a DFMEA with source_req_ids"));if(l.length>50)return Yc(Ic("source_req_ids supports at most 50 entries per call"));if(d.length>b_||c.length>b_)return Yc(Ic(`source_function_ids and source_assets support at most ${b_} entries per call`));if(l.length>0){const{data:t,error:n}=await r.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 a=new Map((t??[]).map(e=>[e.id,e])),i=l.filter(e=>!a.has(e));if(i.length>0)return Yc(Sc("Source requirement(s)",i.join(", ")));const s=l.filter(e=>{const t=a.get(e);return"requirement"!==t.type||DS.has(t.data?.req_type)});if(s.length>0)return Yc(Ic(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${s.join(", ")}`))}if(void 0!==e.variant&&!xl(e.subtype).includes(e.variant))return Yc(Ic(function(e,t){const n=xl(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 u=await VS(r,e.project_id),p=e.variant??function(e,t){return"medical"===t?Uo[e]:Fo[e]}(e.subtype,u),m=await async function(e,t,n,r){const a=n??"automotive";return Ai(a).includes(r)||"automotive"===a&&await $i(e,t,a)?null:function(e,t){const n=Ai(e);return`Cannot create a ${wi[t]}: this project's industry is ${vi[e]}, which offers ${n.length?function(e){const t=e.map(e=>wi[e]);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}(n):"no analyses"}. Analyses already in the project keep working. `+(n.length?"Create one of the offered analyses instead, or change the ":"To create one, change the ")+"industry on the project settings page (allowed while no analysis in the project would end up outside the new industry)."}(a,r)}(r,e.project_id,u,p);if(m)return Yc(Ic(m,uc));const _=dl(o,p),f=cl(_),h=gl(_),g={},y=[];for(const t of[...$o,...Eo]){const n=e[t];"string"==typeof n&&""!==n&&(y.push(t),h.includes(t)&&(g[t]=Jc(n)))}const w=y.filter(e=>!h.includes(e));if(w.length>0)return Yc(Ic(jl(_,w)));let v=[];if("hara"===o){const t=await async function(e,t,n,r){const a=r.functionIds.length>0,i=[];for(const e of r.assets){const t=(e??"").trim();t&&!i.some(e=>j_(e)===j_(t))&&i.push(t)}if("security_tir57"===n)return a?{ok:!1,error:F_("A security risk analysis names assets, never Functions: pass its asset names in source_assets and omit source_function_ids. Nothing was written.",["Pass source_assets with the asset names, one row each"])}:{ok:!0,seeds:i.map(e=>({text:e,functionId:null}))};if(!N_(n))return a||i.length>0?{ok:!1,error:F_(`source_function_ids and source_assets apply to a HARA, a risk analysis or a security risk analysis only; a ${n} analysis is seeded with source_req_ids. Nothing was written.`)}:{ok:!0,seeds:[]};if(i.length>0)return{ok:!1,error:F_(`source_assets applies to a security risk analysis only; a ${n} analysis is seeded with source_function_ids, the ids of Function items. Nothing was written.`,["Find the project's Functions with atoms_list_items type 'function'",`Or create one with ${p_}`])};if(!a)return{ok:!0,seeds:[]};const s=await R_(e,t,r.functionIds);return s.ok?{ok:!0,seeds:s.functions.map(e=>({text:e.title,functionId:e.id}))}:s}(r,e.project_id,_,{functionIds:d,assets:c});if(!t.ok)return Yc(t.error);v=t.seeds}const b="hara"===o?v:l.map(e=>({text:e,functionId:null})),k=$f({...void 0!==e.hazard_id?{hazard_id:e.hazard_id}:{},...void 0!==e.goal_id?{goal_id:e.goal_id}:{}});if(k.error)return Yc(Ic(k.error));let j=!1;if("hara_iso26262"===_&&("ops"===s||xf(k.picks))){const t=await jf(r,e.project_id);if(null===t)return Yc(Sf(null));if(j=function(e,t){return"hara_iso26262"===e&&null!==t&&null===xi(t)}(_,t),!j&&xf(k.picks))return Yc(Sf(t))}const S=await zf(r,e.project_id,"atoms_create_analysis",_,j,k.picks,null,t=>Dg(r,e.project_id,t));if(S)return JS(S);if("ops"===s)return await async function(e){const{client:t,projectId:n,subtype:r,schemeId:a,seeds:i}=e,s=Mo[r],o=To[a],l=$l(a,e.stamp?"hazard_goal":"legacy"),d={analysis:{subtype:r,scheme:a,revision:e.revision,...e.schemeStandard?{standard:e.schemeStandard}:{}},analysis_props:{variant:e.variant,...e.scopeInput,...e.stamp?{event_model:"hazard_goal"}:{}}},c=e=>"hara"===r?D_(e):{source_req:e.text},u=Mf(null,e.picks),p=[$a({type:"analysis",title:e.title,fields:{...d,...u}}),...i.map(e=>$a({type:"requirement",title:"",req_type:s,fields:{...c(e),...u}}))],m=await Iw({projectId:n,tool:"atoms_create_analysis",key:e.key,contents:p}),_=await Ba(t,n,[...m.createRefs,...m.link.slice(1)]),f={};_.has(m.create[0])||(f[o]=1);const h=m.create.slice(1).filter(e=>!_.has(e)).length;h>0&&(f[l]=(f[l]??0)+h);const g=Object.keys(f).length>0?gw(await yw(t,n,f)):null,y=_.get(m.create[0])?.item_id??g(o),w=m.create.slice(1).map(e=>_.get(e)?.item_id??g(l)),v=[{op_id:m.create[0],kind:"create_item",item_id:y,path:[],value:{type:"analysis",title:e.title,data:{body:"",...d}}}];i.forEach((e,t)=>{v.push({op_id:m.create[t+1],kind:"create_item",item_id:w[t],path:[],value:{type:"requirement",title:"",data:{body:"",req_type:s,analysis_props:"hara"===r?{source_req:null,...D_(e),approved:!1,approved_at:null,field_source:{}}:{source_req:e.text,approved:!1,approved_at:null,field_source:{}}}}})}),w.forEach((e,t)=>{v.push({op_id:m.link[t+1],kind:"add",item_id:y,path:["relationships","children"],value:e})});for(const t of w)v.push(...GS(t,null,e.picks));const b=await kw({client:t,projectId:n,ops:qw(v,m),preFound:_,labels:tA(a)}),k=m.create.map(e=>b.answers.find(t=>t.op_id===e)),{tokens:j,unread:S}=await Ow(t,n,k.filter(e=>!!e)),A=k[0]?.item_id??y,$=i.map((t,n)=>{const a=k[n+1]?.item_id??w[n];return{..."hara"===r?H_(a,t):{id:a,source_req:t.text},...xf(e.picks)?Mf(null,e.picks):{},...j.get(a)?{base_token:j.get(a)}:{}}});return jw(b.outcome,{id:A,subtype:r,title:e.title,revision:e.revision,scheme:a,variant:e.variant,labels:Cf(a,e.stamp?"hazard_goal":"legacy"),...e.stamp?{event_model:"hazard_goal"}:{},...e.schemeStandard?{standard:e.schemeStandard}:{},...j.get(A)?{base_token:j.get(A)}:{},rows:$,...b.outcome.replayed?{message:yr}:{},...S?{warning:Kn}:{}},b)}({client:r,projectId:e.project_id,userId:i,subtype:o,schemeId:_,variant:p,schemeStandard:f,scopeInput:g,seeds:b,title:e.title??`New ${Gl(_).parent}`,revision:e.revision??"1.0",key:e.idempotency_key,stamp:j,picks:k.picks});const A=async()=>{const t=To[_],n=$l(_,"legacy"),a={[t]:1};a[n]=(a[n]??0)+b.length;const s=gw(await yw(r,e.project_id,a)),l=s(t),d=`New ${Gl(_).parent}`,c=e.title??d,u=e.revision??"1.0",m=Mo[o],h=(new Date).toISOString(),y={id:l,type:"analysis",title:c,body:"",tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis:{subtype:o,scheme:_,revision:u,...f?{standard:f}:{}},analysis_props:{variant:p,...g},metadata:{created_at:h,created_by:i,updated_at:h,updated_by:i}},{error:w}=await r.rpc("save_item_with_revision",{p_item_id:l,p_project_id:e.project_id,p_type:"analysis",p_title:c,p_data:y,p_user_id:i,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null});if(w)throw new Error(w.message);const v=(e,t)=>"hara"===o?H_(e,t):{id:e,source_req:t.text},k=[],j=[];for(const t of b){const a=s(n),d={id:a,type:"requirement",title:"",body:"",req_type:m,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[l],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:"hara"===o?{source_req:null,...D_(t),approved:!1,approved_at:null,field_source:{}}:{source_req:t.text,approved:!1,approved_at:null,field_source:{}},metadata:{created_at:h,created_by:i,updated_at:h,updated_by:i}},{error:c}=await r.rpc("save_item_with_revision",{p_item_id:a,p_project_id:e.project_id,p_type:"requirement",p_title:"",p_data:d,p_user_id:i,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null});if(c)throw new Error(c.message);const{error:u}=await r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:a,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 ${a}: ${u.message}\n`),j.push({row_id:a,..."hara"===o?{source_function:t.text}:{source_req:t.text},message:u.message})),await r.from("change_history").insert({item_id:a,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:d,actor:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),k.push(v(a,t))}return await r.from("change_history").insert({item_id:l,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:y,actor:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Kc(bc({id:l,subtype:o,title:c,revision:u,scheme:_,variant:p,labels:Gl(_),...f?{standard:f}:{},rows:k,...j.length>0?{link_warnings:j,warning:`${j.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 A()}catch(r){const a=Sw(n,t,r);return a?XS(e,a):Yc(Uc(r))}var a}function eA(e){for(const t of Object.keys(e)){const n=e[t];"string"==typeof n&&(e[t]=Jc(n))}}function tA(e){const t=new Map(Il(e).map(e=>[e.key,e.label]));return{analysisLabel:e=>t.get(e)??null}}function nA(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 rA(e,t,n){const r=n.data,a=new Map;for(const n of FS(r)){const r=await Dg(e,t,n);r&&a.set(n,r)}const i=await jm(e,t,{id:n.id,type:n.type,data:r},[...a.values()]),s=[];for(const r of i){const a=await Dg(e,t,r);a?.data?.asil_source===n.id&&s.push(r)}return s}async function aA(e,t){let n;try{const s=await _u(),o=yu();try{await ju(s,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const l=t??await vw(s,e.project_id);if("unreadable"===l)return bw();n=l;const d=await Dg(s,e.project_id,e.row_id);if(!d)return Yc(Sc("Analysis row",e.row_id));const c=d.data;if("goal"===d.type){const t=Rf(Object.keys(e.fields??{}));if(t.length>0)return Yc(Ic(Tf(d.id,t),uc))}if("analysis"===d.type)return async function(e,t,n,r,a,i,s){const{schemeId:o}=await KS(e,n,function(e){return"dfmea"===e?.analysis?.subtype?"dfmea":"hara"}(a),a),l=function(e,t){const n=gl(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,Ks.includes(t)||Ys.includes(t);var t});if(a.length>0)return{ok:!1,message:eo(a)};const i=r.filter(e=>!n.includes(e));if(i.length>0)return{ok:!1,message:jl(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=yl(e);if("overall_residual_risk"===n&&""!==r&&!a.includes(r))return{ok:!1,message:Sl(n,r,a)};if("software_safety_class"===n&&""!==r&&!Oo.includes(r))return{ok:!1,message:Sl(n,r,Oo)};s[n]=r}return{ok:!0,writes:s}}(o,i);if(!l.ok)return Yc(Ic(l.message));const d=l.writes;if(eA(d),s){const{ops:t,refusals:i}=await xw({client:e,projectId:n,itemId:r.id,tokens:s.tokens,cells:Object.entries(d).map(([e,t])=>({path:["analysis_props",e],value:t}))}),l=await kw({client:e,projectId:n,ops:t,refusals:i,labels:tA(o)}),c={...a.analysis_props??{},...d};return jw(l.outcome,{analysis_id:r.id,scheme:o,written_fields:Object.keys(d),scope:vl(c),overall:bl(c,yl(o))},l)}return await(async()=>{const i=LS(a);i.analysis_props&&"object"==typeof i.analysis_props||(i.analysis_props={});const s=i.analysis_props;for(const[e,t]of Object.entries(d))s[e]=t;const l=(new Date).toISOString();i.metadata={...i.metadata??{},updated_at:l,updated_by:t};const{data:c,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:WA()??null,p_diff_summary:null,p_expected_updated_at:r.updated_at});if(u)throw new Error(u.message);return c?(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:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Kc(bc({analysis_id:r.id,scheme:o,written_fields:Object.keys(d),scope:vl(s),overall:bl(s,yl(o))}))):Yc(jc(`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"]))})()}(s,o,e.project_id,d,c,e.fields??{},"ops"===l?{tokens:Aw(e.base_token)}:void 0);const u=PS(c?.req_type);if(!u)return Yc(Ic(Uf(e.row_id,d.type,"atoms_fill_row"),uc));const{schemeId:p}=await YS(s,e.project_id,u,c),m=await P_(p,Object.keys(e.fields??{}),()=>l_(s,e.project_id));if(m)return Yc(Ic(m,uc));const{[__]:_,...f}=e.fields??{},h=$f(f);if(h.error)return Yc(Ic(h.error));const g=h.rest,y=void 0!==_,w=xf(h.picks),v=(y||w)&&0===Object.keys(g).length?{ok:!0,writes:{}}:ZS(p,u,g,{extraKeys:"hara"===u?["effect","title"]:["effect"]});if(!v.ok)return Yc(Ic(v.message));const b=v.writes;eA(b);const k=Of(d.id,c?.relationships,Object.keys(b),h.picks);if(k)return Yc(Ic(k,uc));if(w){const t=await zf(s,e.project_id,d.id,p,await QS(s,e.project_id,p,c),h.picks,c?.relationships,t=>Dg(s,e.project_id,t));if(t)return JS(t)}let j={};if(y){const t=await WS(s,e.project_id,p,{[__]:_});if(!t.ok)return t.result;Object.assign(b,t.writes),j=t.answer}const S=c?.analysis_props??null;if("ops"===l){const{ops:t,refusals:n}=await xw({client:s,projectId:e.project_id,itemId:d.id,tokens:Aw(e.base_token),cells:nA(u,b)}),o=GS(d.id,c?.relationships,h.picks),l=await kw({client:s,projectId:e.project_id,ops:[...t,...o],refusals:n,labels:tA(p)}),m={...S??{}};for(const[e,t]of Object.entries(b))"effect"!==e&&"title"!==e&&(m[e]=t);const _=Object.keys(b).length>0&&ad({...m})||(r=S,a=c?.relationships,i=h.picks,!0===r?.approved&&Ef(a,i).length>0),f=Ul(p,m),g=G_(c?.relationships,"event_goal").length>0||void 0!==h.picks.event_goal,y=0===l.outcome.not_applied.length&&"hara_iso26262"===p?[...new Set([...await rA(s,e.project_id,d),...g?await Bf(s,e.project_id,(await Dg(s,e.project_id,d.id))?.data?.relationships,t=>Dg(s,e.project_id,t)):[]])].sort():[];return jw(l.outcome,{row_id:d.id,subtype:u,written_fields:Object.keys(b),written_columns:ql(p,Object.keys(b)),computed_level:f,..."hara_iso26262"===p?{asil_propagated_to:y}:{},..._?{approval_cleared:!0}:{},acceptance_revoked:$w(l.answers),...j,...w?Mf(c?.relationships,h.picks):{}},l)}const A=async()=>{const t=function(e,t){const n={};for(const r of["event_hazard","event_goal"])void 0!==t[r]&&Ef(e,{[r]:t[r]}).length>0&&(n[r]=t[r]);return n}(c?.relationships,h.picks);if(0===Object.keys(b).length&&0===Object.keys(t).length)return Kc(bc({row_id:d.id,subtype:u,written_fields:[],written_columns:[],computed_level:Ul(p,S),..."hara_iso26262"===p?{asil_propagated_to:[]}:{},acceptance_revoked:!1,...j,...w?Mf(c?.relationships,h.picks):{}}));const n=LS(c);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.field_source&&"object"==typeof r.field_source||(r.field_source={});let a=d.title;for(const[e,t]of Object.entries(b))"effect"===e?n.body=t:"title"===e?(n.title=t,a=t):(r[e]=t,"failure_mode"===e&&"dfmea"===u&&(n.title=t,a=t)),r.field_source[e]="mcp";if(w){n.relationships={...n.relationships??{}};for(const[e,r]of Object.entries(t))n.relationships[e]=r?[r]:[]}const i=ad(r),l=(new Date).toISOString();n.metadata={...n.metadata??{},updated_at:l,updated_by:o};const m=Ul(p,r),_=Ul(p,S),f=[];if("hara_iso26262"===p&&function(e,t,n){return t!==_o&&(t!==n||e.some(e=>um.includes(e)))}(Object.keys(b),m,_)){const t=new Map;for(const r of FS(n)){const n=await Dg(s,e.project_id,r);n&&t.set(r,n)}const r=await jm(s,e.project_id,{id:d.id,type:d.type,data:n},[...t.values()]);for(const n of r){const r=t.get(n)??await Dg(s,e.project_id,n);r&&Sm(r.data,d.id,m,m!==_)&&f.push(r)}}const{data:g,error:y}=await s.rpc("save_item_with_revision",{p_item_id:d.id,p_project_id:e.project_id,p_type:d.type,p_title:a,p_data:n,p_user_id:o,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null,p_expected_updated_at:d.updated_at});if(y)throw new Error(y.message);if(!g)return Yc(jc(`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 s.from("change_history").insert({item_id:d.id,project_id:e.project_id,changed_by:o,event_type:"updated",old_data:c,new_data:n,actor:VA(),session_id:WA(),...i?{reason:`${Object.keys(b).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 v=BS(c),k=v?await io(v,"The row was",{readParent:()=>Dg(s,e.project_id,v),saveParent:(t,n)=>Jd(()=>s.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:o,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at}),{scope:e.project_id,afterWrite:!0}),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},A=k.revoked,$=[],x=[];for(const t of f){const n=t.data,r=n?.asil??null,a=n?.asil_source??null,i=LS(n);i.asil=m,i.asil_source=d.id,i.metadata={...i.metadata??{},updated_at:l,updated_by:o};let c=null;try{const{error:n}=await s.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:i,p_user_id:o,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});n&&(c=n.message??"unknown error")}catch(e){c=e instanceof Error?e.message:String(e)}null===c?(await s.from("change_history").insert({item_id:t.id,project_id:e.project_id,changed_by:o,event_type:"updated",old_data:{asil:r,asil_source:a},new_data:{asil:m,asil_source:d.id},actor:VA(),session_id:WA(),reason:`ASIL propagated from ${d.id} (rating change via atoms_fill_row)`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),$.push(t.id)):(process.stderr.write(`[atoms-mcp] Warning: ASIL push from ${d.id} to ${t.id} failed: ${c}\n`),x.push(t.id))}const I=[k.warning,x.length>0?(q=d.id,O=x,`${q} was saved, but its ASIL did not reach ${O.join(", ")} (asil_propagation_failed). Repeat the same atoms_fill_row call to push it again; the row's rating is already stored.`):null].filter(e=>"string"==typeof e&&e.length>0);var q,O;return Kc(bc({row_id:d.id,subtype:u,written_fields:Object.keys(b),written_columns:ql(p,Object.keys(b)),computed_level:m,...$.length>0?{asil_propagated_to:$}:{},...x.length>0?{asil_propagation_failed:x}:{},...i?{approval_cleared:!0}:{},acceptance_revoked:A,...I.length>0?{warning:I.join(" ")}:{},...j,...w?Mf(c?.relationships,h.picks):{}}))};return await A()}catch(r){const a=Sw(n,t,r);return a?aA(e,a):Yc(Uc(r))}var r,a,i}function iA(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 sA(e,t,n,r=!1){const a=await Dg(e,t,n);if(!a)return{ok:!1,result:Yc(Sc("Analysis",n))};if("analysis"!==a.type)return{ok:!1,result:Yc(Ic(`Item ${n} is not an analysis (type='${a.type}')`))};const i=a.data,s=PS("hara"===i?.analysis?.subtype?"safety-goal":"dfmea"===i?.analysis?.subtype?"failure-mode":null);if(!s)return{ok:!1,result:Yc(Ic(`Analysis ${n} is missing a valid analysis.subtype`))};const o=Mo[s],{variant:l,schemeId:d}=await KS(e,t,s,i),c=Df(d,i),u=Array.isArray(i?.relationships?.children)?i.relationships.children.filter(e=>"string"==typeof e):[],p=r?await Qr(e,t,[a.id,...u]):new Map;let m=[];if(u.length>0){const n=await En([...new Set(u)],n=>e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",n)),r=new Set(u),a=new Map(n.filter(e=>!e.deleted_at&&r.has(e.id)&&e.data?.req_type===o).map(e=>[e.id,e]));m=u.map(e=>a.get(e)).filter(e=>Boolean(e))}const _=new Set;for(const e of m){const t=e.data?.analysis_props??{};"string"==typeof t.source_req&&t.source_req&&_.add(t.source_req);for(const t of FS(e.data))_.add(t);for(const t of US(e.data))_.add(t);for(const t of Q_(e.data?.relationships))_.add(t)}const f=new Map,h=new Map;let g=[];if(_.size>0){g=await En([..._],n=>e.from("items").select(sm).eq("project_id",t).is("deleted_at",null).in("id",n))??[];for(const e of g)f.set(e.id,e.updated_at),h.set(e.id,e.content_changed_at??e.updated_at)}const y=m.length>0?km(m,[...g,...await bm(e,t)]):new Map,w=await C_(e,t,function(e){return E_(e.map(e=>S_(e).source_function_id))}(m.map(e=>({analysis_props:e.data?.analysis_props??null})))),v=c?await Vf(e,t):null,b=v?Wf(v):null,k="security_tir57"===d?await async function(e,t,n){const r=e=>Am(e.data?.relationships?.affects),a=[...new Set(n.flatMap(r))];if(0===a.length)return new Set;const i=await En(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 new Set(n.filter(e=>r(e).some(e=>s.has(e))).map(e=>e.id))}(e,t,m):new Set,j=new Map,S=m.map(e=>{const t=e.data?.analysis_props??{},n=y.get(e.id)??[],r=FS(e.data).filter(e=>f.has(e)),a=US(e.data).filter(e=>f.has(e)),i=n.length>0,s=Ul(d,t),o=Q_(e.data?.relationships),l=new Set(o),c=b?function(e,t){const n=e.goalOf(t);return n&&e.goalIds.includes(n)?{cited:!0,satisfied:e.satisfiers(n).length>0,id:n}:{cited:!1,satisfied:!1,id:null}}(b,e.id):void 0,u=function(e,t,n,r){if(n)return null;if("hara_iso26262"===e&&r?.cited&&r.satisfied)return null;if("hara_iso26262"===e){const e=Tl(t);return"QM"===e||e===_o?null:r?.cited?`asil ${e} unmitigated: no safety requirement is linked to the row or satisfies its goal${r.id?` ${r.id}`:""}`:`asil ${e} unmitigated`}if("hazard_iso14971"===e){const e=Hl(t);return"Low"!==e&&e!==_o?`${e.toLowerCase()} risk uncontrolled`:null}if("security_tir57"===e){const e=Pl(t);return Qs(e)?`${e.toLowerCase()} security risk uncontrolled`:null}const a=parseInt(Ul(e,t),10),i=parseInt(t?.severity||"",10);return!Number.isNaN(a)&&a>=100?"rpn >= 100":!Number.isNaN(i)&&i>=9?"severity >= 9":null}(d,t,i,c);j.set(e.id,{props:t,affectsLinked:k.has(e.id)});const p={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:zl(d,s),is_gap:null!==u,gap_rule:u,is_critical:Ll(d,t,i,c),is_stale:Wl(t,r,e=>(l.has(e)?h.get(e):f.get(e))??null,x_({analysis_props:t},d,w),o),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"===d?Nl(t):"security_tir57"===d?Fl(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 So[d])p[e]=t[e]??null;return Object.assign(p,function(e,t){const n=A_(S_(e).source_function_id).trim();if(!n)return{};const r=$_(e,t.schemeId,t.itemsById,t.tagMap);return{source_function_id:n,source_function_title:"live"===r.state?r.title:null}}({analysis_props:t},{schemeId:d,itemsById:w})),b&&Object.assign(p,function(e,t){const n=e.goalOf(t);return{...Nf(t),hazard_id:e.hazardOf(t),goal_id:n,goal_asil:n&&e.isLiveId(n)?e.goalAsil(n):null,goal_display:n?(r=n,`Goal ${r}`):null};var r}(b,e.id)),p});return{ok:!0,analysis:{id:a.id,title:"string"==typeof a.title?a.title:"",subtype:s,scheme:d,revision:"string"==typeof i?.analysis?.revision?i.analysis.revision:"1.0",standard:"string"==typeof i?.analysis?.standard?i.analysis.standard:cl(d)??null,variant:l,labels:Cf(d,c?"hazard_goal":"legacy"),...c?{event_model:"hazard_goal"}:{},acceptability:El(d),definitions:Ol(d),control_types:Kl(d),field_labels:Il(d),scope:gl(d).length>0?vl(i?.analysis_props):null,overall:gl(d).length>0?bl(i?.analysis_props,yl(d)):null,threat_model:"security_tir57"===d?iA(i?.analysis_props):null,acceptance:no(i?.analysis_props)},schemeId:d,parentProps:i?.analysis_props??null,revisions:p,rows:S,gapFacts:j,stamped:b&&v?{index:b,items:v,rows:m.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data}))}:null,counts:{rows:S.length,gaps:S.filter(e=>e.is_gap).length,critical:S.filter(e=>e.is_critical).length,stale:S.filter(e=>e.is_stale).length,approved:S.filter(e=>e.approved).length,linked:S.filter(e=>e.mitigated_by.length>0).length}}}async function oA(e){try{return await async function(e,t=yd){let n;const r=new Promise((e,r)=>{n=setTimeout(()=>r(new bd(t)),t)});try{return await Promise.race([e(),r])}finally{clearTimeout(n)}}(()=>async function(e){const t=await _u(),n=!0===await Ra(t,e.project_id),r=await sA(t,e.project_id,e.analysis_id,n);if(!r.ok)return r.result;const a=qd(r.rows,e.offset,e.limit),i={paging:{list:"rows"}};if(!n)return Kc(bc({analysis:r.analysis,rows:a.rows,counts:r.counts},a.meta),i);const s=async e=>{const t=r.revisions.get(e);return t?Wr(t,"analysis"):void 0},o=new Map(Il(r.schemeId).map(e=>[e.key,e.label])),l=await Zr(t,e.project_id,[r.analysis.id,...a.rows.map(e=>e.id)],{analysisLabel:e=>o.get(e)??null}),d=await s(r.analysis.id),c=await Promise.all(a.rows.map(async e=>{const t=await s(e.id);return{...e,...t?{base_token:t}:{},editing_now:l.get(e.id)??[]}}));return Kc(bc({analysis:{...r.analysis,...d?{base_token:d}:{},editing_now:l.get(r.analysis.id)??[]},rows:c,counts:r.counts},a.meta),i)}(e))}catch(e){return Yc(Uc(e,{read:!0}))}}async function lA(e,t,n,r){const a=BS(n);if(!a)return;const i=await Dg(e,t,a);if(!i)return;const{revoked:s,parentProps:o}=ao(i.data);if(!s)return;const l={...i.data,analysis_props:o},{error:d}=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:WA()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});d&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${i.id}': ${d.message}\n`)}async function dA(e,t,n,r){return!0===r?.analysis_props?.approved&&xb(r,await Dg(e,t,n))}async function cA(e,t){let n;try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();if(n=i,e.row_id===e.req_id)return Yc(Ic("row_id and req_id must be different items"));const s=await Dg(r,e.project_id,e.row_id);if(!s)return Yc(Sc("Analysis row",e.row_id));const o=s.data;if("goal"===s.type)return await uA(r,e,s,i,null);const l=PS(o?.req_type);if(!l)return Yc(Ic(Uf(e.row_id,s.type,"atoms_link_mitigation"),uc));if("remove"!==e.action&&G_(o?.relationships,"event_goal").length>0){const{schemeId:t}=await YS(r,e.project_id,l,o),n=await QS(r,e.project_id,t,o),a=n?await Dg(r,e.project_id,G_(o?.relationships,"event_goal")[0]):null,d=function(e,t,n){if(!e)return null;const r=G_(t,"event_goal")[0];return r&&n&&n.id===r&&"goal"===n.type&&(null===n.deleted_at||void 0===n.deleted_at)?r:null}(n,o?.relationships,a?{id:a.id,type:a.type,deleted_at:a.deleted_at??null}:null);if(d&&a)return await uA(r,e,a,i,s.id)}const d=await Dg(r,e.project_id,e.req_id);if(!d)return Yc(Sc("Requirement",e.req_id));const c=d.data;if("remove"===e.action){if(void 0!==e.role||void 0!==e.control_type||void 0!==e.override)return Yc(Ic(pm));if(!$m(e.row_id,o,e.req_id,c))return Yc(Ic(xm(e.row_id,e.req_id),uc));const{schemeId:t}=await YS(r,e.project_id,l,o);if("ops"===i){const n={op_id:ya(),kind:"remove",item_id:e.row_id,path:["relationships","mitigated_by"],value:e.req_id},a=await kw({client:r,projectId:e.project_id,ops:[n],labels:tA(t)});return jw(a.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,...await dA(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},acceptance_revoked:$w(a.answers)},a)}const n=async()=>{const{error:n}=await r.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:a,p_event_source:"mcp",p_expected_from_updated_at:s.updated_at,p_expected_to_updated_at:d.updated_at,p_role:null});if(n)throw new Error(n.message);await r.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"remove",type:"mitigated_by",from:e.row_id,to:e.req_id}},actor:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await lA(r,e.project_id,o,a);const i=await Dg(r,e.project_id,e.row_id),l=i?.data,c=l?.analysis_props?.mitigation_types;if(i&&l&&c&&"object"==typeof c&&Object.prototype.hasOwnProperty.call(c,e.req_id)){const t=LS(l);delete t.analysis_props.mitigation_types[e.req_id],t.metadata={...t.metadata??{},updated_at:(new Date).toISOString(),updated_by:a};const{error:n}=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:t,p_user_id:a,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});if(n)throw new Error(n.message)}return Kc(bc({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,...await dA(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{}}))};return await n()}if("requirement"!==d.type||DS.has(c?.req_type))return Yc(Ic(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));const{schemeId:u}=await YS(r,e.project_id,l,o);if(Yl(u)&&c?.req_type!==co)return Yc(Ic(Zl(e.req_id,u)));const p=Ql(u);if(0===p.length&&void 0!==e.control_type)return Yc(Ic(Xl(u)));if(p.length>0&&!e.control_type)return Yc(Ic(ed(u)));if(!(void 0===e.control_type||ul(e.control_type)&&function(e,t){return Ql(e).some(e=>e.id===t)}(u,e.control_type)))return Yc(Ic(ed(u)));if("dfmea"===l&&!e.role)return Yc(Ic(`role is required for dfmea mitigation links. Choose one of: ${fo.join(", ")}`));if("hara"===l&&e.role)return Yc(Ic("role is not applicable to hara mitigation links; omit it (roles are a dfmea concept)"));if("ops"===i){const t="dfmea"===l?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,a={op_id:ya(),kind:"add",item_id:e.row_id,path:["relationships","mitigated_by"],value:n},i=await kw({client:r,projectId:e.project_id,ops:[a],labels:tA(u)});return jw(i.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:t,scheme:u,...e.control_type?{control_type:e.control_type}:{},...await dA(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},acceptance_revoked:$w(i.answers)},i)}const m=async()=>{let t=_o;if("hara_iso26262"===u){t=Ul(u,o?.analysis_props);const r=c?.asil;if(t!==_o&&"string"==typeof r&&r.length>0&&r!==t&&!0!==e.override)return Yc((i=t,{...jc(`ASIL conflict: the target requirement already carries asil '${n=r}' but ${p=s.id} computes '${i}'.`,["Pass override=true to apply the HARA value; the override is history-logged like a dialog accept","Or align the row's S/E/C ratings with the existing ASIL before linking"]),details:{code:"asil_conflict",current_value:n,incoming_value:i,source_row:p,hint:"pass override=true to apply the HARA value; the override is history-logged like a dialog accept"}}))}var n,i,p;const m="dfmea"===l?e.role:null,{error:_}=await r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:e.row_id,p_to_id:e.req_id,p_type:"mitigated_by",p_action:"add",p_user_id:a,p_event_source:"mcp",p_expected_from_updated_at:s.updated_at,p_expected_to_updated_at:d.updated_at,p_role:m});if(_)throw new Error(_.message);let f;await r.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"add",type:"mitigated_by",from:e.row_id,to:e.req_id,...m?{role:m}:{}}},actor:VA(),session_id:WA()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await lA(r,e.project_id,o,a);let h,g=null;if(e.control_type&&ul(e.control_type)){const t=e.control_type,n=await xS(async()=>{const t=await Dg(r,e.project_id,e.row_id)??s,n=LS(t.data);n.analysis_props&&"object"==typeof n.analysis_props||(n.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const i=n.analysis_props;i.mitigation_types&&"object"==typeof i.mitigation_types||(i.mitigation_types={}),i.mitigation_types[e.req_id]=e.control_type;const o=(new Date).toISOString();n.metadata={...n.metadata??{},updated_at:o,updated_by:a};const{error:l}=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:WA()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});return l??null});n?(process.stderr.write(`[atoms-mcp] Warning: control type write after the link failed for '${e.row_id}': ${n.message}\n`),g={value:t,message:String(n.message??"unknown error")}):f=t}let y=null;if("hara_iso26262"===u&&t!==_o){let n=null,i=null,o=null;const l=await xS(async()=>{const l=await Dg(r,e.project_id,e.req_id);if(o=l?.id??null,!l)return null;const d=l.data;n=d?.asil??null,i=d?.asil_source??null;const c=LS(d);c.asil=t,c.asil_source=s.id;const u=(new Date).toISOString();c.metadata={...c.metadata??{},updated_at:u,updated_by:a};const{error:p}=await r.rpc("save_item_with_revision",{p_item_id:l.id,p_project_id:e.project_id,p_type:l.type,p_title:l.title,p_data:c,p_user_id:a,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null,p_expected_updated_at:l.updated_at});return p??null});l?(process.stderr.write(`[atoms-mcp] Warning: ASIL write after the link failed for '${e.req_id}': ${l.message}\n`),y={level:t,message:String(l.message??"unknown error")}):o&&(await r.from("change_history").insert({item_id:o,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{asil:n,asil_source:i},new_data:{asil:t,asil_source:s.id},actor:VA(),session_id:WA(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${n??"unset"}', now '${t}' 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`)}),h=t)}return Kc(bc({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:m,scheme:u,...f?{control_type:f}:{},...h?{asil_written:h}:{},...await dA(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},...IS({rowId:e.row_id,reqId:e.req_id,asil:y,controlType:g})}))};return await m()}catch(r){const a=Sw(n,t,r);return a?cA(e,a):Yc(Uc(r))}}async function uA(e,t,n,r,a){const i="hara_iso26262";if(void 0!==t.role)return Yc(Ic("role is not applicable to a Safety goal's mitigation links; omit it (roles are a dfmea concept)"));if(void 0!==t.control_type)return Yc(Ic(Xl(i)));if(t.req_id===n.id)return Yc(Ic("row_id and req_id must be different items"));const s=await Dg(e,t.project_id,t.req_id);if(!s)return Yc(Sc("Requirement",t.req_id));const o=s.data,l="remove"===t.action?"remove":"add";if("remove"===l){if(void 0!==t.override)return Yc(Ic(pm));if(!$m(n.id,n.data,t.req_id,o))return Yc(Ic(xm(n.id,t.req_id),uc))}else{if("requirement"!==s.type||DS.has(o?.req_type))return Yc(Ic(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${t.req_id}`));if(Yl(i)&&o?.req_type!==co)return Yc(Ic(Zl(t.req_id,i)))}if("ops"!==r)return Yc(Cs());const d={op_id:ya(),kind:l,item_id:n.id,path:["relationships","mitigated_by"],value:t.req_id},c=await kw({client:e,projectId:t.project_id,ops:[d],labels:tA(i)}),u=await Dg(e,t.project_id,t.req_id),p=u?.data??{};return jw(c.outcome,{row_id:n.id,req_id:t.req_id,type:"mitigated_by",..."remove"===l?{action:"remove"}:{role:null},scheme:i,...a?{redirected_from:a}:{},asil:"string"==typeof p.asil?p.asil:null,asil_source:"string"==typeof p.asil_source?p.asil_source:null,acceptance_revoked:$w(c.answers)},c)}async function pA(e){try{const n=await _u(),r=await sA(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=pl(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=rd(r.schemeId).some(e=>"requirement"===e.scope)?await async function(e,t,n){const r=(await An(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null).eq("type","requirement"),pn)).filter(e=>e.data?.req_type===co&&function(e,t){const n=ml(e);return n.length>0&&n===ml(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 En([...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??_o,severity:td(e.severity),props:r.gapFacts.get(e.id)?.props??null,affectsLinked:r.gapFacts.get(e.id)?.affectsLinked??!1})),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=CS(n?.scenario_catalogs??[]);return a.ok?a.value:[]}(n,e.project_id)),d=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:kl(e),overallJudged:""!==bl(e,a?Fs:qo).residual_risk,everyRowSettled:t.every(e=>e.linked&&e.residualLevel!==_o),catalogsDraft:r,accepted:"accepted"===e?.acceptance_state}}(r.parentProps,o,r.schemeId,l),c=await async function(e,t,n,r){if(!N_(n))return[];if("items"!==await l_(e,t))return[];const a=await An(()=>e.from("items").select("id, type, title").eq("project_id",t).eq("type","function").is("deleted_at",null),pn),{data:i,error:s}=await e.from("function_tag_items").select("tag_key, item_id").eq("project_id",t).is("reverted_at",null).order("tag_key",{ascending:!0}).range(0,999);if(s)throw new Error(`Function tag map read failed: ${s.message??"unknown error"}`);const o=Array.isArray(i)?i:[];if(o.length>=1e3)throw new Error("Function tag map read failed: the moved functions could not be read in full.");return function(e,t,n,r){if(!N_(e))return[];const a=new Map(n.map(e=>[e.id,e])),i=new Set,s=[];for(const n of t){const t=$_(n,e,a,r);"live"===t.state&&t.id?i.add(t.id):"trashed"===t.state&&s.push(n.id)}const o=n.filter(e=>"function"===e.type&&!i.has(e.id)).map(e=>e.id),l=[];return o.length>0&&l.push({kind:"function_not_analysed",label:`${o.length} ${1===o.length?"function":"functions"} not analysed`,rowIds:[],reqIds:[],functionIds:o,count:o.length,fix:"open_item",fixLabel:"Open function"}),s.length>0&&l.push({kind:"function_missing",label:`${s.length} ${1===s.length?"row names":"rows name"} a function that is not live`,rowIds:s,reqIds:[],count:s.length,fix:"open_row",fixLabel:"Open row"}),l}(n,r,a,o)}(n,e.project_id,r.schemeId,r.rows.map(e=>({id:e.id,analysis_props:r.gapFacts.get(e.id)?.props??null}))),u=[...id(r.schemeId,o,s,d),...c],p=r.stamped?function(e,t,n){const r=function(e){const t=e=>e.reduce((e,t)=>e.concat(t.rowIds),[]);return[{kind:"row_no_goal",count:e.rowNoGoal.length,rowIds:[...e.rowNoGoal],goalIds:[],hazardIds:[],criticalIds:[...e.rowNoGoalCritical]},{kind:"goal_no_safety_req",count:e.goalNoSafetyReq.length,rowIds:t(e.goalNoSafetyReq),goalIds:e.goalNoSafetyReq.map(e=>e.goalId),hazardIds:[],criticalIds:e.goalNoSafetyReq.filter(e=>e.critical).map(e=>e.goalId)},{kind:"goal_no_test",count:e.goalNoTest.goals.length+e.goalNoTest.rowIds.length,rowIds:[...e.goalNoTest.rowIds,...t(e.goalNoTest.goals)].sort(),goalIds:e.goalNoTest.goals.map(e=>e.goalId),hazardIds:[],criticalIds:[]},{kind:"hazard_uncited",count:e.hazardUncited.length,rowIds:[],goalIds:[],hazardIds:[...e.hazardUncited],criticalIds:[]},{kind:"goal_trashed",count:e.goalTrashed.rowIds.length,rowIds:[...e.goalTrashed.rowIds],goalIds:[...e.goalTrashed.goalIds],hazardIds:[],criticalIds:[]}].filter(e=>e.count>0)}(function(e,t){const n=e=>e!==_o&&"QM"!==e&&J_(e)>0,r=[],a=[],i=[],s=new Map,o=[],l=new Set;for(const d of t){const t=Tl(d.analysis_props),c=e.goalOf(d.id);if(c&&e.isLiveId(c)){let e=s.get(c);e||s.set(c,e=[]),e.push(d.id);continue}if(c&&(o.push(d.id),l.add(c)),!n(t))continue;const u=e.directMitigators(d.id).filter(t=>e.isLiveId(t));0===u.length?(r.push(d.id),"C"!==t&&"D"!==t||a.push(d.id)):u.some(t=>e.requirementVerified(t))||i.push(d.id)}const d=new Map(t.map(e=>[e.id,Tl(e.analysis_props)])),c=[],u=[];for(const t of[...s.keys()].sort()){const n=e.goalCoverage(t,s.get(t));if(n.uncoveredRows.length>0){const e=n.uncoveredRows.some(e=>"C"===d.get(e)||"D"===d.get(e));c.push({goalId:t,critical:e,rowIds:[...n.uncoveredRows]})}n.untestedRows.length>0&&u.push({goalId:t,critical:!1,rowIds:[...n.untestedRows]})}return{rowNoGoal:r,rowNoGoalCritical:a,goalNoSafetyReq:c,goalNoTest:{goals:u,rowIds:i},hazardUncited:e.hazardIds.filter(t=>0===e.rowsOfHazard(t).length),goalTrashed:{rowIds:o,goalIds:[...l].sort()}}}(t,Lf(n))).map(e=>{const t=sl.find(t=>t.kind===e.kind);return{kind:e.kind,label:t.label(e.count),rowIds:[...e.rowIds],reqIds:[],count:e.count,fix:t.fix,fixLabel:t.fixLabel,...e.goalIds.length>0?{goalIds:[...e.goalIds]}:{},...e.hazardIds.length>0?{hazardIds:[...e.hazardIds]}:{},...e.criticalIds.length>0?{criticalIds:[...e.criticalIds]}:{},...t.informational?{informational:!0}:{}}});return[...r.filter(e=>!e.informational),...e.filter(e=>"unmitigated"!==e.kind&&"no_test"!==e.kind),...r.filter(e=>e.informational)]}(u,r.stamped.index,r.stamped.rows):u,m=p.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,...e.goalIds?{goal_ids:e.goalIds}:{},...e.hazardIds?{hazard_ids:e.hazardIds}:{},...e.criticalIds?{critical_ids:e.criticalIds}:{},...e.informational?{informational:!0}:{},...e.functionIds?{function_ids:e.functionIds}:{}}));return Kc(bc({analysis_id:r.analysis.id,subtype:r.analysis.subtype,scheme:r.analysis.scheme,labels:r.analysis.labels,gaps:a,count:(t=p,t.reduce((e,t)=>e+(t.informational?0:t.count),0)),gap_kinds:m,system_level:i.level,system_level_source:i.source}))}catch(e){return Yc(Uc(e,{read:!0}))}var t}async function mA(e,t){let n;const r=q_("atoms_propose_rows",e);if(r)return Yc(r);try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();n=i;const s=await Dg(r,e.project_id,e.analysis_id);if(!s)return Yc(Sc("Analysis",e.analysis_id));if("analysis"!==s.type)return Yc(Ic(`Item ${e.analysis_id} is not an analysis (type='${s.type}')`));const o=s.data,l=o?.analysis?.subtype,d="hara"===l?"hara":"dfmea"===l?"dfmea":null;if(!d)return Yc(Ic(`Analysis ${e.analysis_id} is missing a valid analysis.subtype`));const{variant:c,schemeId:u}=await KS(r,e.project_id,d,o);if("hara"===d&&e.source_req)return Yc(Ic("A risk analysis row is seeded from a function, never a requirement: pass source_function_id"));if("dfmea"===d&&void 0!==e.source_function_id)return Yc(Ic("source_function_id applies to a HARA or a risk analysis only; seed an FMEA row with source_req"));const p=Array.isArray(e.rows)?e.rows:[];if(0===p.length)return Yc(Ic("rows must contain at least one drafted row"));if(p.length>po)return Yc(Ic(`Propose rows accepts at most ${po} rows per call; ${p.length} were sent. Split the proposal and call again.`));const m=[],_=[];for(let t=0;t<p.length;t++){const n=await P_(u,Object.keys(p[t]??{}),()=>l_(r,e.project_id));if(n)return Yc(Ic(`row ${t+1}: ${n}`,uc));const a=$f(p[t]??{});if(a.error)return Yc(Ic(`row ${t+1}: ${a.error}`));const i=ZS(u,d,a.rest,{extraKeys:"hara"===d?["effect","title"]:["effect"],where:`row ${t+1}`});if(!i.ok)return Yc(Ic(i.message));eA(i.writes);const s=Of(`row ${t+1}`,null,Object.keys(i.writes),a.picks);if(s)return Yc(Ic(s,uc));m.push(i.writes),_.push(a.picks)}const f=Al(o);for(let t=0;t<_.length;t++){const n=await zf(r,e.project_id,`row ${t+1}`,u,Df(u,o),_[t],null,t=>Dg(r,e.project_id,t));if(n)return JS(n)}const h=await async function(e,t,n,r){if(void 0===r)return{ok:!0,seed:null};const a=await P_(n,[__],()=>l_(e,t));if(a)return{ok:!1,error:F_(a)};if("string"!=typeof r)return{ok:!1,error:{status:"error",message:'Validation error: source_function_id must be a string, the id of a Function item ("" clears it on a project with Function items turned on). Nothing was written.',next_steps:["Find the project's Functions with atoms_list_items type 'function'"],code:"function_id_invalid",retryable:!1}};const i=await R_(e,t,r.trim()?[r]:[]);if(!i.ok)return i;const s=i.functions[0];return{ok:!0,seed:s?{text:s.title,functionId:s.id}:null}}(r,e.project_id,u,e.source_function_id);if(!h.ok)return Yc(h.error);const g=h.seed;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=Mo[r],l=$l(a,e.model),d=i.map((t,a)=>function(e,t,n,r,a){return function(e,t){return Tr({analysis_id:e,writes:Aa(t)})}(e,{...t,__seed:"hara"===n?r?r.functionId??r.text:"":a??null})}(n.analysis_id,{...t,...Mf(null,e.rowPicks[a]??{})},r,e.seed,n.source_req)),c=await Iw({projectId:s,tool:"atoms_propose_rows",key:n.idempotency_key,contents:d}),u=await Ba(t,s,[...c.createRefs,...c.link]),p=c.create.filter(e=>!u.has(e)).length,m=p>0?gw(await yw(t,s,{[l]:p})):null,_=c.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?U_(e.seed):{},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=hl(t)),h.push({writes:t,props:i}),f.push({op_id:c.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:c.link[t],kind:"add",item_id:n.analysis_id,path:["relationships","children"],value:e})}),_.forEach((t,n)=>f.push(...GS(t,null,e.rowPicks[n]??{})));const g=await kw({client:t,projectId:s,ops:qw(f,c),preFound:u,labels:tA(a)}),y=c.create.map(e=>g.answers.find(t=>t.op_id===e)),{tokens:w,unread:v}=await Ow(t,s,y.filter(e=>!!e)),b=h.map((t,n)=>{const r=y[n]?.item_id??_[n];return{id:r,written_fields:Object.keys(t.writes),written_columns:ql(a,Object.keys(t.writes)),computed_level:Ul(a,t.props),...xf(e.rowPicks[n]??{})?Mf(null,e.rowPicks[n]):{},...w.get(r)?{base_token:w.get(r)}:{}}});return jw(g.outcome,{analysis_id:n.analysis_id,subtype:r,scheme:a,...e.variant?{variant:e.variant}:{},labels:Cf(a,e.model),...L_(r,e.seed,n.source_req),rows:b,count:b.length,max_rows:po,approved:!1,acceptance_revoked:$w(g.answers),...g.outcome.replayed?{message:yr}:{},...v?{warning:Kn}:{}},g)}({client:r,params:e,parent:s,subtype:d,schemeId:u,variant:c,validatedRows:m,seed:g,model:f,rowPicks:_});const y=async()=>{const t=(new Date).toISOString(),n=Mo[d],i=[],s=[],o=$l(u,f),l=gw(await yw(r,e.project_id,{[o]:m.length}));for(const c of m){const p=l(o),m={source_req:"dfmea"===d?e.source_req??null:null,..."hara"===d?U_(g):{},approved:!1,approved_at:null,approved_by:null,field_source:{}};let _="",f="";for(const[e,t]of Object.entries(c))"effect"===e?_=t:"title"===e?f=t:(m[e]=t,"failure_mode"===e&&"dfmea"===d&&(f=t)),m.field_source[e]="mcp";f||(f=hl(c));const h={id:p,type:"requirement",title:f,body:_,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:y}=await Jd(()=>r.rpc("save_item_with_revision",{p_item_id:p,p_project_id:e.project_id,p_type:"requirement",p_title:f,p_data:h,p_user_id:a,p_event_source:"mcp",p_event_session_id:WA()??null,p_diff_summary:null}),{scope:e.project_id});if(y)throw new Error(y.message);const{error:w}=await Jd(()=>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"}),{scope:e.project_id,afterWrite:!0});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:h,actor:VA(),session_id:WA(),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(c),written_columns:ql(u,Object.keys(c)),computed_level:Ul(u,m)})}let p=!1,_=null;if(i.length>0)try{for(let t=0;t<3;t+=1){const n=await Dg(r,e.project_id,e.analysis_id);if(!n)break;const i=n.data,{revoked:s,parentProps:o}=ao(i);if(!s)break;const l={...i,analysis_props:o},{error:d}=await Jd(()=>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:WA()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at}),{scope:e.project_id,afterWrite:!0});if(!d){p=!0;break}if(!(t<2&&/stale_item_write/i.test(d.message??""))){process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${n.id}': ${d.message}\n`),_=`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`),_=`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 Kc(bc({analysis_id:e.analysis_id,subtype:d,scheme:u,...c?{variant:c}:{},labels:Cf(u,f),...L_(d,g,e.source_req),rows:i,count:i.length,max_rows:po,approved:!1,acceptance_revoked:p,...s.length>0||null!==_?{...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,_].filter(e=>null!==e).join(" ")}:{}}))};return await y()}catch(r){const a=Sw(n,t,r);return a?mA(e,a):Yc(Uc(r))}}async function _A(e,t){let n;try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();n=i;const s=await Dg(r,e.project_id,e.row_id);if(!s)return Yc(Sc("Analysis row",e.row_id));const o=s.data,l=PS(o?.req_type);if(!l)return Yc(Ic(Uf(e.row_id,s.type,"atoms_suggest_field"),uc));const{schemeId:d}=await YS(r,e.project_id,l,o),c=e.rationale?function(e,t){return jo[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}(d,e.field):null;if(e.rationale&&!c)return Yc(Ic(`rationale applies to a rating field only; ${e.field} is not a rating of ${d}`));const u={[e.field]:e.value};c&&e.rationale&&(u[c]=e.rationale);const p=await WS(r,e.project_id,d,u);if(!p.ok)return p.result;const m=0===Object.keys(p.rest).length?{ok:!0,writes:{}}:ZS(d,l,p.rest,{extraKeys:"hara"===l?["effect","title"]:["effect"]});if(!m.ok)return Yc(Ic(m.message));const _=m.writes;eA(_),Object.assign(_,p.writes);const f=p.answer;if("ops"===i){const{ops:t,refusals:n}=await xw({client:r,projectId:e.project_id,itemId:s.id,tokens:Aw(e.base_token),cells:nA(l,_)}),a=await kw({client:r,projectId:e.project_id,ops:t,refusals:n,labels:tA(d)}),i={...o?.analysis_props??{}},u={...i.field_source??{}};for(const[e,t]of Object.entries(_))"effect"!==e&&"title"!==e&&(i[e]=t),u[e]="mcp";const p=ad({...i}),m=Object.entries(u).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return jw(a.outcome,{row_id:s.id,subtype:l,scheme:d,field:e.field,field_source:"mcp",written_fields:Object.keys(_),written_columns:ql(d,Object.keys(_)),...c?{rationale_field:c}:{},...p?{approval_cleared:!0}:{},row:{id:s.id,computed_level:Ul(d,i),approved:!0===i.approved&&!p,mcp_fields:m,...Object.fromEntries(So[d].map(e=>[e,i[e]??null])),...f},acceptance_revoked:$w(a.answers),...f},a)}const h=async()=>{const t=LS(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(_))"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=ad(n),p=(new Date).toISOString();t.metadata={...t.metadata??{},updated_at:p,updated_by:a};const{data:m,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:WA()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(h)throw new Error(h.message);if(!m)return Yc(jc(`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:VA(),session_id:WA(),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 g=BS(o),y=g?await io(g,"The suggestion was",{readParent:()=>Dg(r,e.project_id,g),saveParent:(t,n)=>Jd(()=>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:WA()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at}),{scope:e.project_id,afterWrite:!0}),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 Kc(bc({row_id:s.id,subtype:l,scheme:d,field:e.field,field_source:"mcp",written_fields:Object.keys(_),written_columns:ql(d,Object.keys(_)),...c?{rationale_field:c}:{},...u?{approval_cleared:!0}:{},acceptance_revoked:y.revoked,...y.warning?{warning:y.warning}:{},row:{id:s.id,computed_level:Ul(d,n),approved:!0===n.approved,mcp_fields:w,...Object.fromEntries(So[d].map(e=>[e,n[e]??null])),...f},...f}))};return await h()}catch(r){const a=Sw(n,t,r);return a?_A(e,a):Yc(Uc(r))}}async function fA(e,t){let n;try{const r=await _u(),a=yu();try{await ju(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}const i=t??await vw(r,e.project_id);if("unreadable"===i)return bw();n=i;const s=await Dg(r,e.project_id,e.row_id);if(!s)return Yc(Sc("Analysis row",e.row_id));const o=s.data,l=PS(o?.req_type);if(!l)return Yc(Ic(Uf(e.row_id,s.type,"atoms_approve_row"),uc));const d=e.approver_id??a,c=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,d);if(!c)return Yc(Ic(`Approver '${d}' is not a member of this project's organization. Approve as a project member (omit approver_id to approve as yourself).`));if("viewer"===c)return Yc(Ic(function(e){return`Approver '${e}' is a viewer of this project's organization, and a viewer cannot be the human checker. Name an editor or admin (omit approver_id to approve as yourself).`}(d)));const{schemeId:u}=await YS(r,e.project_id,l,o),p=o?.analysis_props??{},m=Ul(u,p);if(m===_o)return Yc(Ic(`${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=Jc(e.note??""),n=(new Date).toISOString(),{ops:a,refusals:i}=await xw({client:r,projectId:e.project_id,itemId:s.id,tokens:Aw(e.base_token),cells:[{path:["analysis_props","approved"],value:!0},{path:["analysis_props","approved_at"],value:n},{path:["analysis_props","approved_by"],value:d},{path:["analysis_props","approved_note"],value:t}]}),o=await kw({client:r,projectId:e.project_id,ops:a,refusals:i,labels:tA(u)}),_=Object.entries(p.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return jw(o.outcome,{row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:d,approved_at:n,approved_note:t,approver_role:c,computed_level:m,cleared_markers:_,acceptance_revoked:$w(o.answers)},o)}const _=async()=>{const t=LS(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=Jc(e.note??""),_=(new Date).toISOString();n.approved=!0,n.approved_at=_,n.approved_by=d,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:g}=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:WA()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(g)throw new Error(g.message);if(!h)return Yc(jc(`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:d,approved_note:i},actor:VA(),session_id:WA(),reason:`${e.row_id} approved by ${d} via atoms_approve_row`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=BS(o);if(y){const t=await Dg(r,e.project_id,y);if(t){const{revoked:n,parentProps:i}=ao(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:WA()??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 Kc(bc({row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:d,approved_at:_,approved_note:i,approver_role:c,computed_level:m,cleared_markers:f}))};return await _()}catch(r){const a=Sw(n,t,r);return a?fA(e,a):Yc(Uc(r))}}H(NS,{approveRowHandler:()=>fA,createAnalysisHandler:()=>XS,fillRowHandler:()=>aA,getAnalysisHandler:()=>oA,getGapsHandler:()=>pA,linkMitigationHandler:()=>cA,proposeRowsHandler:()=>mA,suggestFieldHandler:()=>_A});var hA=D({"src/tools/analysis.ts"(){MS(),xu(),_e(),Wg(),Ib(),ww(),nc(),Ud(),kr(),JA(),tu(),ai(),Tw(),ai(),Id(),pd(),B_(),k_(),HS(),Yi(),nh(),vf(),Js(),zm(),ol(),DS=new Set(["safety-goal","failure-mode"])}}),gA={};async function yA(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=CS(n?.scenario_catalogs??[]);return a.ok?a.value:[]}async function wA(e){try{const t=await _u(),n=Math.min(Math.max(e.limit??50,1),200),r=Math.max(e.offset??0,0),a=await yA(t,e.project_id);return Kc(bc(a.slice(r,r+n),Od(a.length,n,r)),{paging:{}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Uc(e,{read:!0}))}}async function vA(e){const t=q_("atoms_mutate_scenario_catalog",e);if(t)return Yc(t);try{const t=await _u();yu();try{await ju(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Yc(xc("Viewer"));throw e}if("string"!=typeof(n=e.op)||!zS.includes(n))return Yc(Ic("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 yA(t,e.project_id)).length>=ES)return Yc(Ic(`This project already carries the maximum of ${ES} catalogs.`));const a={};if("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=Jc(e.name)),void 0!==e.entry_id&&(a.entry_id=e.entry_id),void 0!==e.text&&(a.text=Jc(e.text)),void 0!==e.function_ids){const n=await async function(e,t,n){const r=await l_(e,t);if(0===n.length){if("tags"===r)return{ok:!0,payload:{function_tags:[]}};if("items"===r)return{ok:!0,payload:{function_ids:[],function_tags:[]}}}else if("tags"===r)return{ok:!1,error:{status:"error",message:g_,next_steps:[...y_],code:"function_items_off",retryable:!1}};const a=await T_(e,t,n,r);return a.ok?{ok:!0,payload:{function_ids:a.functions.map(e=>e.id)}}:a}(t,e.project_id,e.function_ids);if(!n.ok)return Yc(n.error);Object.assign(a,n.payload)}void 0!==e.by&&(a.by=e.by),void 0!==e.on&&(a.on=e.on);const{data:i,error:s}=await t.rpc("mutate_project_scenario_catalogs",{p_project_id:e.project_id,p_op:r,p_payload:a});return s?Yc(K(s.message)??Ic(s.message)):Kc(bc({scenario_catalogs:i?.scenario_catalogs??[]}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Yc(qc()):Yc(Vc(e instanceof Error?e.message:String(e)))}var n}H(gA,{listScenarioCatalogsHandler:()=>wA,mutateScenarioCatalogHandler:()=>vA});var bA,kA,jA,SA,AA,$A,xA,IA,qA,OA,EA,zA,MA,RA,TA,CA,DA,HA=D({"src/tools/catalogs.ts"(){Ud(),xu(),re(),tu(),B_(),HS()}}),NA={};function PA(e){Je(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=M.default.dirname(n);return M.default.resolve(r,"apps","src","apps",e,t)}(t.appName,t.htmlFile),a=[...jg.resourceDomains,...t.extraResourceDomains??[]];l.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:n}}},t.handler),l.registerAppResource(e,`${t.title} UI`,n,{mimeType:l.RESOURCE_MIME_TYPE},async()=>{const e=await z.default.readFile(r,"utf-8");return{contents:[{uri:n,mimeType:l.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:a}}}}]}})}(AA,e)}function FA(e){return void 0===e?.requestId?void 0:String(e.requestId)}function UA(e,t,n){const r=t instanceof Error?t.message:String(t?.message??t);return process.stderr.write(`[atoms-mcp] ${e} lookup failed: ${r}\n`),t instanceof $t||/^auth_unavailable:/.test(r)?Yc(Ot()):Yt(r)?Yc(Mc()):/not authenticated/i.test(r)?Yc(qc()):Fc(t)||Zt(r)?Yc(Oc()):Yc(n())}function LA(e,t){return async(n,r)=>{let a="",i=null,s=!1;try{i=await _u(),a=yu()}catch(e){i=null,s=e instanceof $t}if(i){const e=await async function(e,t){let n;try{n=await nu(e,t)}catch(e){return process.stderr.write(`[atoms-mcp] platform_status lookup failed: ${e instanceof Error?e.message:String(e?.message??e)}\n`),Fc(e)?Oc():jc("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?Ac("account"):"pending"===n?jc("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 Yc(e)}if(i&&await Le(i,a),Te)return Yc({status:"error",message:U,next_steps:["Wait a few seconds, then retry the same call"],code:"policy_unavailable",retryable:!0,retry_after_seconds:2});if(!Re&&h.has(e))return Yc(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}:qc());if(!ne.has(e)){let t;try{t=await gu(async()=>(i=await _u(),a=yu(),async function(e,t,n,r){if(ne.has(n))return{refused:!1};const a=await ae(e,t);if(ie(a))return{refused:!0,reason:"viewer_everywhere"};const i=se(a);if(0===i.size)return{refused:!1};const{projectIds:s}=await oe(e,r);for(const t of s){const n=await le(e,t);if(n&&i.has(n))return{refused:!0,reason:"viewer_in_org"}}return{refused:!1}}(i,a,e,n)))}catch(e){return UA("viewer gate",e,ce)}if(t.refused)return Yc((o=t.reason,{status:"error",message:X,next_steps:[..."viewer_everywhere"===o?te:ee]}))}var o;{let t;try{t=await gu(async()=>{let t=null,r=null;try{t=await _u(),i=t,a=yu()}catch(s){r=s}return async function(e){const{client:t,toolName:n,params:r}=e;let a=e.set;const i=e.envProjectId??null,s=e.envOrgId??null,o=t=>e.envProjectRefusal?.(t)??null,l=r&&"object"==typeof r?r:{};if(!s&&!function(e,t,n){if(e.orgs.length<2)return!1;const r=e.orgs.map(e=>e.effective);if(r.some(e=>null!==e.project_scope))return!0;const a=e=>new Set(r.map(t=>JSON.stringify(e(t)))).size>1;return!!a(e=>ve(e,t,n))||!!a(e=>e.require_confirmation_for.includes(t))||pe.has(t)&&a(e=>G(e,"atoms_create_level").allowed)}(a,n,r)){const e=a.orgs[0]?.effective??P,s=ve(e,n,r);if(s)return s;if(i&&"string"==typeof l.project_id&&l.project_id!==i)return o(i);let d={projectIds:"string"==typeof l.project_id?[l.project_id]:[],unresolved:0};return ue.some(e=>"string"==typeof l[e])&&(i||null!==e.project_scope)&&(d=await oe(t,r)),i&&(d.unresolved>0||d.projectIds.some(e=>e!==i))?o(i):Y(e,d.projectIds,d.unresolved)}const{targets:d,unresolved:c}=await async function(e,t,n){const r=n&&"object"==typeof n?n:{},a="string"==typeof r.project_id?[r.project_id]:[];let i=0;for(const t of ue){const n=r[t];if("string"!=typeof n)continue;const s=await de(e,n);s?a.push(s):i++}const s=[];for(const n of a)s.push({projectId:n,orgId:await be(e,t,n)});return{targets:s,unresolved:i}}(t,a,r);if(s&&(c>0||d.some(e=>e.orgId!==s)))return e.envOrgRefusal?.(s)??null;const u=()=>d.filter(e=>null!==e.orgId&&!a.orgs.some(t=>t.orgId===e.orgId));if(e.reload&&u().length>0){a=await e.reload();for(const e of u())a.projectOrgs.delete(e.projectId)}const p=new Map,m=d.filter(e=>null===e.orgId).map(e=>e.projectId);for(const e of d)null===e.orgId||p.has(e.orgId)||p.set(e.orgId,{policy:ge(a,e.orgId),projectIds:[],unresolved:0});for(const e of d)null!==e.orgId&&p.get(e.orgId).projectIds.push(e.projectId);if(0===p.size)p.set("",{policy:ye(a),projectIds:m,unresolved:c});else for(const e of p.values())e.projectIds.push(...m),e.unresolved=c;for(const e of p.values()){const t=ve(e.policy,n,r);if(t)return t}if(i&&(c>0||d.some(e=>e.projectId!==i)))return o(i);for(const e of p.values()){const t=Y(e.policy,e.projectIds,e.unresolved);if(t)return t}return null}({client:t??(s=r,{from:()=>{throw s instanceof Error?s:new Error("Not authenticated")}}),set:Fe(),toolName:e,params:n,envProjectId:$e(),envProjectRefusal:Ec,envOrgId:xe(),envOrgRefusal:zc,reload:t?()=>async function(e,t){return Ee=0,await Le(e,t),Oe}(t,a):void 0});var s})}catch(e){return UA("project scope",e,Z)}if(t)return Yc(t)}if(!i)return t(n,r);const l=await async function(e,t){const n=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||ep,r=new Date,a=new Date(r.getTime()-tp);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())+tp-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*tp);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(!l.allowed)return Yc(Mc(l.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(()=>(xu(),mu));await t(i,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(tu(),yc));return Yc(e("Viewer (lockdown mode: read access requires editor or admin)"))}}}const d=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let c,u="success";try{const e=await t(n,r),a=e;if(!0===a?.isError){u="error";const e=a?.content;if(e?.[0]?.text)try{c=JSON.parse(e[0].text).message}catch{}}return hp(e,SA)}catch(e){throw u="error",c=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:n,status:u,duration_ms:d(),error_msg:c,project_id:n.project_id,session_id:xA,client_name:BA(),client_version:SA};try{!function(e,t,n){const r=Xu(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 _u(),a,t)}catch{}}}}function WA(){return xA}function VA(){return Ut(BA())}function BA(){const e=process.env.ATOMS_CLIENT_NAME;return Ft(e&&e.trim()?e:AA.server.getClientVersion()?.name)}H(NA,{ATOMS_MCP_SERVER_VERSION:()=>SA,getMcpActor:()=>VA,getMcpClientName:()=>BA,getMcpSessionId:()=>WA,server:()=>AA});var JA=D({"src/server.ts"(){var e;Wu(),Yu(),lp(),dp(),Ke(),Ie(),We(),Cp(),re(),Ae(),Qt(),Dp(),pd(),B(),xh(),Ah(),dg(),bg(),B_(),Sg(),fm(),ai(),gc(),nh(),xu(),pu(),_e(),tu(),re(),an(),Mt(),Ig(),e=c.z,bA=e.string().datetime({offset:!0}),kA=u.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href),jA=kA("../package.json"),SA=jA.version,function(e){const t=e=>e.endsWith(E)?e:`${e}\n\n${E}`;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)}}(AA=new d.McpServer({name:"atoms-mcp-server",version:SA})),function(e){De=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&&Ce.set(e,r),r}}(AA),$A=(e,t,n)=>{if(Je(e))return AA.registerTool(e,t,n)},xA=i.randomUUID(),$A("atoms_status",{title:"ATOMS MCP Health Check",description:Sh.atoms_status,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>gp(await(async()=>{const e=(e,t)=>async function(e,t,n){try{const e=await(async()=>async function(e,t){Xc.delete(t);const n=await nu(e,t);let r=null;const{data:a,error:i}=await e.from("organizations").select("id, name").eq("status","suspended");let s;i||(r=(a??[]).map(e=>({org_id:e.id,name:e.name})));try{s=ie(await ae(e,t))}catch{s=null}return{platform_status:n,org_suspended:r,viewer_only:s}}(await _u(),yu()))();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"]}:null===e.viewer_only?function(e){return{status:"error",email:e,message:"Your sign-in is valid, but ATOMS could not read your role in your organizations, so tool calls are refused until it can.",next_steps:["Retry in a moment; if it keeps failing, run atoms_status again or contact ATOMS support"]}}(t):!0===e.viewer_only?{status:"viewer_only",email:t,message:X,next_steps:[...te]}:{status:"authenticated",email:t,message:(e.org_suspended??[]).length>0?eu: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(()=>(ut(),Ye)),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(()=>(Pt(),Rt)),{email:n}=await t(),{invalidateClient:r}=await Promise.resolve().then(()=>(xu(),mu));return r(),{content:[{type:"text",text:ru(await e(n,"Token was expired but has been refreshed. You're good to go!"))}]}}catch(e){return e instanceof $t?{content:[{type:"text",text:JSON.stringify({...Ot(),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:ru(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)}]}}})(),SA)),$A("atoms_list_projects",{title:"List ATOMS Projects",description:Sh.atoms_list_projects,inputSchema:{offset:c.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:c.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_projects",async e=>{const{listProjectsHandler:t}=await Promise.resolve().then(()=>(Jg(),Vg));return t(e)})),$A("atoms_list_items",{title:"List ATOMS Items",description:Sh.atoms_list_items,inputSchema:{project_id:c.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:c.z.enum(cf).optional().describe("Filter by item type"),domain:c.z.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:c.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:c.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:c.z.number().int().min(0).default(0).describe("Pagination offset (default 0)"),after:c.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:c.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:bA.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}},LA("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(Kg(),Gg));return t(e)})),$A("atoms_get_item",{title:"Get ATOMS Item Details",description:Sh.atoms_get_item,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:c.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:bA.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}},LA("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(yy(),my));return t(e)})),$A("atoms_list_changes",{title:"List ATOMS Changes",description:O,inputSchema:{project_id:c.z.string().uuid(),since_seq:c.z.number().int().min(0).optional(),limit:c.z.number().int().min(1).max(500).default(100)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_changes",async e=>{const{listChangesHandler:t}=await Promise.resolve().then(()=>(ky(),wy));return t(e)})),$A("atoms_search",{title:"Search ATOMS Items",description:Sh.atoms_search,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),query:c.z.string().min(1).max(1e3).describe("Search text"),type:c.z.enum(cf).optional().describe("Filter by item type"),asset:c.z.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:c.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:c.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}},LA("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>($y(),Sy));return t(e)})),$A("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:Sh.atoms_semantic_search,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),query:c.z.string().min(1).max(1e3).describe("Natural-language concept query"),type:c.z.enum(cf).optional().describe("Filter by item type"),limit:c.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}},LA("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(qy(),xy));return t(e)})),PA({appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:Sh.atoms_get_coverage,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),domain:c.z.string().max(64).optional().describe("Filter by domain tag"),level:c.z.string().max(32).optional().describe("Filter by level"),baseline_id:c.z.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:bA.optional().describe("Compute coverage as of this ISO 8601 moment"),offset:c.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:c.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:LA("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(Ry(),Oy));return t(e)})}),$A("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.\npoints_run counts every point with a verdict, a passed point that needs a rerun included,\nso points_run / points_total is not the share of required runs complete while\nstale is true: the app counts such a point as a run still to do.\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\n${Th}\n\nverified_in: a Release promoted after carry shipped, while the rollout switch\nrelease_carry is on for the project, also counts a pass from an earlier\nRelease at a point that has no run bound to it, when nothing changed after\nthat run (the requirement's content, the test case's content or the link). A\nrequirement that reads verified and not stale through such a pass carries\nverified_in {version, build, run_at, tester}, naming the oldest such run (the\napp shows "Verified in <version>"); every other row has verified_in null. A\ncarried pass that something changed after makes the requirement stale and\nnames its test case under rerun; an earlier failure counts as failing.\n\naccepted_failures is present only while Accept failure is switched on for\nthe project. It lists each test case whose failure an editor or admin\naccepted in the app for this Release with a written reason: the app reads\nthat test as "Failed, accepted for <version>" (label) and never as Verified.\nThe app reads a requirement whose linked tests are each Verified or accepted,\nwith at least one accepted, as "Accepted for <version> (N known anomalies)".\nIts row in requirements keeps the projection's state (failing), so read it\nwith the requirement_ids of accepted_failures. An acceptance holds for this\nRelease only, and a newer run of the test in this Release, or a content\nchange to the test or a linked requirement, reopens it (it is then left out).\nWhile Accept failure is switched on, readiness counts each requirement that\nthe app reads as accepted for this Release under accepted and under no other\ncount, and counts a requirement with an accepted test that does not read\naccepted by its other linked tests, as the app's readiness strip does.\nNo tool accepts a failure: a person does that in the app.\n\ndocument_closures is present only while Close with a document is switched\non for the project, also when release is null. It lists each requirement an\neditor or admin closed in the app with a document named in their own words\n(document_name, link, closed_by, closed_at). The app reads a requirement\nclosed by a document as "Closed by document", covered and done, and a hazard\nwhose controls are each Verified or closed by a document as "Verified via\nmitigation". A requirement closed by a document with a linked test case\nkeeps its row in requirements, with the projection's state and\nclosed_by_document: true (false for a requirement with no standing\nclosure); read a row with closed_by_document true as covered and done.\nA requirement closed by a document with no linked test case has no row in\nrequirements but is still counted in readiness.requirements.\nWhile Close with a document is switched on, readiness counts each\nrequirement whose closure stands, with or without a linked test case,\nunder closed_by_document and under no other count, and leaves its points\nout of points_total and points_run. A closure holds in every Release until it is reopened in the app\nor the requirement's content changes (it is then left out). No tool closes a\nrequirement: a person does that in the app.\n\n${lg}\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 - include_report (boolean, optional, default false): Also return\n release_report, the Release report of the Release read.\n\nReturns:\n { release: {id, version, status} or null,\n readiness: {requirements, verified, failing, incomplete, not_run, stale,\n points_total, points_run, closed_by_document?}. 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, plus\n closed_by_document while Close with a document is switched on (a row\n closed by a document is counted there instead),\n requirements: [{requirement_id, state, stale, points_total, points_run, verified_in}]\n (each row also closed_by_document? while Close with a document is on),\n rerun: [{requirement_id, test_case_ids}],\n accepted_failures?: [{test_case_id, requirement_ids, label, reason, link,\n accepted_by, accepted_at}],\n document_closures?: [{requirement_id, label, document_name, link,\n closed_by, closed_at}],\n gaps?: [{tc_id, asset, point_key}],\n needs_attention?: [{id, action, reason}],\n release_report?: {release_id, release_version, status, stored_at, sha256,\n report_text} or null }\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:c.z.string().uuid().describe("UUID of the project"),release_id:c.z.string().uuid().optional().describe("Formal Release (baselines row) UUID; defaults to the project's current Release"),include_gaps:c.z.boolean().default(!1).describe("Include the not-run (test x unit x value) points for the Release"),include_report:c.z.boolean().default(!1).describe("Include release_report, the Release report of the Release read (where the Release report is switched on)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_verification_status",async e=>{const{verificationStatusHandler:t}=await Promise.resolve().then(()=>(Ly(),Cy));return t(e)})),$A("atoms_get_history",{title:"Get Item Change History",description:Sh.atoms_get_history,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).describe("Item ID"),limit:c.z.number().int().min(1).max(100).default(20).describe("Max entries (default 20)"),offset:c.z.number().int().min(0).default(0).describe("Revisions to skip from the newest (default 0); call again with offset=meta.next_offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(ew(),Ky));return t(e)})),PA({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:Sh.atoms_export_mermaid,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),root_item_id:c.z.string().max(20).optional().describe("Root item ID to start from"),depth:c.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:c.z.boolean().default(!0).describe("Include test case links"),baseline_id:c.z.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:bA.optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:LA("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(_w(),cw));return t(e)})}),qA=()=>c.z.string().max(128).optional().describe(S),OA=()=>c.z.enum(["edit","apply_mine"]).describe(A).optional(),EA=()=>c.z.string().min(1).max(600).optional().describe(x),zA=(IA=()=>c.z.union([c.z.string().min(1).max(Un),c.z.array(c.z.string().min(1).max(Un)).min(1).max(Ln)]).describe(j).optional())(),MA=qA(),$A("atoms_create_item",{title:"Create ATOMS Item",description:Sh.atoms_create_item,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the target project"),type:c.z.enum(ef).describe(tf),title:c.z.string().min(1).max(500).describe("Item title"),req_type:c.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe(Lu),body:c.z.string().max(5e4).optional().describe("Rich text body"),summary:c.z.string().max(2e3).optional().describe("Brief summary"),domains:c.z.array(c.z.string().max(64)).max(20).optional().describe("Domain tags"),level:c.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:c.z.array(c.z.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:c.z.record(c.z.string().max(60),c.z.string().max(2e3)).optional().describe("Project-field values keyed by defined field name"),echo:c.z.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens"),idempotency_key:qA()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Yv(),Qv));return t(e)})),RA={steps:c.z.array(c.z.object({id:c.z.string().describe(Op),instruction:c.z.string().describe("What the tester does"),test_data:c.z.string().optional().describe("Optional test data for the step"),expected:c.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. "+Op),params:c.z.array(c.z.object({name:c.z.string().describe("Parameter name; steps reference it as {name}"),unit:c.z.string().optional().describe("Optional unit (e.g. km/h, V, m)"),values:c.z.array(c.z.union([c.z.string(),c.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. "+qp)},$A("atoms_update_item",{title:"Update ATOMS Item",description:Sh.atoms_update_item,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).optional().describe("Item ID (single form)"),title:c.z.string().min(1).max(500).optional().describe("New title"),body:c.z.string().max(5e4).optional().describe("New body"),summary:c.z.string().max(2e3).optional().describe("New summary"),domains:c.z.array(c.z.string().max(64)).max(20).optional().describe("New domain tags (a function tag is not a domain and is rejected)"),level:c.z.string().max(32).optional().describe("New level"),status:c.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:c.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe(Lu),fields:c.z.record(c.z.string().max(60),c.z.string().max(2e3)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),...RA,expected_updated_at:bA.optional().describe(`metadata.updated_at value from atoms_get_item; rejects stale writes. ${I}`),base_token:IA(),intent:OA(),asil_confirm_lower:c.z.string().max(8).optional().describe(Cu),widget_proof:EA(),echo:c.z.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:c.z.string().max(500).optional().describe(oh),updates:c.z.array(c.z.object({item_id:c.z.string().min(1).max(20),title:c.z.string().min(1).max(500).optional(),body:c.z.string().max(5e4).optional(),summary:c.z.string().max(2e3).optional(),domains:c.z.array(c.z.string().max(64)).max(20).optional(),level:c.z.string().max(32).optional(),status:c.z.enum(["passed","failed","blocked","not-run"]).optional(),req_type:c.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional(),fields:c.z.record(c.z.string().max(60),c.z.string().max(2e3)).optional(),...RA,expected_updated_at:bA.optional(),base_token:IA(),intent:OA(),asil_confirm_lower:c.z.string().max(8).optional().describe(Cu)},{errorMap:kg("atoms_update_item","updates")}).strict()).optional().describe("Array form: update many items in one call"),idempotency_key:qA(),continue_on_error:c.z.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(Rb(),qb));return t(e)})),$A("atoms_delete_item",{title:"Delete ATOMS Item",description:Sh.atoms_delete_item,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:c.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}},LA("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Db(),Tb));return t(e)})),$A("atoms_restore_item",{title:"Restore ATOMS Item",description:ec,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().max(256).describe("ID of the item in Trash"),confirm:c.z.boolean().optional().describe(tc)},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(Vb(),Hb));return t(e)})),$A("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|allocated_to|allocated_from), 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 - allocated_to/allocated_from (Function items): links a requirement and a Function (the requirement is\n allocated_to the Function, the Function holds allocated_from). Needs a project with Function items turned on.\n A Function takes only allocation links and parent/child links to other Functions; any other pair is 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?: Change rationale, shown with the change in atoms_get_history and on its History line in the app\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 written in calls of up to 100 operations (removes before adds), each call all or nothing; a batch of more than 100 is NOT one transaction: a failure leaves earlier calls committed and names which operations\n - reason?, idempotency_key? supported\n\nidempotency_key: ${S}`,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),from_id:c.z.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:c.z.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:c.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]).optional().describe("Relationship type"),action:c.z.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:bA.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:bA.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:c.z.boolean().optional().describe("false → lean response"),reason:c.z.string().max(500).optional().describe(oh),operations:c.z.array(c.z.object({action:c.z.enum(["add","remove"]),from_id:c.z.string().min(1).max(20),to_id:c.z.string().min(1).max(20),type:c.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]),expected_from_updated_at:bA.optional(),expected_to_updated_at:bA.optional()},{errorMap:kg("atoms_link_items","operations")}).strict()).optional().describe("Array form: batch relationship ops, DAG-validated as a whole then written in calls of up to 100 ops, each all or nothing (the batch is not one transaction); a failure reports which ops committed."),idempotency_key:qA()},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},LA("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(rk(),ek));return t(e)})),PA({appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:Sh.atoms_bulk_import,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the target project"),items:c.z.array(c.z.object({type:c.z.enum(ef).describe(tf),title:c.z.string().min(1).max(500).describe("Item title"),body:c.z.string().max(5e4).optional().describe("Rich text body"),summary:c.z.string().max(2e3).optional().describe("Brief summary"),domains:c.z.array(c.z.string().max(64)).max(20).optional().describe("Domain tags"),level:c.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:c.z.string().max(20).optional().describe("Parent item ID to link")},{errorMap:kg("atoms_bulk_import","items",vg)}).strict()).min(1).max(500).describe("Items to create (1-100; 1-500 on a project that saves one field at a time)"),confirmation_token:c.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),idempotency_key:qA()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:LA("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(mk(),lk));return t(e)})}),TA={point:c.z.record(c.z.string(),c.z.union([c.z.string(),c.z.number()])).optional().describe('Matrix point this run executed, e.g. {"speed": 40}'),release_id:c.z.string().uuid().optional().describe("Formal Release to bind this run to (a baseline with a release_version)"),build:c.z.string().optional().describe("Free-text build label"),environment:c.z.string().optional().describe("Structured environment field, distinct from build"),tooling:c.z.string().optional().describe("Structured tooling field, distinct from build"),steps_rev:c.z.string().optional().describe($p),evidence_url:c.z.string().optional().describe(Ip),step_results:c.z.array(c.z.object({step_id:c.z.string().describe("Step id from atoms_get_item steps[].id"),status:c.z.enum(["passed","failed","blocked","skipped"]).describe("Per-step status"),actual:c.z.string().optional().describe("Actual-result note"),evidence_url:c.z.string().optional().describe(xp)}).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.")},$A("atoms_record_test_result",{title:"Record Test Result",description:Sh.atoms_record_test_result,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:c.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:c.z.string().max(500).optional().describe("Reason or comment for this result"),asset:c.z.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new."),date:c.z.string().optional().describe(kp),...TA,idempotency_key:MA},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_record_test_result",async(e,t)=>{const{recordTestResultHandler:n}=await Promise.resolve().then(()=>(gk(),_k));return n({...e,request_id:FA(t)})})),$A("atoms_record_test_results",{title:"Record Test Results (bulk)",description:Sh.atoms_record_test_results,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:c.z.array(c.z.object({asset:c.z.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:c.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:c.z.string().max(500).optional().describe("Run note"),date:c.z.string().optional().describe("Ignored: runs are stamped with server time. A supplied date is reported in the response warning, never stored."),...TA},{errorMap:kg("atoms_record_test_results","results")}).strict()).min(1).max(100).describe("1 to 100 result entries on this test case"),idempotency_key:MA},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_record_test_results",async(e,t)=>{const{recordTestResultsBulkHandler:n}=await Promise.resolve().then(()=>(vk(),yk));return n({...e,request_id:FA(t)})})),PA({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:Sh.atoms_trace,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).describe("Starting item ID"),direction:c.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:c.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:c.z.array(c.z.enum(["parent","child","related","verifies","verified_by","mitigated_by","mitigates","affects","affected_by","allocated_to","allocated_from","event_hazard","hazard_events","event_goal","goal_events"])).optional().describe("Filter to specific relationship types"),offset:c.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:c.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:LA("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(jk(),bk));return t(e)})}),$A("atoms_list_assets",{title:"List Project Assets",description:Sh.atoms_list_assets,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),include_archived:c.z.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>($k(),Sk));return t(e)})),CA=()=>c.z.string().regex(/^MD-\d{3,}$/i).describe("The design's MD id, such as MD-001"),DA=()=>c.z.string().max(4194304).describe("The diagram as a Mermaid flowchart (the form atoms_get_model_design returns)"),$A("atoms_list_model_designs",{title:"List Model Designs",description:Sh.atoms_list_model_designs,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_model_designs",async e=>{const{listModelDesignsHandler:t}=await Promise.resolve().then(()=>(Rk(),xk));return t(e)})),$A("atoms_get_model_design",{title:"Get Model Design",description:Sh.atoms_get_model_design,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),display_id:CA()},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_get_model_design",async e=>{const{getModelDesignHandler:t}=await Promise.resolve().then(()=>(Rk(),xk));return t(e)})),$A("atoms_create_model_design",{title:"Create Model Design",description:Sh.atoms_create_model_design,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(1e3).describe("The design's name, 1 to 200 characters after blanks at either end are removed"),description:c.z.string().max(1e4).optional().describe("What the design shows, at most 5000 characters"),mermaid:DA().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_model_design",async e=>{const{createModelDesignHandler:t}=await Promise.resolve().then(()=>(Rk(),xk));return t(e)})),$A("atoms_update_model_design",{title:"Update Model Design",description:Sh.atoms_update_model_design,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),display_id:CA(),expected_version:c.z.number().int().min(1).describe("The version you read with atoms_get_model_design"),name:c.z.string().min(1).max(1e3).optional().describe("A new name, 1 to 200 characters after blanks at either end are removed"),description:c.z.string().max(1e4).optional().describe("A new description, at most 5000 characters"),mermaid:DA().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_update_model_design",async e=>{const{updateModelDesignHandler:t}=await Promise.resolve().then(()=>(Rk(),xk));return t(e)})),$A("atoms_list_variables",{title:"List Project Variables",description:Sh.atoms_list_variables,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),baseline_id:c.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:bA.optional().describe("Optional ISO timestamp for time-travel reads"),limit:c.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:c.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(nj(),Lk));return t(e)})),$A("atoms_get_variable",{title:"Get Project Variable",description:Sh.atoms_get_variable,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),variable_name:c.z.string().min(1).max(64).describe("Variable name"),baseline_id:c.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:bA.optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(nj(),Lk));return t(e)})),$A("atoms_update_variable",{title:"Update Project Variable",description:Sh.atoms_update_variable,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),variable_name:c.z.string().min(1).max(64).describe("Variable name"),value:c.z.string().max(500).optional().describe("New value"),unit:c.z.string().max(32).optional().describe("Unit abbreviation"),description:c.z.string().max(2e3).optional().describe("Description"),echo:c.z.boolean().optional(),base_token:zA},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(nj(),Lk));return t(e)})),$A("atoms_create_variable",{title:"Create Project Variable",description:Sh.atoms_create_variable,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(64).optional().describe("Variable name (single form)"),value:c.z.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:c.z.string().max(32).optional().describe("Unit abbreviation"),description:c.z.string().max(2e3).optional().describe("Description"),echo:c.z.boolean().optional().describe("false → lean response (default true)"),variables:c.z.array(c.z.object({name:c.z.string().min(1).max(64).describe("Variable name"),value:c.z.string().min(1).max(500).describe("Initial value"),unit:c.z.string().max(32).optional().describe("Unit abbreviation"),description:c.z.string().max(2e3).optional().describe("Description")},{errorMap:kg("atoms_create_variable","variables")}).strict()).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:c.z.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(nj(),Lk));return t(e)})),$A("atoms_delete_variable",{title:"Delete Project Variable",description:Sh.atoms_delete_variable,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(64).describe("Variable name to delete"),force:c.z.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:c.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),base_token:zA},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},LA("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(nj(),Lk));return t(e)})),$A("atoms_list_domains",{title:"List Project Domains",description:Sh.atoms_list_domains,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(cj(),rj));return t(e)})),$A("atoms_create_domain",{title:"Create Project Domain",description:Sh.atoms_create_domain,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(cj(),rj));return t(e)})),$A("atoms_list_levels",{title:"List Project Levels",description:Sh.atoms_list_levels,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(pv(),Bw));return t(e)})),$A("atoms_create_level",{title:"Create Project Level",description:Sh.atoms_create_level,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(pv(),Bw));return t(e)})),$A("atoms_delete_level",{title:"Delete Project Level",description:Sh.atoms_delete_level,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(64).describe("Level name to delete"),confirmation_token:c.z.string().optional().describe("Token from the first (preview) call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},LA("atoms_delete_level",async e=>{const{deleteLevelHandler:t}=await Promise.resolve().then(()=>(pv(),Bw));return t(e)})),$A("atoms_reorder_levels",{title:"Reorder Project Levels",description:Sh.atoms_reorder_levels,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),names:c.z.array(c.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}},LA("atoms_reorder_levels",async e=>{const{reorderLevelsHandler:t}=await Promise.resolve().then(()=>(pv(),Bw));return t(e)})),$A("atoms_list_fields",{title:"List Project Fields",description:`List the project's custom field definitions (project-scoped key-value slots on items, e.g. "Verification Method"), with counts of items carrying a value.\n\nField values are set per item via atoms_create_item / atoms_update_item fields.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { fields: [{ name, type, options, item_count }], total }, meta\n\n${$h("fields")}`,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),offset:c.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:c.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(Gv(),Ov));return t(e)})),$A("atoms_create_field",{title:"Create Project Field",description:Sh.atoms_create_field,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:c.z.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:c.z.array(c.z.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:c.z.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization"),appliesTo:c.z.array(c.z.enum(["requirement","test-case","note","table","function"])).max(5).optional().describe("Item types this field shows on (requirement|test-case|note|table|function); omit for all types")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(Gv(),Ov));return t(e)})),$A("atoms_delete_field",{title:"Delete Project Field",description:'Delete a project field definition. Existing item values are left in item JSON but no longer render as Matrix columns; they come back only if a field of the same name and a type that takes them is created again (a create of a type that cannot take them is refused, naming the item count).\n\nOnly an org admin of the project\'s organization can delete a field definition.\n\nWhen your organization requires confirmation for this tool, the first call returns { status: "confirmation_required", preview, confirmation_token } and deletes nothing; re-call with the same project_id, name and that confirmation_token to delete.\n\nArgs:\n - project_id (string, UUID): Project containing the field\n - name (string): Field name to delete\n - confirmation_token (string, optional): Token from the preview call, when confirmation is required',inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(60).describe("Field name"),confirmation_token:c.z.string().max(500).optional().describe("Token from the preview call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},LA("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(Gv(),Ov));return t(e)})),$A("atoms_reorder_fields",{title:"Reorder Project Fields",description:"Reorder project field definitions. Definition order drives the Column Picker listing and a fresh user's Matrix column order.\n\nOrdering only: no definition is added, dropped, renamed, or retyped, and no item value moves. Use this instead of deleting and recreating definitions to change their order.\n\nOnly an org admin of the project's organization can reorder field definitions.\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:c.z.string().uuid().describe("UUID of the project"),names:c.z.array(c.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}},LA("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(Gv(),Ov));return t(e)})),$A("atoms_update_domain",{title:"Update Project Domain",description:Sh.atoms_update_domain,inputSchema:c.z.object({project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(64).describe("Current domain name"),new_name:c.z.string().min(1).max(64).describe("New domain name"),dry_run:c.z.boolean().optional().describe("Preview impact without applying (default false)")},{errorMap:O_("atoms_update_domain")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(cj(),rj));return t(e)})),$A("atoms_delete_domain",{title:"Delete Project Domain",description:Sh.atoms_delete_domain,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(64).describe("Domain name to delete"),force:c.z.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:c.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}},LA("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(cj(),rj));return t(e)})),PA({appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:Sh.atoms_project_summary,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:LA("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(mj(),uj));return t(e)})}),PA({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:Sh.atoms_browse,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),type:c.z.enum(cf).optional().describe("Filter by item type"),domain:c.z.string().max(64).optional().describe("Filter by domain tag"),level:c.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:c.z.string().max(1e3).optional().describe("Full-text search query"),limit:c.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:c.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:LA("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(hj(),_j));return t(e)})}),$A("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:Sh.atoms_impact_analysis,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),item_id:c.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:c.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:c.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:c.z.boolean().default(!0).describe("Also list the items that share a {variable} with the item (no relationship needed), each with shared_variables naming every variable it shares. Default true."),offset:c.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:c.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(zj(),gj));return t(e)})),$A("atoms_list_baselines",{title:"List ATOMS Baselines",description:Sh.atoms_list_baselines,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),limit:c.z.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:c.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(AS(),_S));return t(e)})),$A("atoms_create_baseline",{title:"Create ATOMS Baseline",description:Sh.atoms_create_baseline,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),name:c.z.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:c.z.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(AS(),_S));return t(e)})),$A("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:Sh.atoms_lock_baseline,inputSchema:{baseline_id:c.z.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(AS(),_S));return t(e)})),$A("atoms_diff_baselines",{title:"Diff ATOMS Baselines",description:Sh.atoms_diff_baselines,inputSchema:{baseline_a_id:c.z.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:c.z.string().uuid().describe("UUID of the second (newer) baseline"),detail:c.z.boolean().default(!1).describe("Add a per-field from/to diff object to each modified item (default false)"),limit:c.z.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:c.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(AS(),_S));return t(e)})),$A("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:Sh.atoms_restore_baseline,inputSchema:{baseline_id:c.z.string().uuid().describe("UUID of the baseline to restore from"),confirm:c.z.boolean().default(!1).describe("Set true to execute; false (default) returns a preview"),source_seq:c.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:c.z.string().uuid().optional().describe($),after_id:c.z.string().min(1).max(64).optional().describe($),confirmation_token:c.z.string().max(500).optional().describe("Token from the preview, when your organization requires confirmation for this tool")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},LA("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(AS(),_S));return t(e)})),$A("atoms_create_analysis",{title:"Create Analysis (HARA, Risk analysis, FMEA)",description:Sh.atoms_create_analysis,inputSchema:c.z.object({project_id:c.z.string().uuid().describe("UUID of the target project"),subtype:c.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:c.z.string().min(1).max(500).optional().describe("Analysis title"),source_function_ids:c.z.array(c.z.string().min(1).max(20)).max(50).optional().describe("HARA or risk analysis only: the ids of the Function items to seed rows from (0-50), e.g. FN-001"),source_assets:c.z.array(c.z.string().min(1).max(100)).max(50).optional().describe("Security risk analysis only: the asset names to seed rows from (0-50), kept as text"),source_req_ids:c.z.array(c.z.string().min(1).max(20)).max(50).optional().describe("dfmea only: requirement IDs to seed rows from (0-50)"),revision:c.z.string().min(1).max(32).optional().describe("Revision label (default 1.0)"),variant:c.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:c.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:c.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:c.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:c.z.string().max(1e4).optional().describe("Security risk analysis only: the threat modeling methodology used, e.g. STRIDE."),threat_model_rationale:c.z.string().max(1e4).optional().describe("Security risk analysis only: why that methodology was chosen."),environment_assumptions:c.z.string().max(1e4).optional().describe("Security risk analysis only: assumptions about the operating environment, one per line."),attack_surfaces:c.z.string().max(1e4).optional().describe("Security risk analysis only: interfaces and entry points considered, one per line."),related_documents:c.z.string().max(1e4).optional().describe("Security risk analysis only: where the SBOM, the security testing report and the architecture views live."),idempotency_key:MA,hazard_id:c.z.string().max(20).optional().describe(nf),goal_id:c.z.string().max(20).optional().describe(rf)},{errorMap:O_("atoms_create_analysis")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("atoms_fill_row",{title:"Fill Analysis Row Fields",description:Sh.atoms_fill_row,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),row_id:c.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:c.z.record(c.z.string().max(64),c.z.union([c.z.string().max(5e4),c.z.number()])).describe("Field name to value map (see description for allowed keys per subtype)"),base_token:zA},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("atoms_get_analysis",{title:"Get Analysis",description:Sh.atoms_get_analysis,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),analysis_id:c.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),offset:c.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:c.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:Sh.atoms_link_mitigation,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),row_id:c.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:c.z.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:c.z.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows (every FMEA); must be omitted for hara rows."),override:c.z.boolean().optional().describe("hara only: apply the row's level (ASIL or Risk) over a conflicting existing value (history-logged)"),control_type:c.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:c.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:!0,idempotentHint:!1,openWorldHint:!1}},LA("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:Sh.atoms_get_gaps,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),analysis_id:c.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}},LA("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("atoms_propose_rows",{title:"Write Proposed Analysis Rows",description:Sh.atoms_propose_rows,inputSchema:c.z.object({project_id:c.z.string().uuid().describe("UUID of the project"),analysis_id:c.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),rows:c.z.array(c.z.record(c.z.string().max(64),c.z.union([c.z.string().max(5e4),c.z.number()]))).min(1).max(po).describe(`The drafted rows (1-${po}), each a scheme field name to value map`),source_function_id:c.z.string().min(1).max(20).optional().describe("HARA or risk analysis only: the id of the Function item these rows analyse, e.g. FN-001"),source_req:c.z.string().min(1).max(20).optional().describe("FMEA only: the requirement these rows analyse"),idempotency_key:MA},{errorMap:O_("atoms_propose_rows")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_propose_rows",async e=>{const{proposeRowsHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("atoms_suggest_field",{title:"Write a Suggested Value for One Analysis Field",description:Sh.atoms_suggest_field,inputSchema:{project_id:c.z.string().uuid().describe("UUID of the project"),row_id:c.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),field:c.z.string().min(1).max(64).describe("The field to fill (a scheme key of this row)"),value:c.z.union([c.z.string().max(5e4),c.z.number()]).describe("The suggested value"),rationale:c.z.string().max(5e4).optional().describe("The evidence behind a suggested rating; written to the scheme's evidence field"),base_token:zA},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_suggest_field",async e=>{const{suggestFieldHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("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:c.z.string().uuid().describe("UUID of the project"),row_id:c.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),approver_id:c.z.string().uuid().optional().describe("The approving project member; defaults to the calling user"),note:c.z.string().max(2e3).optional().describe("Optional note captured with the approval"),base_token:zA},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_approve_row",async e=>{const{approveRowHandler:t}=await Promise.resolve().then(()=>(hA(),NS));return t(e)})),$A("atoms_list_scenario_catalogs",{title:"List Operational Scenario Catalogs",description:Sh.atoms_list_scenario_catalogs,inputSchema:{project_id:c.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),limit:c.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:c.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},LA("atoms_list_scenario_catalogs",async e=>{const{listScenarioCatalogsHandler:t}=await Promise.resolve().then(()=>(HA(),gA));return t(e)})),$A("atoms_mutate_scenario_catalog",{title:"Mutate an Operational Scenario Catalog",description:Sh.atoms_mutate_scenario_catalog,inputSchema:c.z.object({project_id:c.z.string().uuid().describe("UUID of the project"),op:c.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:c.z.string().min(1).max(64).optional().describe("The catalog id (optional for create_catalog: generated when omitted)"),name:c.z.string().min(1).max(100).optional().describe("The catalog name (create_catalog, rename_catalog)"),entry_id:c.z.string().min(1).max(64).optional().describe("The entry id (caller-generated for add_entry)"),text:c.z.string().min(1).max(100).optional().describe("The entry's operational scenario text"),function_ids:c.z.array(c.z.string().min(1).max(20)).optional().describe("The ids of the Function items this entry applies to (e.g. FN-001); [] = every function, accepted on any project; ids need Function items turned on"),by:c.z.string().min(1).max(200).optional().describe("The accepter's name (accept_catalog)"),on:c.z.string().min(1).max(32).optional().describe("The acceptance date (accept_catalog)")},{errorMap:O_("atoms_mutate_scenario_catalog")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},LA("atoms_mutate_scenario_catalog",async e=>{const{mutateScenarioCatalogHandler:t}=await Promise.resolve().then(()=>(HA(),gA));return t(e)})),Ue()}});Ke(),We(),xu();var GA=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"),QA=process.argv.slice(2)[0];(async function(){switch(QA){case"login":{const{login:e}=await Promise.resolve().then(()=>(Eu(),Iu));try{const{email:t}=await e();process.stderr.write(`\n [32m✓[0m Authenticated as ${t}\n`),process.stderr.write(" [32m✓[0m Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" [1mNext steps:[0m\n"),process.stderr.write(" [36m$[0m claude mcp add atoms -- npx -y @atoms-tech/atoms-mcp@latest\n"),process.stderr.write("\n Or add to Claude Desktop (Settings → MCP → Edit Config):\n"),process.stderr.write(' [90m{\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp@latest"]\n }\n }\n }[0m\n\n')}catch(e){process.stderr.write(`\n [31m✗[0m ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>(Pt(),Rt));try{const{email:t,user_id:n}=await e();process.stderr.write(`\n [32m✓[0m Logged in as ${t}\n [90mUser ID: ${n}[0m\n\n`)}catch(e){process.stderr.write(`\n [31m✗[0m 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(()=>(ut(),Ye));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${GA.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 e=!0;try{const{startupAuth:t}=await Promise.resolve().then(()=>(Du(),zu)),n=await t();e=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(e)try{const e=await _u(),t=yu();await async function(e,t){try{const n=await qe(e,t);!function(e){Oe=e,Ee=Date.now(),Re=!0,Te=!1}(n),Ne(n)}catch(e){Re=!1,Te=e instanceof me,process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). `+(Te?"No tool runs until it loads.\n":"Changes are paused until it loads; RLS still enforces row-level access.\n"))}}(e,t)}catch(e){Pe(),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 Pe(),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=Be(),t=Ve(),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:t}=await Promise.resolve().then(()=>(JA(),NA)),n=new p.StdioServerTransport;await t.connect(n);const{startUpdateCheck:r}=await Promise.resolve().then(()=>(Cp(),cp));r(),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}})().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("@modelcontextprotocol/ext-apps/server"),c=require("@modelcontextprotocol/sdk/server/mcp.js"),d=require("zod"),u=require("module"),p=require("@modelcontextprotocol/sdk/server/stdio.js"),m="undefined"!=typeof document?document.currentScript:null;function f(e){return e&&e.__esModule?e:{default:e}}var _,h,g,y,w,v,b,k,j,x,S,$,A,I,q,M,O,E=f(e),z=f(n),R=f(i),T=Object.defineProperty,C=Object.getOwnPropertyNames,P=(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}},D=(e,t)=>{for(var n in t)T(e,n,{get:t[n],enumerable:!0})};function N(e){return k.get(e)}var H,F,L,U,W,V,B=P({"src/core/tool-catalog.ts"(){_=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","atoms_create_model_design","atoms_update_model_design"]),g=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_level","atoms_delete_field","atoms_restore_baseline"]),y={atoms_mutate_scenario_catalog:{param:"op",values:["delete_catalog"]},atoms_link_items:{param:"action",values:["remove"],arrayParam:"operations"},atoms_link_mitigation:{param:"action",values:["remove"]}},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","atoms_list_model_designs","atoms_get_model_design","atoms_create_model_design","atoms_update_model_design"],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),k=new Map;for(const[e,t]of Object.entries(v))for(const n of t)k.set(n,e);j="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.",x="Retry key: sending the same call again with the same key within 24 hours changes nothing twice.",S="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.",$="Set both from the previous answer when it says complete is false, to continue the same restore.",A="Set by the ATOMS editor card. Do not set this yourself.",I="Ignored on projects that save one field at a time; send base_token instead.",q="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.",M="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."}}),G=P({"src/core/types.ts"(){H={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:[]},F={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 J(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&&h.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&g.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=N(t);return void 0===n||e.allowed_toolsets.includes(n)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function Q(e){switch(e){case"lockdown":return"This project's organization puts MCP in lockdown for your role: on its projects only atoms_list_items, atoms_get_item, atoms_search and atoms_browse work.";case"read_only":return"This project's organization puts MCP in read-only mode for your role, so its projects take no changes through MCP.";case"block_destructive":return"Your org policy blocks destructive operations (deletes, link removals, snapshot restore).";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."}}function Y(e){const t=/^(?:Database error: )?(mcp_policy_(read_only|lockdown|block_destructive|block_bulk_import|project_scope|forbidden_tool)): (.+?) is blocked by your org's MCP Access Policy \(/.exec(e);if(!t)return null;const[,n,r,a]=t;return{status:"error",message:`${a.charAt(0).toUpperCase()}${a.slice(1)} is blocked by org policy. This change was not saved.`,next_steps:["project_scope"===r?W:Q(r),"Contact your org admin to adjust the MCP access policy.","Do not retry this call."],code:n,retryable:!1}}function K(e,t,n=0){const r=e.project_scope;if(null===r)return null;if(0===t.length&&0===n)return null;if(0===r.length)return{status:"error",message:U,next_steps:["No tool works on this organization's projects while its Project scope is No projects (atoms_status and atoms_list_projects still work)","An org admin can change Project scope in the MCP policy of Org Settings"]};const a=[`Allowed projects: ${r.length} project${1===r.length?"":"s"} configured by your admin`,"Use atoms_list_projects to see which projects you can access in this session"];return n>0?{status:"error",message:V,next_steps:a}:t.some(t=>!function(e,t){return null===e.project_scope||e.project_scope.includes(t)}(e,t))?{status:"error",message:W,next_steps:a}:null}function Z(){return{status:"error",message:"Project scope check failed.",next_steps:["ATOMS could not confirm which project this call targets, so the call was refused","Retry in a moment; if it keeps failing, run atoms_status"]}}var X,ee,te,ne,re=P({"src/core/policy.ts"(){B(),L="Your organization's MCP policy could not be read just now. Nothing was run. Try again in a moment.",U="Your admin set Project scope to No projects for your role. Ask an org admin to change it.",W="Tool call rejected: project_id is outside your org's MCP project scope.",V="Tool call rejected: this baseline is not in a project your org's MCP project scope allows, or could not be found."}});async function ae(e,t){const{data:n,error:r}=await e.from("org_members").select("org_id, role").eq("user_id",t);if(r)throw new Error(r.message??String(r));return Array.isArray(n)?n:n?[n]:[]}function ie(e){return e.length>0&&e.every(e=>"viewer"===e.role)}function se(e){return new Set(e.filter(e=>"viewer"===e.role&&"string"==typeof e.org_id).map(e=>e.org_id))}async function oe(e,t){const n=t&&"object"==typeof t?t:{},r="string"==typeof n.project_id?[n.project_id]:[];let a=0;for(const t of["baseline_id","baseline_a_id","baseline_b_id"]){const i=n[t];if("string"!=typeof i)continue;const s=await ce(e,i);s?r.push(s):a++}return{projectIds:r,unresolved:a}}async function le(e,t){const{data:n,error:r}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(r)throw new Error(r.message??String(r));const a=n?.org_id;return"string"==typeof a?a:null}async function ce(e,t){const{data:n,error:r}=await e.from("baselines").select("project_id").eq("id",t).maybeSingle();if(r)throw new Error(r.message??String(r));const a=n?.project_id;return"string"==typeof a?a:null}function de(){return{status:"error",message:"Authorization check failed.",next_steps:["ATOMS could not confirm your role in this project's organization, so the call was refused","Retry in a moment; if it keeps failing, run atoms_status"]}}var ue,pe,me,fe=P({"src/core/viewer-gate.ts"(){X="Viewers cannot use the ATOMS MCP. Ask an org admin for editor access.",ee=["Your role in this project's organization is viewer, and viewers cannot use ATOMS tools","Read the project in the ATOMS web app, or ask an org admin to make you an editor"],te=["You are a viewer in every organization you belong to, so no ATOMS tool can be used","Read your projects in the ATOMS web app, or ask an org admin to make you an editor"],ne=new Set(["atoms_status"])}});function _e(e,t=new Map){return{orgs:e,projectOrgs:t}}function he(e){const t="string"==typeof e?.code?e.code:"";return""===t||/^PGRST00[0-3]$/.test(t)}function ge(e,t){return e.orgs.find(e=>e.orgId===t)?.effective??F}function ye(e){if(0===e.orgs.length)return H;if(1===e.orgs.length)return e.orgs[0].effective;const t=e.orgs.map(e=>e.effective),n=e=>t.some(t=>!0===t[e]),r=e=>e.reduce((e,t)=>e.filter(e=>t.includes(e))),a=e=>[...new Set(e.flat())],i=t.map(e=>e.project_scope).filter(e=>null!==e);return{read_only:n("read_only"),lockdown:n("lockdown"),block_destructive:n("block_destructive"),block_bulk_import:n("block_bulk_import"),cross_project_browse:t.every(e=>!0===e.cross_project_browse),allowed_toolsets:r(t.map(e=>e.allowed_toolsets)),forbidden_tools:a(t.map(e=>e.forbidden_tools)),project_scope:0===i.length?null:[...new Set(r(i))],require_confirmation_for:a(t.map(e=>e.require_confirmation_for))}}function we(e,t){return!!_.has(t)||(0===e.orgs.length?J(H,t).allowed:e.orgs.some(e=>J(e.effective,t).allowed))}function ve(e,t,n){const r=J(e,t);if(!r.allowed)return{status:"error",message:`Tool ${t} is blocked by org policy.`,next_steps:[Q(r.reason),"Contact your org admin to adjust the MCP access policy."]};const a=function(e,t,n){const r=y[t];if(!e.block_destructive||!r)return{allowed:!0};const a=n??{},i=r.arrayParam&&Array.isArray(a[r.arrayParam])?a[r.arrayParam]:[],s=[a[r.param],...i.map(e=>e?.[r.param])].find(e=>"string"==typeof e&&r.values.includes(e));return void 0===s?{allowed:!0}:{allowed:!1,reason:"block_destructive",message:`Tool ${t} op ${s} is blocked by org policy.`}}(e,t,n);return a.allowed?null:{status:"error",message:a.message,next_steps:[Q(a.reason),"Contact your org admin to adjust the MCP access policy."]}}async function be(e,t,n){const r=t.projectOrgs.get(n);if("string"==typeof r)return r;const a=await le(e,n);return null!==a&&t.projectOrgs.set(n,a),a}function ke(e,t){if(e.orgs.length<=1)return e.orgs[0]?.effective??H;const n=t?e.projectOrgs.get(t):void 0;return"string"==typeof n?ge(e,n):ye(e)}var je,xe,Se=P({"src/core/org-policy.ts"(){G(),re(),B(),fe(),ue=["baseline_id","baseline_a_id","baseline_b_id"],pe=new Set(["atoms_create_item","atoms_update_item","atoms_bulk_import"]),me=class extends Error{name="PolicyTransientError"}}});function $e(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?je.test(e)?e:(xe||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),xe=!0),null):null}function Ae(){return process.env.ATOMS_MCP_ORG_ID?.trim()||null}var Ie=P({"src/middleware/project-scope.ts"(){je=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,xe=!1}});async function qe(e,t,n){return async function(e,t,n=new Map){const r=await Promise.all(e.map(t));return _e(e.map((e,t)=>({orgId:e,role:r[t].role,effective:r[t].effective,failedClosed:r[t].effective===F})),n)}(await async function(e,t){try{const n=await async function(e,t){const{data:n,error:r}=await e.from("org_members").select("org_id, joined_at, organizations!inner(status)").eq("user_id",t).eq("organizations.status","active").neq("role","viewer").order("joined_at",{ascending:!0});if(r)throw new Error(r.message??String(r));const a=Array.isArray(n)?n:n?[n]:[];return[...new Set(a.map(e=>e.org_id).filter(e=>"string"==typeof e))]}(e,t),r=Ae();return r?n.filter(e=>e===r):n}catch(e){const t=e instanceof Error?e.message:String(e);throw process.stderr.write(`[atoms-mcp] Could not resolve session org: ${t}\n`),new Error(`Could not resolve session org: ${t}`)}}(e,t),n=>async function(e,t,n){if(!n)return{role:null,is_member:!1,effective:H};const{data:r,error:a}=await async function(e,t,n){const r={p_user_id:t,p_org_id:n},a=await e.rpc("mcp_resolve_policy",r);return a.error&&he(a.error)?await e.rpc("mcp_resolve_policy",r):a}(e,t,n);if(a&&he(a))throw process.stderr.write(`[atoms-mcp] mcp_resolve_policy unreachable: ${a.message}. Changes are paused until it loads.\n`),new me(String(a.message??"mcp_resolve_policy unreachable"));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:F}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:H};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.filter(e=>"string"==typeof e):null;return{role:n,is_member:r,effective:{read_only:s(a.read_only,H.read_only),lockdown:s(a.lockdown,H.lockdown),block_destructive:s(a.block_destructive,H.block_destructive),block_bulk_import:s(a.block_bulk_import,H.block_bulk_import),cross_project_browse:s(a.cross_project_browse,H.cross_project_browse),allowed_toolsets:i(a.allowed_toolsets,H.allowed_toolsets),forbidden_tools:i(a.forbidden_tools,H.forbidden_tools),project_scope:l,require_confirmation_for:i(a.require_confirmation_for,H.require_confirmation_for)}}}(r)}(e,t,n),n)}var Me,Oe,Ee,ze,Re,Te,Ce,Pe,De=P({"src/db/policy.ts"(){Se(),Ie(),G()}});function Ne(e){if(0!==e.orgs.length)for(const t of e.orgs)process.stderr.write(t.failedClosed?`[atoms-mcp] Org policy could not be read: org=${t.orgId.slice(0,8)}… (its projects are refused until it can be read)\n`:`[atoms-mcp] Org policy loaded: org=${t.orgId.slice(0,8)}… role=${t.role??"?"} read_only=${t.effective.read_only} lockdown=${t.effective.lockdown}\n`);else process.stderr.write("[atoms-mcp] No org membership detected — running with permissive default policy.\n")}function He(){Re=!1}function Fe(){return Me}function Le(){const e=Pe,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 Ce){const n=we(Me,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?.()}async function Ue(e,t){Re&&Date.now()-Oe<=Ee||(ze||(ze=(async()=>{try{const n=await qe(e,t,Me.projectOrgs);Me=n,Re||Ne(n),Re=!0,Te=!1}catch(e){Re=!1,Te=e instanceof me}Oe=Date.now(),Le()})().finally(()=>{ze=null})),await ze)}var We=P({"src/middleware/session-policy.ts"(){Se(),De(),Me=_e([]),Oe=Date.now(),Ee=3e4,ze=null,Re=!0,Te=!1,Ce=new Map,Pe=null}});function Ve(){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 Be(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function Ge(e){if(Be()&&h.has(e))return!1;if(_.has(e))return!0;const t=Ve();if(null===t)return!0;const n=N(e);return!!n&&t.allowed.has(n)}var Je,Qe,Ye=P({"src/middleware/tool-registry.ts"(){B(),Se(),We()}}),Ke={};async function Ze(){try{const t=await e.readFile(Qe,"utf-8"),n=JSON.parse(t);return n.access_token&&n.refresh_token?n:null}catch{return null}}async function Xe(t){await e.mkdir(Je,{recursive:!0,mode:448}),await e.writeFile(Qe,JSON.stringify(t,null,2),{mode:384})}async function et(){const e=await Ze();return!!e&&e.expires_at>Date.now()+6e4}function tt(e){return e.expires_at>Date.now()+6e4}async function nt(){try{await e.unlink(Qe)}catch{}}function rt(){return Qe}D(Ke,{clearCredentials:()=>nt,getCredentialsPath:()=>rt,hasValidCredentials:()=>et,isTokenValid:()=>tt,readCredentials:()=>Ze,writeCredentials:()=>Xe});var at,it,st,ot,lt,ct,dt,ut=P({"src/auth/token-store.ts"(){Je=n.join(t.homedir(),".atoms"),Qe=n.join(Je,"credentials.json")}}),pt={};async function mt(){try{await e.mkdir(at,{recursive:!0,mode:448});const t=await e.open(it,"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 ft(){try{await e.unlink(it)}catch{}}async function _t(){try{const t=await e.stat(it);return Date.now()-t.mtimeMs>st}catch{return!1}}async function ht(e,t,n=dt){const r=n.now()+ot;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(lt)}}}D(pt,{runExclusiveAuth:()=>ht});var gt,yt,wt,vt=P({"src/auth/lock.ts"(){at=n.join(t.homedir(),".atoms"),it=n.join(at,".auth.lock"),st=7e4,ot=12e4,lt=300,ct=e=>new Promise(t=>setTimeout(t,e)),dt={now:Date.now,wait:ct,tryAcquire:mt,release:ft,isStale:_t}}}),bt={};function kt(e){return e.trim().replace(/\/+$/,"")}D(bt,{ATOMS_APP_URL:()=>wt,ATOMS_SUPABASE_ANON_KEY:()=>yt,ATOMS_SUPABASE_URL:()=>gt,resolveUrl:()=>kt});var jt,xt,St,$t,At,It=P({"src/config.ts"(){gt=kt(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),yt=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",wt=process.env.ATOMS_APP_URL??"https://atoms.tech"}});function qt(e){return e instanceof $t||!!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||!!At.statuses.includes(n)||At.codedStatuses.includes(n)&&"string"==typeof r&&At.codes.includes(r)}(e)}function Mt(){return{status:"error",code:jt,retryable:!0,message:St,next_steps:[`Wait ${xt} seconds, then retry the same call`,"Do not sign out or log in again: the saved session is still valid"]}}var Ot,Et,zt=P({"src/core/auth-outage.ts"(){jt="auth_unavailable",xt=5,St="ATOMS could not check your sign-in just now. Your session is kept. Try again in a moment.",$t=class extends Error{code=jt;constructor(e){super(`${jt}: ${e}`),this.name="AuthServiceUnavailableError"}},At={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"]}}}),Rt={};async function Tt(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=Pt(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await Ze();if(t&&t.expires_at>Date.now()+6e4){const e=Pt(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 Ct(){const e=await Tt();if(e)return e;const t=await Ze();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp@latest login' to connect your ATOMS account.");return ht(async()=>{const e=await Tt();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(gt,yt,{global:{fetch:Et}});let n=await t.auth.refreshSession({refresh_token:e.refresh_token});if(n.error||!n.data.session){const r=await Ze();if(r&&r.expires_at>Date.now()+6e4){const e=Pt(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(qt(n.error))throw new $t(`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 Xe({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 Pt(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}D(Rt,{AUTH_CALL_TIMEOUT_MS:()=>Ot,getValidToken:()=>Ct,readValidToken:()=>Tt});var Dt,Nt,Ht=P({"src/auth/refresh.ts"(){ut(),vt(),It(),zt(),Ot=1e4,Et=async(e,t)=>{const n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Auth did not answer within ${Ot} ms`)),Ot),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 Ft(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,Nt).replace(/_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?Dt:t:Dt}function Lt(e){const t=Ft(e);return"cursor"===t?"mcp_cursor":"copilot"===t?"mcp_copilot":"mcp_claude"}var Ut,Wt,Vt,Bt,Gt,Jt,Qt=P({"src/core/client-identity.ts"(){Dt="claude_desktop",Nt=64}});function Yt(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}function Kt(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 Zt(e){return/token refresh failed|saved atoms session is no longer valid|jwt\s*expired|invalid.?jwt|jwt.*invalid|pgrst30[12]/i.test(e)}function Xt(e){return"string"==typeof e&&e.includes(Vt)}function en(e){return"string"==typeof e&&e.includes(Bt)}function tn(e){return"project"===e?{status:"error",message:"An org admin is needed to change this project's field definitions.",next_steps:["Ask an admin of this organization 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"]}}function nn(e,t){const n=Array.isArray(t.next_steps)?t.next_steps:[];return[`Do not re-send the whole batch: the ${e} committed operation(s) would be applied again.`,...!1===t.retryable?[]:["Reconcile from the committed list, then retry only the failed and any remaining operations."],...n]}function rn(e){const t=Jt.exec(e);if(!t)return null;const[,n,r,a]=t;return{status:"error",message:`${r} cannot be a parent of ${n}, because ${n} is already above ${r}${a.trim()?` (${a.trim()})`:""}. That link would make a loop, so nothing was saved.`,next_steps:["Do not retry this call: the same link is refused every time.",`Choose another parent for ${n}, or first remove the link that puts ${n} above ${r}.`],code:"hierarchy_cycle",retryable:!1}}var an=P({"src/core/errors.ts"(){Ut=[/^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 /,/^event_source .* is not allowed \(allowed: web, mcp\)/s],Wt=class extends Error{},Vt="rollout_switched:multiuser_saving: This project still saves whole items. Reload, then save again.",Bt="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.",Gt=10,Jt=/^(?:[A-Za-z_][\w ]{0,60}:\s+){0,2}hierarchy_cycle:\s+(\S+) cannot go under (\S+) because \S+ is already above it \(([^)]*)\)/}});function sn(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function on(e){return e.replace(/[\\%_*]/g,e=>`\\${e}`)}function ln(e){return sn(`*${on(e)}*`)}function cn(e){return on(e)}function dn(e){return`*"${on(e)}"*`}async function un(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 pn,mn,fn,_n,hn,gn,yn,wn,vn,bn,kn,jn,xn=P({"src/core/postgrest.ts"(){}});async function Sn(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(a,n);void 0!==a&&(s=s.or(An(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(`${$n(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(`${$n(s)} read, page ${i}: the page did not move past the last row read`);r.push(...c),a=d}}function $n(e){const t=e.url;return t instanceof URL?decodeURIComponent(t.pathname).replace(/^.*\/rest\/v1\//,""):"query"}function An(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 sn(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 In(e,t,n,r){return Sn(()=>e.rpc(t,{p_project_id:n,p_snapshot_at:r}),hn[t])}function qn(e,t,n){return"baselineId"in n?Sn((t,r)=>e.rpc("baseline_state_page",{p_baseline_id:n.baselineId,p_after_id:t?.id??null,p_limit:r}),pn):In(e,"project_state_at",t,n.at)}function Mn(e,t,n){return"baselineId"in n?Sn(()=>e.rpc("baseline_variables_state",{p_baseline_id:n.baselineId}),_n):In(e,"variables_at",t,n.at)}async function On(e,t){const n=[];for(let r=0;r<e.length;r+=wn){const{data:a,error:i}=await t(e.slice(r,r+wn));if(i)throw new Error(i.message);n.push(...a??[])}return n}function En(e,t){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(kn(t)?[e.created_at,e.id,t]:[e.created_at,e.id]))}var zn,Rn,Tn,Cn,Pn,Dn,Nn,Hn,Fn,Ln,Un,Wn,Vn,Bn,Gn,Jn,Qn,Yn,Kn,Zn,Xn,er,tr,nr,rr,ar,ir,sr,or,lr,cr,dr,ur,pr,mr,fr,_r,hr,gr,yr,wr,vr,br,kr=P({"src/core/paginate.ts"(){xn(),mn=["from_id","to_id","type"],fn=["name","id"],hn={project_state_at:pn=["id"],variables_at:_n=["name","id"]},gn=e=>({at:e}),yn=e=>({baselineId:e}),wn=200,vn=100,bn=["created_at","id"],kn=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0,jn=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 jr(e){return/rollout_switched:multiuser_saving/i.test(e)}function xr(){return{status:"error",message:Rn,next_steps:[Tn],code:"rollout_switched",retryable:!1}}function Sr(e){return/project_in_trash/i.test(e)||e===Pn}function $r(){return{status:"error",message:Cn,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 Ar(e){return e===Nn||/not a member of this project's organization/i.test(e)||/\b[a-z_]+: not a member of this project\s*$/i.test(e)}function Ir(){return{status:"error",message:Dn,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 qr(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 Mr(e){const t=/approved_item_delete_blocked: ([^\s;:]{1,60}) /.exec(e);return t?{status:"error",message:`${t[1]}: ${Hn}. Nothing was changed.`,next_steps:["Do not retry this call.","Only a project admin releasing review on the project removes the block, and that returns every item to draft.","Use atoms_get_item to read the item."],code:"approved_item_delete_blocked",retryable:!1}:null}function Or(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&&Kt(t.message)?new Error(t.message):t&&"42501"!==t.code||!Fn.test(e)?new Error(`Project '${e}' not found`):new Error(Nn)}function Er(e){return/too_many_items/.test(e)}function zr(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 Rr(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 Tr(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":Tr(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)}:${Tr(t[e])}`).join(",")}}`}return"null"}async function Cr(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 Pr(e,t,n="item"){return e&&"object"==typeof e?"variable"===n?"variables"!==t[0]?null:t.length<=2?e:Dr(e[t[2]],t.slice(3)):0===t.length?e.data??null:Jn.has(t[0])?1===t.length?e[t[0]]??null:null:Dr(e.data,t):null}function Dr(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 Nr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Hr(e,t){return e.length<=t.length&&e.every((e,n)=>e===t[n])}function Fr(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=>Hr(e,t)));if(0===t.length||Qn.has(t[0]))return!1;switch(r){case"item":case"all":return!0;case"core":return Wn.some(e=>Nr(e,t));case"analysis":return Nr(t,["title"])||Nr(t,["body"])||("analysis_props"===t[0]||"relationships"===t[0])&&t.length>=2;case"paths":return(a??[]).some(e=>Hr(e,t))}return!1}async function Lr(e,t,n="item"){let r;if("string"!=typeof t)r=t.paths.map(t=>Pr(e,t,n));else if("core"===t||"analysis"===t){const a="core"===t?Wn:Vn;r=Object.fromEntries(a.map(t=>[JSON.stringify(t),Pr(e,t,n)]))}else r=e??null;return(await Cr(Tr(r))).slice(0,16)}function Ur(e,t,n){return`${e}.${t}~${function(e){return"string"==typeof e?e:`paths:${encodeURIComponent(JSON.stringify(e.paths))}`}(n)}`}async function Wr(e,t,n="item"){return Ur(e.id,await Lr(e.fields_snapshot,t,n),t)}function Vr(e){if("string"!=typeof e||0===e.length||e.length>Ln)return null;const t=Gn.exec(e);if(!t)return null;const n=t[1].toLowerCase(),r=t[2].toLowerCase(),a=t[3];if(Bn.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 Br(e){return"variable"===e?{table:"variable_revisions",idCol:"variable_id"}:{table:"item_revisions",idCol:"item_id"}}function Gr(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 Jr(e,t){return new Error(String(e?.message??`${t} failed`))}async function Qr(e,t,n,r="item"){const a=new Map,i=[...new Set(n)],{table:s,idCol:o}=Br(r);for(let n=0;n<i.length;n+=vn){const{data:r,error:l}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in(o,i.slice(n,n+vn)).is("valid_to",null).is("deleted_at",null);if(l)throw Jr(l,`${s} read`);for(const e of r??[]){const t=Gr(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 Yr(e,t,n,r="item"){const a=new Map,i=[...new Set(n)],{table:s,idCol:o}=Br(r);for(let n=0;n<i.length;n+=vn){const{data:r,error:l}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in("id",i.slice(n,n+vn));if(l)throw Jr(l,`${s} read`);for(const e of r??[]){const t=Gr(e,o);a.set(t.id,t)}}return a}async function Kr(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 Jr(r,"changes_since");const a=n?.head_seq;return"number"==typeof a?a:Number(a??0)}async function Zr(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 Jr(o,"fresh_typing_notes");for(const e of s??[]){const t=a.get(e.item_id)??[];t.push({path:e.path,field_label:Xr(e.path,r),person:{name:e.user_name??"Someone",kind:"person"}}),a.set(e.item_id,t)}return a}function Xr(e,t){if(!e||0===e.length)return"Item";const n=Kn[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 ea(e){return JSON.stringify(e)}async function ta(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=Vr(n);t?(e.parsed.push(t),r.push(t.revisionId)):e.bad=!0}n.set(t.itemId,e)}const a=await Yr(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 Lr(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)Fr(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(ea(n),{base:Pr(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 Qr(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",...na(t,e.req),path:e.path,seq:null,current:r?Pr(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",...na(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 na(e,t){return"variable"===e?{item_id:null,name:t.name??t.itemId,variable_id:t.itemId}:{item_id:t.itemId}}function ra(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 aa(e){return e?"agent"===e.kind?e.label??e.name??null:e.name??null:null}async function ia(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??""}|${ea(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(Zn.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:aa(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??""}|${ea(c??[])}`),u={item_id:l.item_id??null,...null===l.item_id&&l.name?{name:l.name}:{},path:c,field_label:Xr(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),"relationships"===c?.[0]&&"string"==typeof u.your_value&&u.your_value.length<=ir&&(u.to_id=u.your_value);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 f=null;"conflict"===l.status?("current"in l&&(u.theirs_value=l.current),l.current_revision_id&&(f={revId:l.current_revision_id,rev:e.revisionsById?.get(l.current_revision_id),value:l.current??null})):m&&c?(u.theirs_value=Pr(m.fields_snapshot,c),f={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 _=l.current_author??p?.change?.author??null;_&&(u.changed_by={kind:_.kind,name:aa(_)});const h=l.current_at??p?.change?.at??null;(_||h)&&(u.changed_at=h);const g=l.current_seq??p?.change?.seq;if(null!=g&&(u.seq=g),("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),f&&c){const e=`${u.item_id??u.name??""}|${f.revId}`,t=i.get(e)??{revId:f.revId,rev:f.rev,entries:[]};t.entries.push({entry:u,value:f.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=ea(a.path);t.has(s)||(t.add(s),n.push(a.path),r.push(e.rev?Pr(e.rev.fields_snapshot,a.path):i))}const a=(await Cr(Tr(r))).slice(0,16),i=Ur(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=oa(e,t),a.not_applied.push(ca(e));return a.replayed=e.answers.length>0&&e.answers.every(e=>!0===e.replayed),a}function sa(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 oa(e,t){const n=sa(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&&"far"===t?.trashed_end&&t.trashed_id?`${n} ${r} not saved: the linked item ${t.trashed_id} is in the Trash.`:"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: ${aa(t?.change_author??null)??a} has an open change on ${"string"==typeof t?.change_item_id&&t.change_item_id?t.change_item_id: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"approved_item_delete_blocked"===s?`${n}: ${Hn}.`:`${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"asil_put_back":return`${n} ${r} not saved: a row that gives ${n} its ASIL was not saved, so nothing of ${n} was saved.`;case"link_end_skipped":return`${n} ${r} not saved: an item linked with ${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 String(t?.forbidden_reason??"").startsWith("mcp_policy_")?`${n} ${r} not saved: your org's MCP Access Policy does not allow this change.`:`${n} ${r} not saved: your role cannot change it.`;case"approved":return`${n} ${r} not saved: ${n} is approved.`;case"chunk_not_sent":return e.to_id?`${n} --[${e.path?.[1]??"link"}]--\x3e ${e.to_id} not saved: an earlier part of this call failed, so this part was not sent.`:`${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 la(e){if("string"==typeof e)return e.length;const t=JSON.stringify(e);return void 0===t?0:t.length}function ca(e){const t={...e},n=[];for(const e of dr)e in t&&la(t[e])>Xn&&(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 ${Xn} characters and was left out. Read it with atoms_get_item (${sa(e)}), then send your change again.`),t}function da(e){return"string"==typeof e?`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`:Array.isArray(e)?e.map(da):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,da(t)])):e}function ua(e){const t=new TextEncoder,n=t.encode(JSON.stringify(e)??"").length,r=t.encode(JSON.stringify(da(e),null,2)??"").length;return Math.max(n,r)}function pa(e,t=ua){if(t(e)<=er)return e;const n=e.not_applied.map(e=>{const t={...e};let n=!1;for(const e of dr)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)<=er)return r;const a=n.map(e=>{const{message:t,hint:n,...r}=e;return r});if(r={...r,not_applied:a},t(r)<=er)return r;const{applied:i,...s}=r,o={...s,next_steps:r.next_steps.map(e=>e===rr?ar:e),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<nr&&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))<=er?c=e:d=e-1}return l(c)}function ma(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??oa(a),i=t-r-1>0?` And ${t-r-1} more.`:"";if([...n,e].join(" ").length+i.length>tr)break;n.push(e),r+=1}r<t&&n.push(`And ${t-r} more.`);const a=n.join(" ");return a.length<=tr?a:a.slice(0,tr)}function fa(e){const t=t=>e.not_applied.some(t),n=[rr];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(sr),t(e=>"skipped_typing"===e.status||"skipped"===e.status&&"typing"===e.reason)&&n.push(or),t(e=>"locked"===e.status||"skipped"===e.status&&"locked"===e.reason)&&n.push(lr),t(e=>"conflict"===e.status&&("no_base"===e.reason||"bad_token"===e.reason))&&n.push(cr),n}function _a(e,t,n){const r=e.applied.length+e.captured.length;return{isError:0===r,result:pa({...t??{},status:r>0?"partial":"error",code:"not_all_applied",retryable:!1,message:ma(e),next_steps:fa(e),applied:e.applied,not_applied:e.not_applied,seq:e.seq,...e.merged_fields.length>0?{merged_fields:e.merged_fields}:{}},n)}}function ha(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 ga(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)}`}(ur,e.map(String).join("\n"))}function ya(){return crypto.randomUUID()}function wa(e){return[e.userId,e.projectId,"create_item",e.content,e.k,e.sessionId]}function va(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 ba(e){return va({userId:e.userId,projectId:e.projectId,family:ja(e.tool),key:e.key,itemIdOrK:e.itemId,path:["runs"],runHash:e.runHash,runK:e.k})}function ka(e){return[e.userId,e.projectId,e.what,e.name]}function ja(e){return"atoms_create_item"===e||"atoms_bulk_import"===e?"item":e}function xa(e){const t=new Map;return e.map(e=>{const n=t.get(e)??0;return t.set(e,n+1),n})}function Sa(e){return"string"==typeof e?e.replace(/<\s*\/?\s*user_content\s*>/gi,""):Array.isArray(e)?e.map(Sa):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Sa(t)])):e}function $a(e){return Tr(Sa({type:e.type,title:e.title,body:e.body??null,summary:e.summary??null,req_type:e.req_type??null,domains:pr(e.domains),level:e.level??null,parent_ids:pr(e.parent_ids),fields:e.fields??{}}))}function Aa(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 Ia(e){if(!e.item_id)return[];const t=[e.item_id];if(("add"===e.kind||"remove"===e.kind)&&2===e.path.length&&"relationships"===e.path[0]){const n=e.value,r="string"==typeof n?n:n&&"object"==typeof n?n.id:void 0;"string"==typeof r&&r!==e.item_id&&t.push(r)}return t}function qa(e){const t=new Set;for(const n of e)for(const e of Ia(n.op))t.add(e);return t}function Ma(e,t,n){const r=[];let a=[],i=new Set;for(const s of e.flatMap(e=>function(e,t){if(qa(e.ops).size<=t)return[e];const n=[];let r=[],a=new Set;for(const i of e.ops){const s=Ia(i.op),o=new Set([...a,...s]);r.length>0&&o.size>t?(n.push({key:e.key,ops:r}),r=[],a=new Set(s)):a=o,r.push(i)}return r.length>0&&n.push({key:e.key,ops:r}),n}(e,t))){const e=new Set([...i,...qa(s.ops)]);a.length>0&&(e.size>t||a.length+s.ops.length>n)?(r.push(a),a=[],i=qa(s.ops)):i=e,a.push(...s.ops)}return a.length>0&&r.push(a),r.map(e=>e.sort((e,t)=>e.index-t.index).map(e=>e.op))}function Oa(e){return e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message:e)}function Ea(e){return/too_many_items/.test(Oa(e))}function za(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 Ra(e,t){let n;try{n=await e.rpc("rollout_state",{p_project_id:t})}catch{return null}const{data:r,error:a}=n;if(a){if("42501"===a.code||Ar(a.message??""))throw new Error(Nn);return null}return!!r&&"object"==typeof r&&!0===r.multiuser_saving}function Ta(){return{status:"error",message:_r,next_steps:["Send the same call again in a moment"],code:"rollout_state_unreadable",retryable:!0}}function Ca(e,t){const n=Oa(t);return"ops"===e&&Xt(n)?"main":"main"===e&&(en(n)||n.includes(zn))?"ops":null}async function Pa(e,t){try{return await t(e)}catch(n){const r=Ca(e,n);if(!r)throw n;return t(r)}}function Da(e){const t=Lt(e);return"mcp_cursor"===t?"Cursor":"mcp_copilot"===t?"Copilot":"Claude"}function Na(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)}`}function Ha(e){return e.startsWith("op_id_reused: ")}function Fa(){return{status:"error",message:hr,next_steps:["Send the call again with a new idempotency_key, or without one"],code:"op_id_reused",retryable:!1}}async function La(e){return Cr("string"==typeof e?e:Tr(Sa(e)))}async function Ua(e){return e.content_hash=await La({kind:e.kind,value:e.value??null,order_key:e.order_key??null}),e}function Wa(e){const t=new Map;for(const n of e){const e="string"==typeof n?n:n?.op_id;if("string"!=typeof e||0===e.length)continue;const r="string"==typeof n||"string"!=typeof n.content_hash?void 0:n.content_hash;t.has(e)&&void 0===r||t.set(e,r)}return t}async function Va(e,t,n){const r=new Map,a=new Set,i=Wa(n),s=[...i.keys()];for(let n=0;n<s.length;n+=vr){const{data:o,error:l}=await e.rpc("mcp_op_answers",{p_project_id:t,p_op_ids:s.slice(n,n+vr)});if(l)throw Jr(l,"mcp_op_answers");for(const e of o?.answers??[]){if(!e||!e.op_id)continue;const{content_hash:t,...n}=e,s=i.get(e.op_id);"string"==typeof t&&"string"==typeof s&&t!==s?a.add(e.op_id):r.set(e.op_id,{...n,replayed:!0})}}return{found:r,reused:a}}async function Ba(e,t,n){const{found:r,reused:a}=await Va(e,t,n);if(a.size>0)throw new Error(br);return r}async function Ga(e,t,n,r=[]){const a=e=>"invalid"===e.status&&"op_id_reused"===e.reason,i=n.filter(a).map(e=>e.op_id);if(0===i.length)return n.map(e=>({...e}));const s=Wa(r),{found:o,reused:l}=await Va(e,t,i.map(e=>({op_id:e,content_hash:s.get(e)})));return n.map(e=>{if(!a(e))return{...e};if(l.has(e.op_id))return{...e,retryable:!1,message:hr};const t=o.get(e.op_id);return t?{...t,replayed:!0}:{...e,message:hr}})}function Ja(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 Qa,Ya,Ka,Za,Xa,ei,ti,ni,ri,ai=P({"src/core/agent-saving.ts"(){Qt(),an(),kr(),B(),zn="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.",Rn="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: ",""),Tn="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.",Cn="This project is in the Trash. Nothing was saved. A project admin can restore it in ATOMS, then try again.",Pn="PROJECT_IN_TRASH",Dn="You no longer have access to this project. Ask an admin of its organization to add you back.",Nn="PROJECT_ACCESS_LOST",Hn="it is approved under change control, so it cannot be moved to Trash",Fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ln=2e3,Un=20,Wn=[["title"],["summary"],["body"],["req_type"],["status"],["tags","domains"],["tags","level"]],Vn=[["title"],["body"],["analysis_props"],["relationships"]],Bn=new Set(["item","all","analysis","core","variable"]),Gn=/^([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,Jn=new Set(["title","type","approver_user_id","requires_impacted_approval"]),Qn=new Set(["variables","taxonomy","settings"]),Yn="The items were saved, but their base_token could not be read. Read each item with atoms_get_item before you update it.",Kn={'["title"]':"Title",'["summary"]':"Summary",'["body"]':"Body",'["req_type"]':"Type",'["type"]':"Type",'["status"]':"Status",'["tags","level"]':"Level",'["tags","domains"]':"Domains",'["asil_confirm_lower"]':"ASIL"},Zn=new Set(["applied","noop","replaced"]),Xn=4e3,er=65536,tr=600,nr=200,rr="Changes under applied are saved; do not send them again. Tell the person which changes were not saved and why.",ar="The applied_count changes are saved; do not send them again. Send only the not_applied changes again, and tell the person which changes were not saved and why.",ir=64,sr="For each conflict: merge theirs_value with your change, then call the tool again with that entry's base_token.",or="For a field someone is typing in: offer to try again in a minute.",lr="For a locked item: ask the person it is locked to, or an admin, to unlock it.",cr="For a change with no base: read the item with atoms_get_item, or use the entry's base_token, then send it again.",dr=["your_value","theirs_value","base_value"],ur="0b7e5c1a-3d2f-4e6b-9a8c-1f2e3d4c5b6a",pr=e=>[...new Set((e??[]).map(e=>String(Sa(e))))].sort(),mr=50,fr=500,_r="Could not read how this project saves, so nothing was saved. Try again.",gr="The change is saved. A read for this answer failed, so part of the answer is missing. Do not send the write again; read the item with atoms_get_item if you need it.",yr="Already created by an earlier identical call. Nothing new was created. To create another copy, call again with a new idempotency_key.",wr="Already recorded by an earlier identical call. Nothing new was stored. To record another run, call again with a new idempotency_key.",vr=500,br="op_id_reused: "+(hr="idempotency_key already used for a different change; use a new key.")}});function ii(e){const t=e??{},n=t.tags?.domains;return[t.title||"",t.body||"",t.summary||"",Array.isArray(n)?n.join(", "):"",t.tags?.level||"",t.type||""].filter(Boolean).join(" | ")}function si(e){return{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken.replace(/^Bearer\s+/i,"")}`,...e.anonKey?{apikey:e.anonKey}:{}}}async function oi(e,t,n){try{if(!e.supabaseUrl||!e.accessToken)return;const r=e.fetch??fetch,a=[...new Set(n)],i=a.slice(0,Xa);a.length>i.length&&console.error(`[embed-on-save] ${a.length-i.length} of ${a.length} items of project ${t} left to the backlog sweep (more than ${Xa} in one call)`);const s=[];for(let n=0;n<i.length;n+=Za){const a=i.slice(n,n+Za).map(e=>`"${e.replace(/["\\]/g,"\\$&")}"`).join(","),o=`${e.supabaseUrl}/rest/v1/items?select=id,data&project_id=eq.${encodeURIComponent(t)}&deleted_at=is.null&id=in.(${encodeURIComponent(a)})`,l=await r(o,{method:"GET",headers:si(e)});if(!l.ok){console.error(`[embed-on-save] item read failed (${l.status})`);continue}const c=await l.json();Array.isArray(c)&&s.push(...c)}await async function(e,t,n){try{if(!e.supabaseUrl||!e.accessToken)return;const r=e.fetch??fetch,a=n.filter(e=>"string"==typeof e.id&&""!==e.id).map(e=>({itemId:e.id,projectId:t,text:ii(e.data??{})})).filter(e=>e.text.trim().length>=3),i=[];for(let e=0;e<a.length;e+=Ya)i.push(a.slice(e,e+Ya));let s=0,o=0;const l=async()=>{for(;o<i.length;){const t=i[o++];try{const n=await r(`${e.supabaseUrl}/functions/v1/embed/batch`,{method:"POST",headers:si(e),body:JSON.stringify({items:t})});if(n.ok){const e=Number((await n.json().catch(()=>({}))).failed);Number.isFinite(e)&&e>0&&(s+=e)}else s+=t.length,console.error(`[embed-on-save] embed batch failed (${n.status}) for ${t.map(e=>e.itemId).join(", ")}`)}catch(e){s+=t.length,console.error("[embed-on-save] embed batch failed:",e instanceof Error?e.message:e)}}};await Promise.all(Array.from({length:Math.min(Ka,i.length)},l)),s>0&&console.error(`[embed-on-save] ${s} of ${a.length} items of project ${t} left without a fresh embedding; scripts/backfill-embeddings.ts fills them`)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}(e,t,s)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}function li(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){if(!n||"string"!=typeof n.item_id||""===n.item_id)continue;const e=Array.isArray(n.path)?n.path[0]:void 0;("create_item"===n.kind||"string"==typeof e&&Qa.includes(e))&&t.add(n.item_id)}return[...t]}function ci(e,t,n){return`${e.supabaseUrl}/rest/v1/project_changes?project_id=eq.${encodeURIComponent(t)}&bulk_id=eq.${encodeURIComponent(n)}`}function di(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e[ni];return t&&"object"==typeof t?t:null}function ui(e){const t=globalThis.EdgeRuntime;try{t?.waitUntil?.(e)}catch{}}function pi(e,t=fetch){const n={...e,fetch:t};return async(e,r)=>{const a=await t(e,r);try{const t=a.ok?function(e,t){if("POST"!==(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase())return null;const n="string"==typeof e?e:e instanceof URL?e.href:e instanceof Request?e.url:"",r=/\/rest\/v1\/rpc\/([A-Za-z0-9_]+)(?:\?|$)/.exec(n);return r&&ri.has(r[1])?r[1]:null}(e,r):null;if(t&&"string"==typeof r?.body){const e=JSON.parse(r.body),a=e.p_project_id;if("string"==typeof a){const r="apply_item_ops"===t?li(e.p_ops):"save_item_with_revision"===t?"string"==typeof e.p_item_id?[e.p_item_id]:[]:(Array.isArray(e.p_items)?e.p_items.map(e=>e?.id):[]).filter(e=>"string"==typeof e&&""!==e);ui(oi(n,a,r))}}}catch(e){console.error("[embed-on-save] not queued:",e instanceof Error?e.message:e)}return a}}var mi,fi,_i,hi=P({"src/core/embed-on-save.ts"(){Qa=["title","body","summary","tags","type"],Ya=5,Ka=3,Za=100,Xa=500,ei=1e3,ti=5e3,ni=Symbol.for("atoms.embedOnSave.config"),ri=new Set(["save_item_with_revision","bulk_save_items_with_revisions","apply_item_ops"])}});function gi(e=(e,t)=>fetch(e,t)){return async(t,n)=>{const r="string"==typeof t?t:t instanceof URL?t.href:null,a=null==n?.body||"string"==typeof n.body,i=null!==r&&a&&function(e,t){let n;try{n=new URL(e).pathname}catch{return!1}if(!n.startsWith("/rest/v1/"))return!1;if("GET"===t||"HEAD"===t)return!0;const r=/^\/rest\/v1\/rpc\/([^/]+)$/.exec(n);return"POST"===t&&null!==r&&mi.has(r[1])&&!fi.has(r[1])}(r,(n?.method??"GET").toUpperCase());let s;try{s=await e(t,n)}catch(r){if(!i||!function(e){for(let t=e,n=0;null!=t&&n<4;t=t.cause,n++){if("object"!=typeof t)return"string"==typeof t&&_i.test(t);const{name:e,code:n,message:r}=t;if("AbortError"===e||"TimeoutError"===e)return!1;if(_i.test(`${String(n??"")} ${String(r??"")}`))return!0}return!1}(r))throw r;return e(t,n)}return 502===s.status&&i?(await(s.body?.cancel().catch(()=>{})),e(t,n)):s}}var yi,wi,vi,bi,ki,ji,xi=P({"src/core/gateway-retry-reads.ts"(){mi=new Set(["baseline_item_state","baseline_state","baseline_state_page","baseline_variables_state","cc_normative_changed","cc_project_is_controlled","changes_since","fresh_typing_notes","is_active_project_member_for_field","is_platform_admin","item_state_at","item_trash_info","mcp_count_items","mcp_count_recent_changes","mcp_field_value_counts","mcp_op_answers","mcp_resolve_policy","mcp_variable_reference_counts","model_design_get","model_designs_list","mue_value_at","needs_attention_test_states","next_item_id","order_key_valid","order_keys_initial","project_function_mode","project_item_domain_tags","project_state_at","release_report_stored","restore_baseline_preview_counts","rollout_state","tag_key","tcm_requirements_for_test_cases","tcm_rerun_list","variables_at","verification_accepted_failures","verification_document_closures","verification_notrun_points","verification_readiness"]),fi=new Set(["mcp_resolve_policy"]),_i=/ECONNRESET|UND_ERR_SOCKET|connection reset|connection closed before message completed|other side closed|socket hang up|invalid response (?:was received )?from the upstream|invalid response from upstream/i}});function Si(e){const t=yi[e];return[...t.top,...t.other]}async function $i(e,t,n){const r=function(e){const t=Si(e);return bi.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))}function Ai(e){return function(e){return"automotive"===(e.industry??"automotive")&&!e.holdsAnalysisOutsideAutomotive}(e)?e.hazardGoalItemsOn&&e.multiuserSavingOn?null:ji:ki}var Ii,qi,Mi,Oi,Ei,zi,Ri,Ti,Ci,Pi,Di=P({"src/core/analysis-industry.ts"(){yi={automotive:{top:["iso26262","design"],other:[]},medical:{top:["iso14971","tir57","process"],other:["software","use"]},general:{top:[],other:[]}},wi={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"},vi={automotive:"Automotive (ISO 26262)",medical:"Medical device (ISO 14971)",general:"Standard"},bi=Object.keys(wi),ki="Hazard and Safety goal items are for ISO 26262 (automotive) projects. In a medical device project hazards are rows of the ISO 14971 risk analysis.",ji="rollout_switched:hazard_goal_items"}});function Ni(e,t){switch(t){case"left":return{x:e.x,y:e.y+e.h/2};case"right":return{x:e.x+e.w,y:e.y+e.h/2};case"top":return{x:e.x+e.w/2,y:e.y};case"bottom":return{x:e.x+e.w/2,y:e.y+e.h};default:return{x:e.x+e.w/2,y:e.y+e.h/2}}}function Hi(e,t,n,r,a){const i="left"===r||"right"===r?"y":"x",s=e=>{const n=t.find(t=>t.id===e);return n?"y"===i?n.y+n.h/2:n.x+n.w/2:0},o=s(n);return e.filter(e=>e.from===n&&e.fromPort===r||e.to===n&&e.toPort===r).map(e=>{const t=s(e.from===n&&e.fromPort===r?e.to:e.from);return{a:e,k:e.fromPort===e.toPort?2*o-t:t}}).sort((e,t)=>e.k-t.k||e.a.id.localeCompare(t.a.id)).map(e=>e.a)}function Fi(e,t,n,r){const a=Ni(e,t),i=r.length;if(i<=1)return a;const s=r.findIndex(e=>e.id===n);if(s<0)return a;const o="left"===t||"right"===t?e.h:e.w,l=Math.min(Ii,(o-16)/(i-1)),c=s*l-(i-1)*l/2;return"left"===t||"right"===t?{x:a.x,y:a.y+c}:{x:a.x+c,y:a.y}}function Li(e,t,n){const r=t.x,a=t.y,i=n.x,s=n.y,o=e.bendOffset||0;let l,c,d=0,u=(r+i)/2,p=(a+s)/2-8,m=!1;if(e.curve){let t,n;if("right"===e.fromPort&&"left"===e.toPort||"left"===e.fromPort&&"right"===e.toPort){const e=i-r;t={x:r+.5*e,y:a},n={x:i-.5*e,y:s}}else if("bottom"===e.fromPort&&"top"===e.toPort||"top"===e.fromPort&&"bottom"===e.toPort){const l=Math.max(20,Math.abs(s-a)/2)+o,c=Pi(e.fromPort),d=Pi(e.toPort);t={x:r,y:a+c.y*l},n={x:i,y:s+d.y*l}}else{const l=Math.max(30,Math.hypot(i-r,s-a)/2)+o,c=Pi(e.fromPort),d=Pi(e.toPort);t={x:r+c.x*l,y:a+c.y*l},n={x:i+d.x*l,y:s+d.y*l}}l=`M ${r} ${a} C ${t.x} ${t.y}, ${n.x} ${n.y}, ${i} ${s}`,d=Math.atan2(s-n.y,i-n.x),u=(r+3*t.x+3*n.x+i)/8,p=(a+3*t.y+3*n.y+s)/8,c=[];for(let e=0;e<=24;e++){const o=e/24,l=1-o;c.push({x:l*l*l*r+3*l*l*o*t.x+3*l*o*o*n.x+o*o*o*i,y:l*l*l*a+3*l*l*o*t.y+3*l*o*o*n.y+o*o*o*s})}}else if(e.ortho){let f=r,_=a;switch(e.fromPort){case"right":f=r+qi;break;case"left":f=r-qi;break;case"bottom":_=a+qi;break;case"top":_=a-qi}const h="left"===e.fromPort||"right"===e.fromPort,g="left"===e.toPort||"right"===e.toPort;if(h&&g){const e=(r+i)/2+o;l=`M ${r} ${a} L ${f} ${a} L ${e} ${a} L ${e} ${s} L ${i} ${s}`,c=[t,{x:f,y:a},{x:e,y:a},{x:e,y:s},n],u=e,p=(a+s)/2,m=!1}else if(h||g)if(h){const e=f+o;l=`M ${r} ${a} L ${e} ${a} L ${e} ${s} L ${i} ${s}`,c=[t,{x:e,y:a},{x:e,y:s},n],u=e,p=(a+s)/2,m=!1}else{const e=_+o;l=`M ${r} ${a} L ${r} ${e} L ${i} ${e} L ${i} ${s}`,c=[t,{x:r,y:e},{x:i,y:e},n],u=(r+i)/2,p=e,m=!0}else{const e=(a+s)/2+o;l=`M ${r} ${a} L ${r} ${_} L ${r} ${e} L ${i} ${e} L ${i} ${s}`,c=[t,{x:r,y:_},{x:r,y:e},{x:i,y:e},n],u=(r+i)/2,p=e,m=!0}switch(e.toPort){case"left":default:d=0;break;case"right":d=Math.PI;break;case"top":d=Math.PI/2;break;case"bottom":d=-Math.PI/2}}else l=`M ${r} ${a} L ${i} ${s}`,c=[t,n],d=Math.atan2(s-a,i-r);return{path:l,points:c,endAngle:d,startX:r,startY:a,endX:i,endY:s,bendX:u,bendY:p,bendIsVertical:m}}function Ui(e,t,n=1){const r=Mi+Oi*(Math.max(1,n)-1),a=(e,t)=>({x:e+Mi,y:t+4,anchor:"start"}),i=(e,t)=>({x:e,y:t-r,anchor:"middle"});let s;if(t.ortho)s=e.bendIsVertical?Math.abs(e.endX-e.startX)<Ei?a(Math.max(e.startX,e.endX),e.bendY):i(e.bendX,e.bendY):Math.abs(e.endY-e.startY)<Ei?i(e.bendX,Math.min(e.startY,e.endY)):a(e.bendX,e.bendY);else if(t.curve&&t.fromPort&&t.fromPort===t.toPort){const n=e.bendX,r=e.bendY;s="right"===t.fromPort?a(n,r):"left"===t.fromPort?{x:n-Mi,y:r+4,anchor:"end"}:"bottom"===t.fromPort?{x:n,y:r+Mi+10,anchor:"middle"}:i(n,r)}else{const n=(e.startX+e.endX)/2,o=(e.startY+e.endY)/2,l=e.endX-e.startX,c=(e.endY-e.startY)*(t.curve?2:1);s=Math.abs(l)<=.25*Math.abs(c)?a(n,o):Math.abs(c)<=.25*Math.abs(l)?i(n,o):l*c<0?{x:n-4,y:o-r,anchor:"end"}:{x:n+4,y:o-r,anchor:"start"}}const o=t.labelOffset;return o&&Number.isFinite(o.x)&&Number.isFinite(o.y)&&(s={...s,x:s.x+o.x,y:s.y+o.y}),s}function Wi(e){const t=[];return e.label&&t.push({text:e.label,charPx:Ri}),e.techDetail&&t.push({text:e.techDetail,charPx:Ti}),e.links&&e.links.length>0&&t.push({text:`[${e.links.length}]`,charPx:Ci}),t}function Vi(e,t){return Wi(e).map((e,n)=>{const r=[...e.text].length*e.charPx;return{x:"start"===t.anchor?t.x:"end"===t.anchor?t.x-r:t.x-r/2,y:t.y+Oi*n-9,w:r,h:12}})}function Bi(e,t){const n=new Map(e.map(e=>[e.id,e])),r=[];for(const a of t){const i=n.get(a.from),s=n.get(a.to);if(!i||!s)continue;const o=Li(a,Fi(i,a.fromPort,a.id,Hi(t,e,i.id,a.fromPort)),Fi(s,a.toPort,a.id,Hi(t,e,s.id,a.toPort))),l=Wi(a).length;r.push({id:a.id,from:a.from,to:a.to,path:o,labels:l?Vi(a,Ui(o,a,l)):[]})}return r}function Gi(e,t,n=0){return e.x<t.x+t.w+n&&t.x<e.x+e.w+n&&e.y<t.y+t.h+n&&t.y<e.y+e.h+n}function Ji(e,t,n,r){const a=(t.x-e.x)*(r.y-n.y)-(t.y-e.y)*(r.x-n.x);if(Math.abs(a)<1e-9)return!1;const i=((n.x-e.x)*(r.y-n.y)-(n.y-e.y)*(r.x-n.x))/a,s=((n.x-e.x)*(t.y-e.y)-(n.y-e.y)*(t.x-e.x))/a;return i>=0&&i<=1&&s>=0&&s<=1}function Qi(e,t,n){if(n.w<=0||n.h<=0)return!1;const r=e=>e.x>n.x&&e.x<n.x+n.w&&e.y>n.y&&e.y<n.y+n.h;if(r(e)||r(t))return!0;const a=[{x:n.x,y:n.y},{x:n.x+n.w,y:n.y},{x:n.x+n.w,y:n.y+n.h},{x:n.x,y:n.y+n.h}];for(let n=0;n<4;n++)if(Ji(e,t,a[n],a[(n+1)%4]))return!0;return!1}function Yi(e,t){if(Ki(t,e))return 0;const n=t=>Math.hypot(Math.max(e.x-t.x,0,t.x-(e.x+e.w)),Math.max(e.y-t.y,0,t.y-(e.y+e.h)));let r=1/0;for(let e=0;e+1<t.length;e++){const a=t[e],i=t[e+1],s=Math.max(1,Math.ceil(Math.hypot(i.x-a.x,i.y-a.y)/6));for(let e=0;e<=s;e++)r=Math.min(r,n({x:a.x+(i.x-a.x)*e/s,y:a.y+(i.y-a.y)*e/s}))}return r}function Ki(e,t){for(let n=0;n+1<e.length;n++){const r=e[n],a=e[n+1];if(!(Math.max(r.x,a.x)<t.x||Math.min(r.x,a.x)>t.x+t.w||Math.max(r.y,a.y)<t.y||Math.min(r.y,a.y)>t.y+t.h)&&Qi(r,a,t))return!0}return!1}var Zi,Xi,es,ts,ns=P({"src/core/model-design-geometry.ts"(){Ii=40,qi=30,Mi=8,Oi=12,Ei=40,zi=14,Ri=5.8,Ti=5.5,Ci=5,Pi=e=>"left"===e?{x:-1,y:0}:"right"===e?{x:1,y:0}:"top"===e?{x:0,y:-1}:"bottom"===e?{x:0,y:1}:{x:0,y:0}}});function rs(e){const t=[...e].length*Xi.boxLabelCharPx+Xi.boxLabelInset;return Math.min(Xi.maxBoxWidth,Math.max(Xi.minBoxWidth,ts(t)))}function as(e,t){const n=[...e.boxes.entries()].map(([e,t])=>({id:e,...t})),r=Bi(n,t.map((t,n)=>({id:`e${n}`,from:t.from,to:t.to,...e.routes[n],curve:e.routes[n].curve??!1})));let a=0;for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){const n=r[e].path.points,i=r[t].path.points,s=[r[e].from,r[e].to].some(e=>e===r[t].from||e===r[t].to);for(let e=s?1:0;e+1<n.length-(s?1:0);e++)for(let t=s?1:0;t+1<i.length-(s?1:0);t++)Ji(n[e],n[e+1],i[t],i[t+1])&&a++}const i=[...n.flatMap(e=>[e.x,e.x+e.w]),...r.flatMap(e=>e.path.points.map(e=>e.x))],s=[...n.flatMap(e=>[e.y,e.y+e.h]),...r.flatMap(e=>e.path.points.map(e=>e.y))];return{crossings:a,area:i.length?(Math.max(...i)-Math.min(...i))*(Math.max(...s)-Math.min(...s)):0}}function is(e,t,n,r){const a="TD"===e||"TB"===e||"BT"===e,i=t.length,s=new Map(t.map((e,t)=>[e.id,t])),o=new Array(i).fill(0);{const e=new Array(i).fill(0),t=new Array(i).fill(0);n.forEach((n,r)=>{s.has(n.from)&&s.has(n.to)&&n.from!==n.to&&(e[s.get(n.from)]++,t[s.get(n.to)]++)});for(let n=0;n<i;n++)o[n]=Math.max(e[n],t[n])}const l=(e,t)=>Math.max(t,ts(16+14*Math.max(0,e-1))),c=t.map((e,t)=>a?Math.max(rs(e.label),l(o[t],0)):rs(e.label)),d=t.map((e,t)=>a?Xi.boxHeight:l(o[t],Xi.boxHeight)),u=e=>a?d[e]:c[e],p=e=>a?c[e]:d[e],m=t.map(e=>e.group),f=n.map(e=>s.has(e.from)&&s.has(e.to)&&e.from!==e.to),_=Array.from({length:i},()=>[]);n.forEach((e,t)=>{f[t]&&_[s.get(e.from)].push(t)});const h=new Set;{const e=new Array(i).fill(0);for(let t=0;t<i;t++){if(e[t])continue;const r=[{v:t,i:0}];for(e[t]=1;r.length;){const t=r[r.length-1],a=_[t.v];if(t.i>=a.length){e[t.v]=2,r.pop();continue}const i=a[t.i++],o=s.get(n[i].to);1===e[o]?h.add(i):0===e[o]&&(e[o]=1,r.push({v:o,i:0}))}}}const g=Array.from({length:i},()=>new Set),y=Array.from({length:i},()=>new Set);n.forEach((e,t)=>{if(!f[t])return;let n=s.get(e.from),r=s.get(e.to);h.has(t)&&([n,r]=[r,n]),g[n].add(r),y[r].add(n)});const w=new Array(i).fill(0);{const e=y.map(e=>e.size),n=[];for(let t=0;t<i;t++)0===e[t]&&n.push(t);const r=[];for(;n.length;){const t=n.shift();r.push(t);for(const r of g[t])w[r]=Math.max(w[r],w[t]+1),0===--e[r]&&n.push(r)}for(let e=0;e<4;e++){let e=!1;for(const n of[...r].reverse()){const r=[...y[n]],a=[...g[n]],i=r.length?Math.max(...r.map(e=>w[e]+1)):-1/0,s=a.length?Math.min(...a.map(e=>w[e]-1)):1/0;let o=w[n];if(0===r.length&&a.length>0){const e=null===m[n]?[]:t.map((e,t)=>t).filter(e=>e!==n&&m[e]===m[n]);o=e.length?Math.min(s,Math.max(...e.map(e=>w[e]))):s}else a.length>r.length&&Number.isFinite(s)?o=s:r.length>a.length&&Number.isFinite(i)&&(o=i);o=Math.max(Number.isFinite(i)?i:0,Math.min(Number.isFinite(s)?s:o,o)),o!==w[n]&&o>=0&&(w[n]=o,e=!0)}if(!e)break}const a=i?Math.min(...w):0;for(let e=0;e<i;e++)w[e]=w[e]-a}const v=i?Math.max(...w)+1:0;if(!a)for(let e=0;e<v;e++){const t=[...Array(i).keys()].filter(t=>w[t]===e);if(t.length<2)continue;const n=t.map(e=>c[e]),r=Math.max(...n);if(r-Math.min(...n)<=120)for(const e of t)c[e]=r}const b=[],k=[];for(let e=0;e<i;e++)k.push(b.length),b.push({kind:"node",layer:w[e],node:t[e].id,group:m[e],across:p(e),along:u(e),pos:0,order:0});const j=new Map,x=n.reduce((e,t,n)=>f[n]?e+Math.max(0,Math.abs(w[s.get(t.to)]-w[s.get(t.from)])-1):e,0)>4e3;n.forEach((e,t)=>{if(!f[t])return;let n=s.get(e.from),a=s.get(e.to);h.has(t)&&([n,a]=[a,n]);const i=[k[n]],o=null!==m[n]&&m[n]===m[a]?m[n]:null;if(!x&&!h.has(t)&&!r.has(t))for(let e=w[n]+1;e<w[a];e++)i.push(b.length),b.push({kind:"dummy",layer:e,edge:t,group:o,across:0,along:0,pos:0,order:0});i.push(k[a]),j.set(t,i)});const S=[...new Set(m.filter(e=>null!==e))],$=new Map;for(const e of S){const t=b.filter(t=>t.group===e).map(e=>e.layer);$.set(e,[Math.min(...t),Math.max(...t)])}const A=new Map;for(const e of S){const[t,n]=$.get(e);for(let r=t;r<=n;r++){const t=b.length;b.push({kind:"lb",layer:r,group:e,across:0,along:0,pos:0,order:0});const n=b.length;b.push({kind:"rb",layer:r,group:e,across:0,along:0,pos:0,order:0}),A.set(`${e}\0${r}`,{lb:t,rb:n})}}const I=b.map(()=>[]),q=b.map(()=>[]),M=(e,t,n)=>{q[e].push([t,n]),I[t].push([e,n])},O=new Map;for(const[e,t]of j){if(t.length<3)continue;const n=O.get(t[0]);(void 0===n||j.get(n).length<t.length)&&O.set(t[0],e)}for(const[e,t]of j)if(!(t.length<2))for(let r=0;r+1<t.length;r++){const a=b[t[r]],i=b[t[r+1]];if(i.layer!==a.layer+1)continue;const o="node"===a.kind&&"node"===i.kind&&1===_[s.get(a.node)].length&&1===n.filter((e,t)=>f[t]&&e.to===i.node).length,l="dummy"===a.kind&&"dummy"===i.kind?8:"dummy"===i.kind?O.get(t[0])===e?16:2:"dummy"===a.kind?.5:o?4:1;M(t[r],t[r+1],l)}for(const e of S){const[t,n]=$.get(e);for(let r=t;r<n;r++){const t=A.get(`${e}\0${r}`),n=A.get(`${e}\0${r+1}`);M(t.lb,n.lb,4),M(t.rb,n.rb,4)}}const E=Array.from({length:v},()=>[]);{const e=new Set,t=[];for(let n=0;n<b.length;n++){if(e.has(n))continue;const r=[n];for(e.add(n);r.length;){const n=r.shift();t.push(n);for(const[t]of[...q[n],...I[n]])e.has(t)||(e.add(t),r.push(t))}}for(const e of t)E[b[e].layer].push(e)}const z=()=>E.forEach(e=>e.forEach((e,t)=>{b[e].order=t}));let R=new Map(S.map((e,t)=>[e,t]));const T=(e,t)=>{const n=E[e],r=[],a=new Map;for(const e of n){const n=b[e];if(null===n.group){r.push({g:null,members:[e],key:t(e)});continue}let i=a.get(n.group);i||(i={g:n.group,members:[],key:0},a.set(n.group,i),r.push(i)),"node"!==n.kind&&"dummy"!==n.kind||i.members.push(e)}for(const n of r){if(null===n.g)continue;n.members.sort((e,n)=>t(e)-t(n)||b[e].order-b[n].order);const r=n.members.map(t),a=A.get(`${n.g}\0${e}`);n.key=r.length?r.reduce((e,t)=>e+t,0)/r.length:(t(a.lb)+t(a.rb))/2}r.sort((e,t)=>e.key-t.key);const i=r.map((e,t)=>null!==e.g?t:-1).filter(e=>e>=0),s=i.map(e=>r[e]).sort((e,t)=>R.get(e.g)-R.get(t.g));i.forEach((e,t)=>{r[e]=s[t]});const o=[];for(const t of r){if(null===t.g){o.push(t.members[0]);continue}const n=A.get(`${t.g}\0${e}`);o.push(n.lb,...t.members,n.rb)}E[e]=o,o.forEach((e,t)=>{b[e].order=t})},C=e=>{const t=[];for(const n of E[e])for(const[e,r]of q[n])t.push([b[n].order,b[e].order,r]);let n=0;for(let e=0;e<t.length;e++)for(let r=e+1;r<t.length;r++){const a=t[e],i=t[r];(a[0]-i[0])*(a[1]-i[1])<0&&(n+=a[2]*i[2])}return n},P=()=>{let e=0;for(let t=0;t+1<v;t++)e+=C(t);return e},D=()=>{const e=new Map;for(const t of S){const n=b.filter(e=>e.group===t&&("node"===e.kind||"dummy"===e.kind)).map(e=>e.order/Math.max(1,E[e.layer].length));e.set(t,n.reduce((e,t)=>e+t,0)/Math.max(1,n.length))}R=new Map([...S].sort((t,n)=>e.get(t)-e.get(n)).map((e,t)=>[e,t]))};z();for(let e=0;e<v;e++)T(e,e=>b[e].order);const N=b.length>1500;let H=E.map(e=>[...e]),F=P();const L=N?4:24;for(let e=0;e<L&&F>0;e++){const t=e%2==0,n=t?[...Array(v).keys()].slice(1):[...Array(v).keys()].reverse().slice(1);for(const e of n){const n=t?I:q;T(e,e=>{const t=n[e];if(!t.length)return b[e].order;const r=t.reduce((e,[,t])=>e+t,0);return t.reduce((e,[t,n])=>e+b[t].order*n,0)/r})}D();const r=P();r<F&&(F=r,H=E.map(e=>[...e]))}H.forEach((e,t)=>{E[t]=e}),z();const U=a?{start:Xi.groupPadding,end:Xi.groupPadding}:{start:Xi.groupLabelSpace,end:Xi.groupPadding},W=(e,t)=>{const n=e.across/2+t.across/2;return"lb"===e.kind&&t.group===e.group&&"rb"!==t.kind?n+U.start:"rb"===t.kind&&e.group===t.group&&"lb"!==e.kind?n+U.end:"lb"===e.kind&&"rb"===t.kind?0:"rb"===e.kind||"lb"===t.kind?n+Xi.groupGap:"dummy"===e.kind||"dummy"===t.kind?n+Xi.laneGap:n+Xi.nodeGap};for(const e of E){let t=0;e.forEach((n,r)=>{r>0&&(t+=W(b[e[r-1]],b[n])),b[n].pos=t})}const V=(e,t,n)=>{const r=[];let a=0;e.forEach((t,n)=>{n>0&&(a+=W(b[e[n-1]],b[t])),r.push(a)});const i=[];e.forEach((e,a)=>{for(i.push({sum:(t[a]-r[a])*n[a],w:n[a],count:1});i.length>1;){const e=i[i.length-1],t=i[i.length-2];if(t.sum/t.w<=e.sum/e.w)break;i.splice(i.length-2,2,{sum:t.sum+e.sum,w:t.w+e.w,count:t.count+e.count})}});let s=0;for(const t of i)for(let n=0;n<t.count;n++,s++)b[e[s]].pos=t.sum/t.w+r[s]};(e=>{for(let t=0;t<e;t++){const e=t%2==0?[...E.keys()]:[...E.keys()].reverse();for(const t of e){const e=E[t],n=[],r=[];for(const t of e){const e=[...I[t],...q[t]],a=e.reduce((e,[,t])=>e+t,0);0!==a?(n.push(e.reduce((e,[t,n])=>e+b[t].pos*n,0)/a),r.push(a)):(n.push(b[t].pos),r.push(.05))}V(e,n,r)}}})(N?4:16);const B=new Map;b.forEach((e,t)=>{null!==e.group&&B.set(e.group,[...B.get(e.group)??[],t])});const G=e=>{const[t,n]=$.get(e);let r=1/0,a=-1/0;for(let i=t;i<=n;i++){const t=A.get(`${e}\0${i}`);r=Math.min(r,b[t.lb].pos),a=Math.max(a,b[t.rb].pos)}for(let i=t;i<=n;i++){const t=A.get(`${e}\0${i}`);b[t.lb].pos=r,b[t.rb].pos=a}};for(const e of S)G(e);for(let e=0;e<500;e++){let e=!1;for(const t of E)for(let n=1;n<t.length;n++){const r=b[t[n-1]],a=b[t[n]],i=r.pos+W(r,a)-a.pos;if(!(i<=1e-6))if(e=!0,null===a.group||r.group===a.group||"lb"!==a.kind&&"node"!==a.kind&&"dummy"!==a.kind)a.pos+=i,"rb"===a.kind&&G(a.group);else for(const e of B.get(a.group))b[e].pos+=i}if(!e)break}const J=new Array(v).fill(0);for(const e of b)"node"===e.kind&&(J[e.layer]=Math.max(J[e.layer],e.along));const Q=new Array(v).fill(a?Xi.layerGapTD:Xi.layerGapLR),Y=n.map(e=>{return(t=e.label)?[...t].length*Xi.arrowLabelCharPx+8:0;var t});n.forEach((e,t)=>{if(!f[t]||h.has(t)||!Y[t])return;const n=w[s.get(e.from)],r=w[s.get(e.to)],i=Math.min(n,r),o=Math.max(n,r),l=a?40:Y[t]+40;Q[i]=Math.max(Q[i],l),o-1!==i&&(Q[o-1]=Math.max(Q[o-1],l))});for(const e of S){const[t,n]=$.get(e),r=a?Xi.groupLabelSpace:Xi.groupPadding;t>0&&(Q[t-1]=Q[t-1]+r+(a?Xi.groupGap:0)),n+1<v&&(Q[n]=Q[n]+Xi.groupPadding+(a?Xi.groupGap:0))}const K=new Array(v).fill(0);for(let e=1;e<v;e++)K[e]=ts(K[e-1]+J[e-1]+Q[e-1]);const Z=Math.min(0,...b.map(e=>e.pos-e.across/2)),X=new Map,ee=e=>K[w[e]]+(J[w[e]]-u(e))/2;for(let e=0;e<i;e++){const n=b[k[e]],r=es(ee(e)),i=es(n.pos-n.across/2-Z);X.set(t[e].id,a?{x:i,y:r,w:c[e],h:d[e]}:{x:r,y:i,w:c[e],h:d[e]})}const te=v?K[v-1]+J[v-1]:0;if("RL"===e||"BT"===e)for(const t of X.values())"RL"===e?t.x=es(te-t.x-t.w):t.y=es(te-t.y-t.h);const ne=new Map;for(const e of S){const n=t.filter(t=>t.group===e).map(e=>X.get(e.id));if(!n.length)continue;const r=Xi.groupLabelSpace,a=Math.min(...n.map(e=>e.x))-Xi.groupPadding,i=Math.min(...n.map(e=>e.y))-r,s=Math.max(...n.map(e=>e.x+e.w))+Xi.groupPadding,o=Math.max(...n.map(e=>e.y+e.h))+Xi.groupPadding;ne.set(e,{x:a,y:i,w:s-a,h:o-i})}const re=function(e,t,n,r,a,i,s){const o="TD"===e||"TB"===e||"BT"===e,l="LR"===e?{from:"right",to:"left"}:"RL"===e?{from:"left",to:"right"}:"BT"===e?{from:"top",to:"bottom"}:{from:"bottom",to:"top"};new Map(t.map((e,t)=>[e.id,t]));const c=[...i.entries()],d=(e,t,n,r,a)=>{const i=Li({...e,curve:e.curve??!1},Ni(t,e.fromPort),Ni(n,e.toPort)).points;return!u(i,r,a)},u=(e,t,n)=>{let r=1/0,a=1/0,i=-1/0,s=-1/0;for(const t of e)t.x<r&&(r=t.x),t.x>i&&(i=t.x),t.y<a&&(a=t.y),t.y>s&&(s=t.y);for(const[o,l]of c)if(!t.has(o)&&!(l.x-n>i||l.x+l.w+n<r||l.y-n>s||l.y+l.h+n<a)&&Ki(e,{x:l.x-n,y:l.y-n,w:l.w+2*n,h:l.h+2*n}))return!0;return!1},p=new Array(n.length),m=[],f=(e,t,n,r)=>{p[e]=t,a.has(e)||m.push(Li({...t,curve:t.curve??!1},Ni(n,t.fromPort),Ni(r,t.toPort)).points)},_=[],h=e=>{let t=0;for(const n of[...m,..._])for(let r=0;r+1<e.length;r++)for(let a=0;a+1<n.length;a++)Ji(e[r],e[r+1],n[a],n[a+1])&&t++;return t};function g(e,t,n,r=!0){const a=o?["right","left"]:["bottom","top"];let i=null;for(const r of a){const a=Ni(e,r),l=Ni(t,r),u=Math.max(30,Math.hypot(l.x-a.x,l.y-a.y)/2),p="right"===r||"bottom"===r?1:-1,f=o?Math.min(a.y,l.y):Math.min(a.x,l.x),g=o?Math.max(a.y,l.y):Math.max(a.x,l.x),y=e=>o?e.x:e.y,w=p>0?Math.max(y(a),y(l)):Math.min(y(a),y(l)),v=[...c.map(([,e])=>e),...s.values()].filter(e=>o?e.y<g&&e.y+e.h>f:e.x<g&&e.x+e.w>f).map(e=>o?p>0?e.x+e.w:e.x:p>0?e.y+e.h:e.y),b=[...m,..._].flatMap(e=>e.filter(e=>o?e.y>f&&e.y<g:e.x>f&&e.x<g).map(y)),k=Math.max(0,...[...v,...b].map(e=>(e-w)*p)),j=Math.max(24,(k+Xi.loopClearance)/.75);let x=-1;for(let s=j;s<=j+1200&&!(x>=0&&s>x+300);s+=10){const o={fromPort:r,toPort:r,ortho:!1,curve:!0,bendOffset:s-u};if(!d(o,e,t,n,12))continue;x<0&&(x=s);const c=Li({...o,curve:!0},a,l).points,p=h(c),m=1e3*p+s;if((!i||m<i.cost)&&(i={r:o,cost:m,cross:p,pts:c}),0===p)break}}return i?r?(_.push(i.pts),i.r):{r:i.r,cross:i.cross,pts:i.pts}:null}const y=e=>{const t=i.get(n[e].from),r=i.get(n[e].to);return t&&r?Math.hypot(t.x-r.x,t.y-r.y):0};[...n.keys()].sort((e,t)=>Number(a.has(e))-Number(a.has(t))||(a.has(e)?y(e)-y(t):0)||e-t).forEach(t=>{const s=n[t],c={fromPort:l.from,toPort:l.to,ortho:!1,curve:!1,bendOffset:0};if(!r[t])return void(p[t]=c);const u=i.get(s.from),m=i.get(s.to),y=new Set([s.from,s.to]);if(a.has(t)){const e={fromPort:l.to,toPort:l.from,ortho:!1,curve:!0,bendOffset:0},n=Li({...e,curve:!0},Ni(u,e.fromPort),Ni(m,e.toPort)).points,r=d(e,u,m,y,8),a=r?h(n):1/0,i=r&&0===a?null:g(u,m,y,!1);return r&&(!i||a<=i.cross)?(_.push(n),void f(t,e,u,m)):i?(_.push(i.pts),void f(t,i.r,u,m)):void f(t,e,u,m)}const w={...c,curve:!0};if(d(w,u,m,y,8))return void f(t,w,u,m);if(d(c,u,m,y,8))return void f(t,c,u,m);const v=n.length>300?null:g(u,m,y,!1);if(v&&0===v.cross)return _.push(v.pts),void f(t,v.r,u,m);const b=Ni(u,l.from),k=Ni(m,l.to),j=o?Xi.layerGapTD:Xi.layerGapLR,x="RL"===e||"BT"===e?-1:1,S=(o?b.y:b.x)+x*(Xi.exitBuffer+10),$=(o?k.y:k.x)-x*j/2,A=Math.max(1,Math.round(Math.abs($-S)/Xi.grid)),I=[];for(let e=0;e<=A;e++)I.push($-x*(Math.abs($-S)*e)/A);const q=I.length>60?I.filter((e,t)=>t%Math.ceil(I.length/60)===0):I;for(const e of q){const n={...c,ortho:!0,bendOffset:o?e-(b.y+k.y)/2:e-(b.x+k.x)/2};if(d(n,u,m,y,6))return void f(t,n,u,m)}f(t,g(u,m,y)??w,u,m)});const w=[...i.entries()].map(([e,t])=>({id:e,...t})),v=()=>n.map((e,t)=>({id:`e${t}`,from:e.from,to:e.to,...p[t],curve:p[t].curve??!1,label:e.label})).filter((e,t)=>r[t]),b=(e,t)=>u(e,new Set([t.from,t.to]),4),k=n.length>300?1:3;for(let e=0;e<k;e++){const e=new Map(Bi(w,v()).map(e=>[e.id,e]));let t=!1;if(n.forEach((n,r)=>{const a=e.get(`e${r}`);if(!a||!b(a.path.points,n))return;const s=p[r],l={x:a.path.startX,y:a.path.startY},c={x:a.path.endX,y:a.path.endY},d=e=>!b(Li({...e,curve:e.curve??!1},l,c).points,n);if(s.fromPort!==s.toPort){const e=o?[l.y,c.y]:[l.x,c.x],a=Math.min(...e)+Xi.exitBuffer+10,u=Math.max(...e)-20,m=Math.sign(o?c.y-l.y:c.x-l.x)||1,f=(e[0]+e[1])/2,_=[{...s,ortho:!1,curve:!0,bendOffset:0},{...s,ortho:!1,curve:!1,bendOffset:0}];for(let e=m>0?u:a;m>0?e>=a:e<=u;e-=m*Xi.grid)_.push({...s,ortho:!0,curve:!1,bendOffset:e-f});const h=_.find(d);if(h)return p[r]=h,void(t=!0);const y=g(i.get(n.from),i.get(n.to),new Set([n.from,n.to]));return void(y&&(p[r]=y,t=!0))}for(let e=(s.bendOffset||0)+20;e<=1200;e+=20){const n={...s,bendOffset:e};if(d(n))return p[r]=n,void(t=!0)}}),!t)break}return p}(e,t,n,f,h,X,ne);return{boxes:X,groups:ne,routes:re}}var ss,os,ls,cs,ds,us,ps,ms,fs,_s,hs,gs,ys,ws,vs,bs,ks,js,xs,Ss,$s,As,Is,qs=P({"src/core/model-design-layout.ts"(){ns(),Zi=Object.freeze({grid:20,boxHeight:60,minBoxWidth:160,maxBoxWidth:480,boxLabelCharPx:7.2,boxLabelInset:28,arrowLabelCharPx:5.8,nodeGap:40,laneGap:24,groupGap:30,groupPadding:20,groupLabelSpace:40,layerGapLR:80,layerGapTD:60,loopClearance:30,loopSpacing:14,exitBuffer:30}),Xi=Zi,es=e=>Math.round(e/Xi.grid)*Xi.grid,ts=e=>Math.ceil(e/Xi.grid)*Xi.grid}});function Ms(e){let t=0,n=e.length;for(;t<n&&ms.includes(e[t]);)t++;for(;n>t&&ms.includes(e[n-1]);)n--;return e.slice(t,n)}function Os(e){const t=ds(Ms(e??""));return t<1||t>os.maxName?"a model design needs a name of 1 to 200 characters":null}function Es(e){return ds(e??"")>os.maxDescription?"a description holds at most 5000 characters":null}function zs(e){const t=new Set;for(const n of e.boxes)for(const e of n.links??[])t.add(e);for(const n of e.arrows)for(const e of n.links??[])t.add(e);return[...t]}function Rs(e,t=""){let n="";for(const r of e??""){const e=_s.find(([e])=>e===r);e?n+=e[1]:t.includes(r)?n+=`#${r.codePointAt(0)};`:n+=r}return n}function Ts(e){return e.replace(/#(quot|lt|gt|amp|\d{1,7});/g,(e,t)=>{if(t in hs)return hs[t];const n=Number(t);if(n<=0||n>1114111||n>=55296&&n<=57343)throw new gs(`#${t}; names no character that can be stored`);return String.fromCodePoint(n)})}function Cs(e){const t=e.replace(/[^A-Za-z0-9_]/g,"_"),n=/^[A-Za-z_]/.test(t)?t:`n_${t}`;return(ys.has(n.toLowerCase())?`n_${n}`:n).slice(0,os.maxIdLength)}function Ps(e){const t=new Map,n=new Set,r=e=>{if(t.has(e))return;const r=Cs(e);let a=r;for(let e=1;n.has(a);e++){const t=`_${e}`;a=r.slice(0,os.maxIdLength-t.length)+t}n.add(a),t.set(e,a)};for(const t of e.groups)r(t.id);for(const t of e.boxes)r(t.id);return t}function Ds(e,t){const n=e.x+e.w/2,r=e.y+e.h/2;return n>=t.x&&n<=t.x+t.w&&r>=t.y&&r<=t.y+t.h}function Ns(e){const t=new Map;for(const n of e.boxes){let r=null;for(const t of e.groups)Ds(n,t)&&(!r||t.w*t.h<r.w*r.h)&&(r=t);r&&t.set(n.id,r.id)}return t}function Hs(e,t,n){const r=(t??[]).filter(e=>"string"==typeof e&&ls.test(e));return 0===r.length?null:`%% links ${e}: ${r.map(e=>{const t=n?n(e):void 0;return void 0===t?e:null===t?`${e} (not in this project)`:`${e} "${Rs(t,",")}"`}).join(", ")}`}function Fs(e,t={},n){const r=[];r.push("%% ATOMS model design"+(t.displayId?` ${t.displayId}`:"")),null!=t.name&&r.push(`%% name: ${Rs(t.name)}`),t.description&&r.push(`%% description: ${Rs(t.description)}`),r.push("flowchart LR");const a=Ps(e),i=e=>a.get(e)??Cs(e),s=Ns(e),o=(e,t)=>{r.push(`${t}${i(e.id)}["${Rs(e.label??"")}"]`);const a=Hs(i(e.id),e.links??[],n);a&&r.push(`${t}${a}`)};for(const t of e.groups){r.push(` subgraph ${i(t.id)}["${Rs(t.label??"")}"]`);for(const n of e.boxes)s.get(n.id)===t.id&&o(n," ");r.push(" end")}for(const t of e.boxes)s.has(t.id)||o(t," ");return e.arrows.forEach((e,t)=>{const a=e.label?`|"${Rs(e.label)}"|`:"";r.push(` ${i(e.from)} ${function(e){return e.bi?e.dashed?"<-.->":"<--\x3e":e.dashed?"-.->":"--\x3e"}(e)}${a} ${i(e.to)}`);const s=Hs(`edge ${t+1}`,e.links??[],n);s&&r.push(` ${s}`)}),r.join("\n")+"\n"}var Ls,Us,Ws,Vs,Bs,Gs,Js=P({"src/core/model-design.ts"(){qs(),ns(),ss=Object.freeze({boxes:[],arrows:[],groups:[]}),os=Object.freeze({maxElements:1e3,maxLabel:200,maxTechDetail:1e3,maxLinksPerElement:20,maxIdLength:64,maxName:200,maxDescription:5e3,maxCanvasBytes:2097152}),ls=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,cs=Object.freeze({maxChars:4194304,maxElements:1e3}),ds=e=>{let t=0;for(const n of e)t++;return t},us=Object.freeze({boxWidth:160,boxHeight:60,gapX:80,gapY:40,originX:40,originY:40,belowExistingGap:80,groupPadding:20,groupLabelSpace:40}),ps=/^MD-\d{3,}$/i,ms=" \t\r\n\f\v",fs=e=>"number"==typeof e&&Number.isFinite(e),_s=[["#","#35;"],['"',"#quot;"],["<","#lt;"],[">","#gt;"],["&","#amp;"],["|","#124;"],["`","#96;"],["\n","#10;"],["\r","#13;"],["\t","#9;"],["[","#91;"],["]","#93;"]],hs={quot:'"',lt:"<",gt:">",amp:"&"},gs=class extends Error{},ys=new Set(["end","subgraph","graph","flowchart","direction","style","classdef","class","click","linkstyle"]),ws="[A-Za-z_][A-Za-z0-9_]{0,63}",vs='"([^"]*)"',bs=new RegExp(`^(${ws})(?:\\[${vs}\\])?$`),ks=new RegExp(`^subgraph\\s+(${ws})(?:\\[${vs}\\])?$`),js=new RegExp(`^(${ws})(?:\\[${vs}\\])?\\s*(<-\\.->|<--\x3e|-\\.->|--\x3e)(?:\\|(?:${vs}|([^|"]*))\\|)?\\s*(${ws})(?:\\[${vs}\\])?$`),xs=new RegExp(`^%%\\s*links\\s+(edge\\s+(\\d{1,4})|${ws})\\s*:\\s*(.*)$`),Ss=/^([A-Za-z][A-Za-z0-9._-]{0,63})(?:\s+(?:"[^"]*"|\([^)]*\)))?$/,$s=e=>ds(e)>os.maxLabel,As=e=>20*Math.ceil(e/20),Is="Add me as editor"}});function Qs(){return{status:"error",code:"rollout_switched",key:"model_designs",retryable:!1,message:Us,next_steps:["Ask an org admin to turn on Model design for this project if it should have model designs","Do not retry this call"]}}function Ys(e){const t=String(e?.message??e??""),n=String(e?.details??""),r=e=>t.slice(t.indexOf(e)+e.length).trim();if(t.includes("rollout_switched:model_designs"))return Qs();if(t.includes("model_design_stale:")){let e={};try{e=JSON.parse(n)}catch{e={}}return{status:"error",code:"stale_version",retryable:!0,message:`Not saved: ${r("model_design_stale:")}.`,..."number"==typeof e.version?{current_version:e.version}:{},next_steps:["Read the design again with atoms_get_model_design","Apply your change to that version's Mermaid, then call atoms_update_model_design with its version as expected_version"]}}if(t.includes("model_design_not_editor:")){const e=/add yourself as an editor/i.test(t),n=/Ask (.+?) for edit access\.?\s*$/.exec(t)?.[1]?.trim(),i="Only the design's creator and the editors named on it can change it";return{status:"error",code:"not_an_editor",retryable:!1,message:`Not saved: ${r("model_design_not_editor:")}`,next_steps:e?[`Open the design in the ATOMS app and press ${Is} in its Details panel, then call again`,`${i}; as an org admin you can add yourself`,"There is no tool that names editors"]:[...n?[(a=n,`Ask ${a} for edit access.`)]:[],`${i}${n?"; editors are named in the ATOMS app (the design's Details panel), and there is no tool for it":""}`,...n?[]:["Editors are named in the ATOMS app (the design's Details panel) by its creator or an org admin; there is no tool for it"],"Do not retry this call"]}}var a;if(t.includes("model_design_viewer:"))return{status:"error",code:"viewer_read_only",retryable:!1,message:"Not saved: an org viewer can view model designs but not change them.",next_steps:["Ask an org admin to make you an editor of the organization","Do not retry this call"]};if(t.includes("model_design_in_trash:"))return{status:"error",code:"model_design_in_trash",retryable:!1,message:`Not saved: ${r("model_design_in_trash:")}.`,next_steps:["Ask its creator or an org admin to restore it from the project Trash in the app","Do not retry this call"]};if(t.includes("model_design_not_found:"))return{status:"error",code:"not_found",retryable:!1,message:r("model_design_not_found:"),next_steps:["Use atoms_list_model_designs to see this project's model designs and their MD ids"]};const i=/model_design_(name|description|canvas|version|source|agent_client):\s*(.*)$/.exec(t);return i?{status:"error",code:"validation_error",retryable:!1,message:`Validation error: ${i[2]}`,next_steps:["Fix the named value and call again"]}:null}async function Ks(e,t){const{data:n,error:r}=await e.from("projects").select("id, deleted_at").eq("id",t).maybeSingle();if(r)throw r;return!!n?.deleted_at}async function Zs(e,t,n){return function(e){if(e.error)throw e.error;return e.data}(await e.rpc(t,n))}async function Xs(e,t,n){const r=new Map;for(let a=0;a<n.length;a+=Ws){const i=n.slice(a,a+Ws),{data:s,error:o}=await e.from("items").select("id, title, type").eq("project_id",t).is("deleted_at",null).in("id",i);if(o)throw o;for(const e of s??[])r.set(e.id,e)}return r}async function eo(e,t,n){const r=await Zs(e,"model_design_get",{p_project_id:t,p_design:n});return!0!==r?.enabled?null:r.design??null}async function to(e,t,n,r){const a=function(e){const t=cs;if("string"!=typeof e)return{ok:!1,error:"mermaid must be text"};if((e=function(e){const t=e.length-e.trimStart().length,n=e.trim();return n.startsWith("<user_content>")&&n.endsWith("</user_content>")?" ".repeat(t)+n.slice(14,n.length-15):e}(e)).length>t.maxChars)return{ok:!1,error:`the Mermaid text holds ${e.length} characters; at most ${t.maxChars} are accepted`};const n={direction:"LR",name:null,description:null,nodes:[],edges:[],groups:[]},r=new Map,a=new Set,i=new Map,s=new Map;let o=!1,l=null;const c=(e,t)=>({ok:!1,error:`line ${e}: ${t}`}),d=(e,i,s)=>{if(a.has(e))return`${e} names a subgraph, not a box`;if(ys.has(e.toLowerCase()))return`${e} is a Mermaid keyword and cannot name a box`;const o=void 0===i?void 0:Ts(i);if(void 0!==o&&$s(o))return`the label of ${e} holds more than 200 characters`;const l=r.get(e);if(l){if(void 0!==o){if(l.labelSet&&l.label!==o)return`${e} is declared twice with different labels`;l.label=o,l.labelSet=!0}if(s){if(l.group&&l.group!==s)return`${e} is in two subgraphs`;l.group=s}return null}if(r.size+n.edges.length+n.groups.length>=t.maxElements)return`more than ${t.maxElements} boxes, arrows and subgraphs`;const c={id:e,label:o??e,group:s,links:[],labelSet:void 0!==o};return r.set(e,c),null},u=e.split(/\r?\n/);for(let e=0;e<u.length;e++){const t=p(e+1,u[e].trim());if(t)return t}return function(){if(!o)return{ok:!1,error:'the diagram must start with "flowchart LR" (or TD, TB, RL, BT)'};if(l)return{ok:!1,error:`the subgraph ${l} has no "end"`};for(const[e,t]of i){const n=r.get(e);if(!n)return{ok:!1,error:`%% links names ${e}, which is no box of this diagram`};n.links=t}for(const[e,t]of s){const r=n.edges[e-1];if(!r)return{ok:!1,error:`%% links names edge ${e}, but the diagram has ${n.edges.length} arrows`};r.links=t}return n.nodes=[...r.values()].map(e=>({id:e.id,label:e.label,group:e.group,links:e.links})),{ok:!0,value:n}}();function p(e,u){try{return function(e,u){if(""===u)return null;if(u.startsWith("%%")){const t=/^%%\s*name:\s?(.*)$/.exec(u);if(t)return n.name=Ts(t[1]),null;const r=/^%%\s*description:\s?(.*)$/.exec(u);if(r)return n.description=Ts(r[1]),null;const a=xs.exec(u);if(a){const t=""===a[3].trim()?[]:a[3].split(",").map(e=>e.trim()),n=[];for(const r of t){const t=Ss.exec(r);if(!t)return c(e,`"${r.slice(0,80)}" is not a linked item; write the item id, optionally followed by its title in quotes`);n.includes(t[1])||n.push(t[1])}if(n.length>os.maxLinksPerElement)return c(e,"a box or arrow links at most 20 items");if(a[2]){const t=Number(a[2]);if(s.has(t))return c(e,`edge ${t} has a links line already; put all its linked items on one line`);s.set(t,n)}else{if(i.has(a[1]))return c(e,`${a[1]} has a links line already; put all its linked items on one line`);i.set(a[1],n)}return null}return null}if(!o){const t=/^(flowchart|graph)\s+(LR|RL|TB|TD|BT)\s*;?$/.exec(u);return t?(n.direction=t[2],o=!0,null):c(e,'the diagram must start with "flowchart LR" (or TD, TB, RL, BT)')}const p=u.replace(/;$/,"").trim(),m=ks.exec(p);if(m){if(l)return c(e,"subgraphs inside subgraphs are not supported");const i=m[1];if(a.has(i)||r.has(i))return c(e,`${i} is used twice`);if(r.size+n.edges.length+n.groups.length>=t.maxElements)return c(e,`more than ${t.maxElements} boxes, arrows and subgraphs`);const s=void 0===m[2]?i:Ts(m[2]);return $s(s)?c(e,`the label of ${i} holds more than 200 characters`):(a.add(i),n.groups.push({id:i,label:s}),l=i,null)}if("end"===p)return l?(l=null,null):c(e,'"end" without a subgraph');const f=js.exec(p);if(f){if(l)return c(e,'write arrows after the subgraph\'s "end", not inside it');const[,a,i,s,o,u,p,m]=f,_=d(a,i,null);if(_)return c(e,_);const h=d(p,m,null);if(h)return c(e,h);if(r.size+n.edges.length+n.groups.length>=t.maxElements)return c(e,`more than ${t.maxElements} boxes, arrows and subgraphs`);const g=Ts((o??u??"").trim());return $s(g)?c(e,"an arrow label holds more than 200 characters"):a===p?c(e,`the arrow from ${a} to itself is not supported`):(n.edges.push({from:a,to:p,label:g,dashed:s.includes("."),bi:s.startsWith("<"),links:[]}),null)}const _=bs.exec(p);if(_){const t=d(_[1],_[2],l);return t?c(e,t):null}return c(e,`"${p.slice(0,80)}" is not a model design line; write boxes as id["label"], arrows with --\x3e, -.->, <--\x3e or <-.-> (an optional |"label"| after the arrow), groups as subgraph id["label"] ... end, and links as %% links id: REQ-001`)}(e,u)}catch(t){if(t instanceof gs)return c(e,t.message);throw t}}}(n);if(!a.ok)return{ok:!1,error:Ls("mermaid_not_accepted",`Validation error: the Mermaid was not accepted: ${a.error}`,['Write a flowchart as atoms_get_model_design returns it: flowchart LR, boxes as id["label"], arrows --\x3e, -.->, <--\x3e or <-.-> with an optional |"label"|, subgraph id["label"] ... end, and %% links id: REQ-001',"Fix the named line and call again"])};const i=function(e,t=ss){const n=us,r="TB"===e.direction||"TD"===e.direction||"BT"===e.direction,a=Ps(t),i=new Map;for(const e of t.boxes)i.set(a.get(e.id),e);const s=new Map;for(const e of t.groups)s.set(a.get(e.id),e);const o=e.nodes.filter(e=>i.has(e.id)),l=e.nodes.filter(e=>!i.has(e.id)),c=new Set([...t.boxes.map(e=>e.id),...t.groups.map(e=>e.id),...t.arrows.map(e=>e.id)]),d=e=>{const t=e.slice(0,os.maxIdLength);let n=t;for(let e=1;c.has(n);e++){const r=`_${e}`;n=t.slice(0,os.maxIdLength-r.length)+r}return c.add(n),n},u=new Map;for(const e of o){const t=i.get(e.id);u.set(e.id,{...t,label:e.label,links:[...e.links]})}const p=t=>e.nodes.filter(e=>e.group===t).map(e=>e.id),m=e=>s.get(e),f=[...o.map(e=>{const t=i.get(e.id);return t.y+t.h}),...e.groups.map(e=>m(e.id)).filter(e=>!!e).map(e=>e.y+e.h)],_=[...o.map(e=>{const t=i.get(e.id);return t.x+t.w}),...e.groups.map(e=>m(e.id)).filter(e=>!!e).map(e=>e.x+e.w)],h=n.originX,g=n.originY;let y=r?0===_.length?h:As(Math.max(..._)+n.belowExistingGap):0===f.length?g:As(Math.max(...f)+n.belowExistingGap);const w=()=>r?{x:y,y:g}:{x:h,y:y},v=e=>{y=As((r?e.x+e.w:e.y+e.h)+n.gapY)},b=(e,t)=>{const r=e.map(e=>u.get(e)),a=Math.min(...r.map(e=>e.x))-(t?n.groupPadding:0),i=Math.min(...r.map(e=>e.y))-(t?n.groupLabelSpace:0);return{x:a,y:i,w:Math.max(...r.map(e=>e.x+e.w))+(t?n.groupPadding:0)-a,h:Math.max(...r.map(e=>e.y+e.h))+(t?n.groupPadding:0)-i}},k=e=>({x:e.x,y:e.y,w:n.boxWidth+2*n.groupPadding,h:n.boxHeight+n.groupLabelSpace+n.groupPadding}),j=new Map,x=(t,r,a,i)=>{const s=new Set(t),o=e.nodes.filter(e=>s.has(e.id)).map(e=>({id:e.id,label:e.label,group:i?e.group:null})),l=e.edges.map((e,t)=>({e:e,k:t})).filter(({e:e})=>s.has(e.from)&&s.has(e.to)),c=function(e,t,n){const r=is(e,t,n,new Set),a=new Set(r.routes.map((e,t)=>e.fromPort===e.toPort?t:-1).filter(e=>e>=0));if(0===a.size||n.length>300)return r;const i=is(e,t,n,a),s=as(r,n),o=as(i,n);return o.crossings<s.crossings||o.crossings===s.crossings&&o.area<=s.area?i:r}(e.direction,o,l.map(({e:e})=>({from:e.from,to:e.to,label:e.label}))),p=[...c.boxes.values(),...c.groups.values()],m=Math.min(...p.map(e=>e.x)),f=Math.min(...p.map(e=>e.y)),_=r.x+(a?n.groupPadding:0)-m,h=r.y+(a?n.groupLabelSpace:0)-f;for(const t of e.nodes){const e=c.boxes.get(t.id);e&&u.set(t.id,{id:d(t.id),x:e.x+_,y:e.y+h,w:e.w,h:e.h,label:t.label,links:[...t.links]})}l.forEach(({k:e},t)=>j.set(e,c.routes[t]));const g=new Map;for(const[e,t]of c.groups)g.set(e,{x:t.x+_,y:t.y+h,w:t.w,h:t.h});return g},S=new Set(o.map(e=>e.id));let $=e.groups.filter(e=>m(e.id)&&p(e.id).every(e=>S.has(e)));for(let e=!0;e;){e=!1;const t=$.map(e=>({...m(e.id),id:e.id})),n=Ns({boxes:o.map(e=>({...u.get(e.id),id:e.id})),groups:t}),r=$.filter(e=>{const t=o.filter(t=>n.get(t.id)===e.id).map(e=>e.id).sort(),r=p(e.id).sort();return t.length===r.length&&t.every((e,t)=>e===r[t])});r.length!==$.length&&($=r,e=!0)}const A=new Set($.map(e=>e.id)),I=new Map;for(const e of $){const t=m(e.id);I.set(e.id,{x:t.x,y:t.y,w:t.w,h:t.h})}const q=0===o.length&&l.length>0;if(q){const e=x(l.map(e=>e.id),w(),!1,!0);for(const[t,n]of e)I.set(t,n);const t=[b(l.map(e=>e.id),!1),...e.values()],n=Math.min(...t.map(e=>e.x)),r=Math.min(...t.map(e=>e.y));v({x:n,y:r,w:Math.max(...t.map(e=>e.x+e.w))-n,h:Math.max(...t.map(e=>e.y+e.h))-r})}for(const t of e.groups){if(A.has(t.id))continue;if(q&&I.has(t.id))continue;const e=p(t.id).filter(e=>!S.has(e)),n=p(t.id);if(0===n.length){const e=m(t.id);if(e){I.set(t.id,{x:e.x,y:e.y,w:e.w,h:e.h});continue}const n=k(w());I.set(t.id,n),v(n);continue}e.length>0&&(x(e,w(),!0,!1),e.length,n.length,v(b(e,!0))),I.set(t.id,b(n,!0))}const M=l.filter(e=>null===e.group).map(e=>e.id);M.length>0&&!q&&(x(M,w(),!1,!1),v(b(M,!1)));const O=()=>e.nodes.map(e=>({...u.get(e.id),id:e.id}));for(let t=0;t<=e.groups.length;t++){const t=e.groups.map(e=>({id:e.id,label:e.label,...I.get(e.id)})),n=Ns({boxes:O(),groups:t}),r=e.groups.find(t=>{const r=e.nodes.filter(e=>n.get(e.id)===t.id).map(e=>e.id).sort(),a=p(t.id).sort();return!(r.length===a.length&&r.every((e,t)=>e===a[t]))});if(!r)break;const a=e.groups.find(t=>t.id!==r.id&&e.nodes.some(e=>e.group===r.id&&n.get(e.id)===t.id))??r,i=p(a.id),s=w();if(0===i.length){const e=k(s);I.set(a.id,e),v(e);continue}const o=b(i,!0),l=s.x-o.x,c=s.y-o.y;for(const e of i){const t=u.get(e);u.set(e,{...t,x:t.x+l,y:t.y+c})}const d=b(i,!0);I.set(a.id,d),v(d)}const E=new Map(t.boxes.map((e,t)=>[e.id,t])),z=e.nodes.map(e=>u.get(e.id)).map((e,n)=>({b:e,k:E.get(e.id)??t.boxes.length+n})).sort((e,t)=>e.k-t.k).map(e=>e.b),R=new Map;for(const e of t.arrows){const t=`${e.from}\0${e.to}`;R.set(t,[...R.get(t)??[],e])}const T=e.edges.map((e,t)=>{const n=u.get(e.from).id,a=u.get(e.to).id,i=`${n}\0${a}`,s=R.get(i)?.shift();if(s)return{...s,label:e.label,dashed:e.dashed,bi:e.bi,links:[...e.links]};const o=j.get(t);return{id:d(`arrow_${n}_${a}`),from:n,to:a,fromPort:o?.fromPort??(r?"bottom":"right"),toPort:o?.toPort??(r?"top":"left"),label:e.label,techDetail:"",dashed:e.dashed,bi:e.bi,ortho:o?.ortho??!1,curve:o?.curve??!1,bendOffset:o?.bendOffset??0,links:[...e.links]}}),C=new Set(t.arrows.map(e=>e.id)),P=new Set(T.filter(e=>!C.has(e.id)).map(e=>e.id)),D=P.size?function(e,t,n){const r=Bi(e,t),a=new Map(r.map(e=>[e.id,e])),i=r.filter(e=>!n.has(e.id)).flatMap(e=>e.labels),s=(e,t)=>({x:e.x-t,y:e.y-t,w:e.w+2*t,h:e.h+2*t}),o=t=>t.every(t=>{const n=s(t,2);return!e.some(e=>Gi(n,e))&&!r.some(e=>Ki(e.path.points,n))&&!i.some(e=>Gi(n,e))}),l=(e,t)=>e.every(e=>{const n=s(e,zi);if(r.some(e=>e.id!==t&&Ki(e.path.points,n)))return!1;const i=a.get(t);if(!i)return!0;const o=Yi(e,i.path.points);return r.every(n=>n.id===t||Yi(e,n.path.points)>o)});return t.map(e=>{const t=a.get(e.id);if(!t||!n.has(e.id)||0===t.labels.length)return e;if(o(t.labels)&&l(t.labels,e.id))return i.push(...t.labels),e;const s=Math.min(...t.labels.map(e=>e.x)),c=Math.min(...t.labels.map(e=>e.y)),d=Math.max(...t.labels.map(e=>e.x+e.w)),u=Math.max(...t.labels.map(e=>e.y+e.h)),p=(s+d)/2,m=(c+u)/2,f=d-s,_=u-c,h=t.path.points,g=[0];for(let e=1;e<h.length;e++)g.push(g[e-1]+Math.hypot(h[e].x-h[e-1].x,h[e].y-h[e-1].y));const y=g[g.length-1],w=e=>{const t=y*e;let n=1;for(;n<g.length-1&&g[n]<t;)n++;const r=h[n-1],a=h[n],i=g[n]-g[n-1]||1,s=(t-g[n-1])/i;return{p:{x:r.x+(a.x-r.x)*s,y:r.y+(a.y-r.y)*s},dir:{x:(a.x-r.x)/i,y:(a.y-r.y)/i}}},v=[];for(const e of[0,14])for(const t of[.5,.4,.6,.3,.7,.2,.8,.12,.88]){const{p:n,dir:r}=w(t),a=-r.y,i=r.x,s=Math.abs(a)*(f/2)+Math.abs(i)*(_/2)+Mi+e;v.push({x:n.x+a*s,y:n.y+i*s},{x:n.x-a*s,y:n.y-i*s})}const b=v.map(e=>({dx:e.x-p,dy:e.y-m})).sort((e,t)=>Math.hypot(e.dx,e.dy)-Math.hypot(t.dx,t.dy)).map(e=>({...e,rs:t.labels.map(t=>({...t,x:t.x+e.dx,y:t.y+e.dy}))})),k=b.filter(t=>o(t.rs)&&l(t.rs,e.id)).map(t=>{return{m:t,score:(n=t.rs,Math.min(30,...n.map(t=>Math.min(...r.filter(t=>t.id!==e.id).map(e=>Yi(t,e.path.points)))))-.15*Math.hypot(t.dx,t.dy))};var n}).sort((e,t)=>t.score-e.score),j=k[0]?.m??(o(t.labels)?null:b.find(e=>o(e.rs)));if(!j)return i.push(...t.labels),e;i.push(...j.rs);const x=e.labelOffset??{x:0,y:0};return{...e,labelOffset:{x:Math.round(x.x+j.dx),y:Math.round(x.y+j.dy)}}})}(z,T,P):T;if(q){const e=Bi(z,D),t=e.flatMap(e=>[...e.path.points.map(e=>e.x),...e.labels.map(e=>e.x)]),r=e.flatMap(e=>[...e.path.points.map(e=>e.y),...e.labels.map(e=>e.y)]),a=t.length?Math.max(0,As(n.originX-Math.min(...t))):0,i=r.length?Math.max(0,As(n.originY-Math.min(...r))):0;if(a||i){for(const e of z)e.x+=a,e.y+=i;for(const[e,t]of I)I.set(e,{...t,x:t.x+a,y:t.y+i})}}return{boxes:z,arrows:D,groups:e.groups.map(e=>{const t=m(e.id),n=I.get(e.id);return t&&A.has(e.id)?{...t,label:e.label}:{id:t?t.id:d(e.id),x:n.x,y:n.y,w:n.w,h:n.h,label:e.label}})}}(a.value,r),s=function(e){const t=e;if(!t||"object"!=typeof t||Array.isArray(t))return"the canvas must be an object with boxes, arrows and groups";if(!Array.isArray(t.boxes)||!Array.isArray(t.arrows)||!Array.isArray(t.groups))return"the canvas must hold the arrays boxes, arrows and groups";if(t.boxes.length+t.arrows.length+t.groups.length>os.maxElements)return"a model design holds at most 1000 boxes, arrows and groups";if(function(e){const t=e=>(new TextEncoder).encode(e).length,n=e=>{if(null===e||"object"!=typeof e)return t(JSON.stringify(e)??"null");if(Array.isArray(e))return 2+e.reduce((e,t)=>e+n(t),0)+2*Math.max(0,e.length-1);const r=Object.entries(e).filter(([,e])=>void 0!==e);return 2+r.reduce((e,[r,a])=>e+t(JSON.stringify(r))+2+n(a),0)+2*Math.max(0,r.length-1)};return n(e)}(t)>os.maxCanvasBytes)return"a model design canvas holds at most 2 MB of JSON";const n=new Set,r=new Set;for(const e of["boxes","groups","arrows"])for(const a of t[e]){const t=a;if(!t||"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.id||t.id.length<1||t.id.length>os.maxIdLength)return"every box, arrow and group needs an id of 1 to 64 characters";if(n.has(t.id))return`the id ${t.id} is used twice`;if(n.add(t.id),"label"in t&&"string"!=typeof t.label)return"a label must be text";if(ds(String(t.label??""))>os.maxLabel)return"a label holds at most 200 characters";if("arrows"!==e&&!(fs(t.x)&&fs(t.y)&&fs(t.w)&&fs(t.h)))return"every box and group needs the numbers x, y, w and h";if("boxes"===e&&r.add(t.id),"arrows"===e){if("string"!=typeof t.from||"string"!=typeof t.to||!r.has(t.from)||!r.has(t.to))return`the arrow ${t.id} must join two boxes of this design`;if("techDetail"in t&&"string"!=typeof t.techDetail)return"a technical detail must be text";if(ds(String(t.techDetail??""))>os.maxTechDetail)return"a technical detail holds at most 1000 characters"}if("links"in t){if(!Array.isArray(t.links))return"links must be a list of item ids";if(t.links.length>os.maxLinksPerElement)return"a box or arrow links at most 20 items";for(const e of t.links)if("string"!=typeof e||!ls.test(e))return"a linked item id is an item id such as REQ-001"}}return null}(i);if(s)return{ok:!1,error:Ls("validation_error",`Validation error: ${s}`,["Make the diagram smaller and call again"])};const o=function(e,t=ss){const n=new Set(zs(t));return zs(e).filter(e=>!n.has(e))}(i,r);if(o.length>0){const n=await Xs(e,t,o),r=o.filter(e=>!n.has(e));if(r.length>0)return{ok:!1,error:Ls("unknown_item_ids",`Validation error: these linked ids are no live item of this project: ${r.join(", ")}`,["Use atoms_search or atoms_list_items to find the item ids","Remove or correct the %% links entries and call again"],!1,{unknown_item_ids:r})}}return{ok:!0,canvas:i,parsed:a.value}}function no(e,t){const n=new Set(t.boxes.map(e=>e.id)),r=new Set(t.arrows.map(e=>e.id));return{removed_boxes:e.boxes.filter(e=>!n.has(e.id)).length,removed_arrows:e.arrows.filter(e=>!r.has(e.id)).length}}function ro(e){return Y(`mcp_policy_block_destructive: ${e} is blocked by your org's MCP Access Policy (Block destructive ops)`)}function ao(e,t){return void 0!==t.name&&null!==e.name&&Ms(e.name)!==Ms(t.name)?Ls("validation_error","Validation error: the %% name: line of the Mermaid differs from the name param",["Send one name: change the %% name: line or the name param so they agree, or drop the line"]):void 0!==t.description&&null!==e.description&&e.description!==t.description?Ls("validation_error","Validation error: the %% description: line of the Mermaid differs from the description param",["Send one description: change the %% description: line or the description param so they agree, or drop the line"]):null}var io,so,oo,lo,co,uo=P({"src/core/model-design-tools.ts"(){Js(),ai(),re(),Ls=(e,t,n,r=!1,a={})=>({ok:!1,error:{status:"error",code:e,retryable:r,message:t,next_steps:n,...a}}),Us="Model design is not switched on for this project, so its model designs cannot be read or written here.",Ws=100,Vs=e=>({display_id:e.display_id,name:e.name,description:e.description,version:e.version,creator_name:e.created_by_name,updated_by_name:e.updated_by_name,updated_at:e.updated_at,editor_count:e.editor_count,you_can_edit:e.can_edit}),Gs={atoms_list_model_designs:"List the model designs (user-drawn architecture diagrams, MD-001 and on) of a project: each design's display_id, name, description, version, creator_name, updated_at, editor_count and whether you can edit it. Use atoms_get_model_design for one design's diagram.",atoms_get_model_design:"Read one model design by its MD id: its name, description, version, creator, and its diagram as Mermaid (model_mermaid), plus for each box and arrow that links ATOMS items the linked items with id and title. Box names and arrow labels are the user's own words; there are no built-in box types. "+(Bs='The Mermaid is a flowchart: a first line "flowchart LR" (or TD; the direction places new boxes and is not stored), boxes as id["label"], arrows as a --\x3e b (solid), a -.-> b (dashed), a <--\x3e b or a <-.-> b (both ways), each with an optional |"label"| after the arrow, groups as subgraph id["label"] ... end (not nested, arrows after the end), and per box or arrow one line %% links <box id>: REQ-001, TC-002 or %% links edge <n>: ... (n counts the arrows from 1) naming linked ATOMS items. The %% name: and %% description: lines set the name and description when you send no name or description param. Label text uses Mermaid codes: #quot; for ", #lt; #gt; #amp; #35; #124; #91; #93; #10; for a new line. Send the Mermaid as you read it, with or without its <user_content> markers. Anything else is refused with the line number. At most 1000 boxes, arrows and subgraphs together.'),atoms_create_model_design:`Create a model design in a project: a name (1 to 200 characters), an optional description (at most 5000 characters) and an optional Mermaid flowchart. You become its creator and its first editor. Every linked item id must be a live item of the project. ${Bs}`,atoms_update_model_design:`Change a model design you may edit (its creator, or an editor its creator or an org admin named; an org admin who is not named adds themselves in the ATOMS app first): any of name, description and mermaid, with expected_version set to the version you read. A box whose id matches one already there keeps its place; new boxes are placed automatically; boxes and arrows you leave out are removed, and the design's history (atoms_get_history with the MD id) records what changed but keeps no copy to restore them from, so the answer counts them (removed_boxes, removed_arrows); removing a box, arrow, group or linked item is refused under an org's Block destructive ops. If someone saved after your read the call is refused, naming who and when: read again and redo your change. Editors are named only in the ATOMS app. ${Bs}`}}});function po(e){const t=io.exec(e);return t?t[1]:null}function mo(e){return e.includes("function_is_item")}function fo(){return{status:"error",code:"function_is_item",retryable:!1,message:lo,next_steps:['Create a Function with atoms_create_item and type "function", or edit the Function item itself',"Do not retry this call"]}}function _o(){return{status:"error",code:"rollout_switched",key:"hazard_goal_items",retryable:!1,message:co,next_steps:["This project keeps its hazards and safety goals as text on its HARA rows for now (atoms_fill_row hazard and safety_goal)","Ask an org admin to turn on Hazard and Safety goal items for this project if it should have them","Do not retry this call"]}}function ho(e){return e.includes("hazard_goal_not_automotive")}function go(){return{status:"error",code:"hazard_goal_not_automotive",retryable:!1,message:`Validation error: ${ki} This change was not saved.`,next_steps:["In a medical device project, record the hazard as a row of the project's ISO 14971 risk analysis (atoms_create_analysis subtype risk_analysis, then atoms_propose_rows or atoms_fill_row)","A Standard project keeps no hazards or safety goals; Hazard and Safety goal items need the industry Automotive (ISO 26262), set on the project settings page","Do not retry this call"]}}function yo(e){return e.includes("hazard_goal_restore_refused")}var wo,vo,bo,ko,jo,xo,So,$o=P({"src/core/rollout-errors.ts"(){Di(),uo(),io=/rollout_switched:([a-z][a-z0-9_]{2,62})/,so="This project's saving rules just changed. Read the item again, then retry your change.",oo="Function items are not on for this project yet, so a Function item cannot be created here. This change was not saved.",lo="Validation error: this project's Functions are items now, so its function tag list no longer changes. This change was not saved.",co="Hazard and Safety goal items are not on for this project, so a Hazard, a Safety goal, or the Hazard or Safety goal of a hazardous event cannot be written here. This change was not saved."}});function Ao(e,t){const n=bo.indexOf(String(e??"")),r=bo.indexOf(String(t??""));return n<0||r<0?wo:ko[n][r]}function Io(e){return"Moderate"===e||"High"===e||"Very High"===e}var qo,Mo,Oo,Eo=P({"src/core/securityScheme.ts"(){wo="-",vo=["Very Low","Low","Moderate","High","Very High"],bo=["1","2","3","4","5"],ko=[["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"]],jo={"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"},xo=[{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"}],So={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 zo(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 Ro(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. ${Oo}`}function To(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 Co(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function Po(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 Do(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}=Po(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 No,Ho,Fo,Lo,Uo,Wo,Vo,Bo,Go,Jo,Qo,Yo,Ko,Zo,Xo,el,tl,nl,rl,al,il,sl,ol,ll,cl,dl,ul,pl,ml,fl,_l,hl,gl,yl,wl,vl,bl,kl,jl,xl,Sl,$l,Al,Il,ql,Ml,Ol,El,zl,Rl,Tl,Cl,Pl,Dl,Nl=P({"src/core/acceptance.ts"(){qo=["acceptance_state","accepted_by","accepted_at","acceptance_note","open_gaps_at_acceptance"],Mo=["prev_accepted_by","prev_accepted_at","accepted_snapshot_id","accepted_snapshot_name"],Oo="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 Hl(e){return t=e?.industry,"automotive"===t||"medical"===t||"general"===t?e.industry:null;var t}function Fl(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 Ll(e){return Ho[e]}function Ul(e){return Fo.some(t=>t.id===e)||function(e){return xo.some(t=>t.id===e)}(e)}function Wl(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:Uo,source:"fallback"}}function Vl(e){const t=(e??"").trim().toLowerCase();return"sub-system"===t?"subsystem":t}function Bl(e,t){const n=Wl(e),r=Wl(t);return Vl(n.level)===Vl(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 Gl(e,t,n){if("title"!==t&&("dfmea"!==e||"failure_mode"!==t)||n.length<=Vo)return null;const r="title"===t?"a row's title holds":"an FMEA row's failure mode is also its title, which holds";return`${t} is ${n.length} characters; ${r} at most ${Vo}. Shorten it to ${Vo} or fewer.`}function Jl(e){const t=(e.failure_mode??"").trim()||(e.hazard??"").trim()||"";if(t.length<=Vo)return t;const n=t.slice(0,Vo);return/[\uD800-\uDBFF]$/.test(n)?n.slice(0,-1):n}function Ql(e){return"hazard_iso14971"===e?sl:"security_tir57"===e?dl:[]}function Yl(e){return"security_tir57"===e?vo:ol}function Kl(e){return String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e)}function Zl(e){const t=e??{};return{intended_use:String(t.intended_use??"").trim(),foreseeable_misuse:Kl(t.foreseeable_misuse),safety_characteristics:Kl(t.safety_characteristics)}}function Xl(e,t=ol){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:ll.includes(a)?a:"",safety_rationale:String(n.software_safety_rationale??"").trim()}}function ec(e){return""!==Zl(e).intended_use}function tc(e,t){const n=Ql(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 nc(e,t,n){return`Invalid ${e} value ${JSON.stringify(t)}. Allowed: ${n.join(", ")}`}function rc(e){const t=e?.analysis_props;return null===t||"object"!=typeof t||Array.isArray(t)?"legacy":t.event_model===_l?"hazard_goal":"legacy"}function ac(e,t){return"hara_iso26262"===e&&"hazard_goal"===t?hl:pl[e]}function ic(e){return"risk_analysis"===e||"hazard_analysis"===e?["iso14971"]:"security_risk"===e?["tir57"]:No[gl[e]]}function sc(e){return Object.entries(Al[e]).map(([e,t])=>({key:e,label:t}))}function oc(e,t){const n=Al[e];return t.map(e=>({key:e,label:n[e]??e}))}function lc(e){return Object.entries(function(e){return"hara_iso26262"===e?kl:"dfmea_rpn"===e?Sl:"hazard_iso14971"===e?xl:"security_tir57"===e?So:$l}(e)).map(([e,t])=>({key:e,text:t}))}function cc(e){return"hazard_iso14971"===e?Xo:"security_tir57"===e?jo:null}function dc(e,t){const n=cc(e);return n?n[t]??null:null}function uc(e){return(e??"").trim().toLowerCase()}function pc(e,t){const n=uc(e);if(!n)return null;for(const e of t)if(uc(e)===n)return e;return null}function mc(e){const t=e?.severity||"",n=e?.exposure||"",r=e?.controllability||"";return t&&n&&r?"S0"===t||"E0"===n||"C0"===r?"QM":Jo[`${t}-${n}-${r}`]||Bo:Bo}function fc(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)?Bo:String(t*n*r)}function _c(e,t,n){const r=String(e??""),a=String(t??""),i=String(n??"");if(Yo.indexOf(r)<0||Yo.indexOf(a)<0||Yo.indexOf(i)<0)return Bo;const s=Ko[`${a}-${i}`];return s&&Zo[`${s}-${r}`]||Bo}function hc(e){return _c(e?.severity,e?.p1,e?.p2)}function gc(e){return _c(e?.residual_s,e?.residual_p1,e?.residual_p2)}function yc(e){return Ao(e?.severity,e?.exploitability)}function wc(e){return Ao(e?.residual_s,e?.residual_e)}function vc(e,t){return"hara_iso26262"===e?mc(t):"hazard_iso14971"===e?hc(t):"security_tir57"===e?yc(t):"fmea_software"===e?function(e){return fc({...e??{},occurrence:el})}(t):fc(t)}function bc(e,t,n,r){if(n)return!1;if("hara_iso26262"===e&&r?.cited&&r.satisfied)return!1;if("hara_iso26262"===e){const e=mc(t);return"C"===e||"D"===e}if("hazard_iso14971"===e)return"High"===hc(t);if("security_tir57"===e){const e=yc(t);return"High"===e||"Very High"===e}const a=parseInt(vc(e,t),10);return!Number.isNaN(a)&&a>=200}function kc(e,t,n,r,a){if(!e?.approved||!e.approved_at)return!1;const i=Date.parse(e.approved_at);if(Number.isNaN(i))return!1;const s=r?Date.parse(r):NaN;return!Number.isNaN(s)&&s>i||[...e.source_req?[e.source_req]:[],...t,...a??[]].some(e=>{const t=n(e),r=t?Date.parse(t):NaN;return!Number.isNaN(r)&&r>i})}function jc(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 xc(e){return"fmea_software"===e?{field:"occurrence",value:el}:null}function Sc(e){const t=xc(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 $c(e){return Ol[e]}function Ac(e){return"security_tir57"===e?xo:function(e){return"hazard_iso14971"===e||"fmea_process"===e||"fmea_software"===e||"fmea_use"===e}(e)?Fo:[]}function Ic(e){return Ac(e).map((e,t)=>({...e,precedence:t+1}))}function qc(e){return"hara_iso26262"===e||"hazard_iso14971"===e||"security_tir57"===e}function Mc(e,t){return`${e} is not a ${Ol[t].mitigating_requirement}: a mitigation target must be a requirement of req_type '${Lo}'. Create or convert one, then link it.`}function Oc(e){return`control_type applies to the medical schemes only (ISO 14971 clause 7); ${Ol[e].parent} links carry none, so omit it.`}function Ec(e){return"security_tir57"===e?`control_type is required for a security control link (FDA Appendix 1). Choose one of: ${xo.map(e=>`${e.id} (${e.label})`).join(", ")}.`:`control_type is required for a risk control link (ISO 14971 clause 7). Choose one of: ${Fo.map(e=>`${e.id} (${e.label})`).join(", ")}.`}function zc(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 Rc(e){const t=parseInt(e,10);return!Number.isNaN(t)&&t>=100}function Tc(e){return"hara_iso26262"===e?Rl:"hazard_iso14971"===e?Tl:"security_tir57"===e?Pl:Cl}function Cc(e){return!0===e.approved&&(e.approved=!1,e.approved_at=null,e.approved_by=null,e.approved_note="",!0)}function Pc(e,t,n,r){const a=[];for(const i of Tc(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}function Dc(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function Nc(e,t,n=uc){const r=new Set(t.map(n).filter(e=>e.length>0));return e.filter(e=>r.has(n(e)))}function Hc(e){const t=e.length>1;return`Function-flagged tag${t?"s":""} used as domain${t?"s":""}: ${e.join(", ")}. A function tag is not a domain tag: tag the item with a domain instead. A function is an item: create one with atoms_create_item type 'function' and name it on an analysis row by its id (atoms_create_analysis source_function_ids), in a project with Function items turned on; a project still on function tags turns one back into a domain in Taxonomy Management.`}var Fc,Lc,Uc,Wc=P({"src/core/analysis.ts"(){Eo(),Eo(),Nl(),No={hara:["iso26262","iso14971","tir57"],dfmea:["design","process","software","use"]},Ho={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"},Fo=[{id:"inherent",label:"Inherent design",abbr:"ID"},{id:"protective",label:"Protective measure",abbr:"PM"},{id:"information",label:"Information for safety",abbr:"IFS"}],Lo="safety",Uo="L1",Wo=8,Vo=500,Bo="-",Go=["prevention","detection","mitigation"],Jo={"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"},Ko={"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"},Zo={"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"},Xo={Low:"Acceptable",Medium:"Acceptable with justification",High:"Not acceptable"},el="10",tl={hara_iso26262:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea_rpn:{severity:Qo=["1","2","3","4","5","6","7","8","9","10"],occurrence:Qo,detection:Qo},hazard_iso14971:{severity:Yo=["1","2","3","4","5"],p1:Yo,p2:Yo,residual_s:Yo,residual_p1:Yo,residual_p2:Yo},fmea_process:{severity:Qo,occurrence:Qo,detection:Qo},fmea_software:{severity:Qo,detection:Qo},fmea_use:{severity:Qo,occurrence:Qo,detection:Qo},security_tir57:{severity:[...bo],exploitability:[...bo],residual_s:[...bo],residual_e:[...bo]}},nl={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"]},rl={security_tir57:{aliases:{threat_event:"failure_mode",vulnerability:"operating_scenario",impact:"effect",harm:"hazard",security_control:"safety_goal"},row:"security risk analysis row",kind:"security name"},hazard_iso14971:{aliases:{harm:"hazard",hazardous_situation:"effect",sequence_of_events:"operating_scenario"},row:"risk analysis row",kind:"ISO 14971 name"}},al=["intended_use","foreseeable_misuse","safety_characteristics"],il=["overall_residual_risk","overall_residual_rationale","software_safety_class","software_safety_rationale"],sl=[...al,...il],ol=["Low","Medium","High"],ll=["A","B","C"],cl=["threat_model_method","threat_model_rationale","environment_assumptions","attack_surfaces","related_documents","overall_residual_risk","overall_residual_rationale"],dl=[...cl,"lifecycle_sources"],ul={hara:"safety-goal",dfmea:"failure-mode"},pl={hara_iso26262:"SG",dfmea_rpn:"FM",hazard_iso14971:"RSK",fmea_process:"PF",fmea_software:"FM",fmea_use:"FM",security_tir57:"CYB"},ml={hara_iso26262:"HARA",dfmea_rpn:"DFMEA",hazard_iso14971:"RA",fmea_process:"PFMEA",fmea_software:"SFMEA",fmea_use:"UFMEA",security_tir57:"SEC"},fl=["HA"],Array.from(new Set([...Object.values(ml),...Object.values(pl),...fl])).sort(),_l="hazard_goal",hl="HE",gl={hara:"hara",dfmea:"dfmea",risk_analysis:"hara",fmea:"dfmea",hazard_analysis:"hara",security_risk:"hara"},yl=["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"],wl={hara:"iso26262",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"design",fmea:"process",security_risk:"tir57"},vl={hara:"iso14971",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"process",fmea:"process",security_risk:"tir57"},bl={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."},kl={...bl,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:Ro("The confirmation review of the HARA (ISO 26262)")},jl={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)."},xl={...bl,...jl,accept_analysis:Ro("The ISO 14971 clause 8 overall residual risk conclusion")},Sl={...bl,dfmea_s:kl.dfmea_s,o:kl.o,d:kl.d,rpn:kl.rpn,accept_analysis:Ro("The AIAG-VDA FMEA sign-off")},$l={...bl,dfmea_s:jl.dfmea_s,o:jl.o,o_sw:jl.o_sw,d:jl.d,rpn:jl.rpn,process_step:jl.process_step,controls:jl.controls,fn:jl.fn,risk_control:jl.risk_control,control_req:jl.control_req,verified_by:jl.verified_by,accept_analysis:Ro("The FMEA sign-off")},Al={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"}},Il=["asil","rpn","risk","p0"],ql=["approved","approved_at","approved_by","approved_note","field_source","link_roles","mitigation_types"],Ml=[...Il,...ql],Ol={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"}},El=(e,t,n)=>1===e?t:n,Rl=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft safety requirement",label:e=>`${e} ${El(e,"safety goal","safety goals")} unmitigated`,matches:e=>e.level!==Bo&&"QM"!==e.level&&!e.linked},{kind:"no_test",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${El(e,"safety goal","safety goals")} without a test on its ODD`,matches:e=>e.level!==Bo&&"QM"!==e.level&&e.linked&&!e.verified},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} ${El(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},zl={kind:"not_accepted",scope:"analysis",fix:"open_analysis",fixLabel:"Accept analysis",label:()=>"Analysis not accepted",matchesAnalysis:e=>e.hasRows&&!e.accepted}],Tl=[{kind:"no_control",scope:"row",fix:"link_requirement",fixLabel:"Draft risk control requirement",label:e=>`${e} ${El(e,"risk","risks")} above Low with no control`,matches:e=>e.level!==Bo&&"Low"!==e.level&&!e.linked},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${El(e,"control","controls")} not verified for effectiveness`,matches:e=>e.level!==Bo&&"Low"!==e.level&&e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual ${El(e,"risk","risks")} not assessed`,matches:e=>e.level!==Bo&&"Low"!==e.level&&e.linked&&e.residualLevel===Bo},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} risk ${El(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},zl],Cl=[{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=>Rc(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=>!Rc(e.level)&&null!==e.severity&&e.severity>=9&&!e.linked},zl],Pl=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft security control",label:e=>`${e} security ${El(e,"risk","risks")} above Low with no control`,matches:e=>Io(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===Bo},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${El(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===Bo},{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(Io(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 ${El(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},{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},zl],Dl=[{kind:"row_no_goal",fix:"open_row",fixLabel:"Set the safety goal",informational:!1,label:e=>`${e} hazardous ${El(e,"event","events")} rated ASIL A-D with no safety goal or safety requirement`},{kind:"goal_no_safety_req",fix:"link_requirement",fixLabel:"Draft safety requirement",informational:!1,label:e=>`${e} ${El(e,"safety goal","safety goals")} with no safety requirement`},{kind:"goal_no_test",fix:"open_row",fixLabel:"Verify its safety requirement",informational:!1,label:e=>`${e} ${El(e,"safety goal","safety goals")} with a hazardous event no verified safety requirement covers`},{kind:"hazard_uncited",fix:"open_item",fixLabel:"Open hazard",informational:!0,label:e=>`${e} ${El(e,"hazard","hazards")} cited by no hazardous event`},{kind:"goal_trashed",fix:"open_row",fixLabel:"Open row",informational:!0,label:e=>`${e} hazardous ${El(e,"event cites","events cite")} a safety goal in Trash`}]}});async function Vc(e,t,n,r){const a=await async function(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)}(e,t),i=r.includes(n)||a.includes(n)?n:pc(n,r)??pc(n,a);return{spelling:i,registered:null!==i&&r.includes(i),carried:a.filter(e=>null!==pc(e,[n]))}}async function Bc(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 Gc(e){return`Domain "${e}" registered. You can now tag items with domains=["${e}"].`}function Jc(e,t){return t?`"${e}" is already a function tag of this project, and a function tag is not a domain tag. Choose another domain name. A function is an item: create one with atoms_create_item type 'function', in a project with Function items turned on.`:`Domain "${e}" already exists in this project.`}function Qc(e){return`Domain "${e}" already exists. Choose a different name.`}var Yc,Kc,Zc,Xc,ed=P({"src/core/domains.ts"(){Wc(),Fc="domain_not_function",Lc=class extends Error{code=Fc;names;unregistered;constructor(e,t=[]){super(`${Fc}: ${e.join(", ")}`),this.name="DomainNotFunctionError",this.names=[...e],this.unregistered=[...t]}},Uc="domain_rename_onto_function"}});function td(){return{status:"error",code:Kc,retryable:!0,message:Zc,next_steps:["Send the same call again in a moment","If it times out again, tell the user ATOMS is slow right now"]}}function nd(e,t){return"57014"===e||/statement timeout|request timeout|upstream request timeout/i.test(t)}var rd,ad,id,sd=P({"src/core/read-budget.ts"(){Yc=25e3,Kc="read_timed_out",Zc="ATOMS did not answer this read in time, so nothing was returned. The read changes nothing: asking again is safe.",Xc=class extends Error{code=Kc;constructor(e){super(`${Kc}: the read did not finish within ${e} ms`),this.name="ReadBudgetExceededError"}}}});function od(e,t=0,n=ad){const r=e.slice(t,t+n),a=t+r.length,i=a<e.length;return{rows:r,meta:{total_count:e.length,limit:n,offset:t,has_more:i,...i?{next_offset:a}:{}}}}function ld(e,t,n){const r=n+t<e;return{total_count:e,limit:t,offset:n,has_more:r,...r?{next_offset:n+t}:{}}}function cd(e,t=rd,n,r){if(id(e)<=t)return e;if("success"!==e.status)return e;if(r)return function(e,t,n){const r=e.data;if(!r||"object"!=typeof r||!Array.isArray(r[n]))return cd(e,t);const a=e=>Array.isArray(e)?e.map(e=>e&&"object"==typeof e&&!Array.isArray(e)?(({title:e,...t})=>t)(e):e):e,i=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,a(t)])),s=[],o={},l=()=>({...e,data:i,meta:{...e.meta??{},truncated:!0,truncation_message:`Response kept near ${t} characters: titles left out (they are the titles you sent, in the same order)${s.length>0?`; arrays cut: ${s.join(", ")}`:""}. Every created item is listed in '${n}'.`}});for(;;){const e=l();if(id(e)<=t)return e;let r,a=0;for(const[e,t]of Object.entries(i))if(e!==n&&Array.isArray(t)&&t.length>1){const n=JSON.stringify(t).length;n>a&&(r=e,a=n)}if(!r)return e;const c=i[r];o[r]??=c.length,i[r]=c.slice(0,Math.floor(c.length/2));const d=`${r} ${o[r]} to ${i[r].length}`,u=s.findIndex(e=>e.startsWith(`${r} `));u>=0?s[u]=d:s.push(d)}}(e,t,r);if(n){const r=function(e,t,n){const r=void 0===n.list?e.data:e.data?.[n.list];if(!Array.isArray(r)||r.length<2)return null;const a=e.meta??{},i=i=>{let s;if("none"===n.resume)s={next:""};else if(n.resume)s=n.resume(i);else{const e="number"==typeof a.offset?a.offset:0;s={meta:{next_offset:e+i},next:`offset=${e+i}`}}const o=r.slice(0,i),l=void 0===n.list?o:{...e.data,[n.list]:o,...s.data},c=s.next?`Call again with ${s.next} to continue after the last returned row.`:"Lower 'limit' or narrow the query to see the rest.";return{...e,data:l,meta:{...a,returned:i,has_more:!0,...s.meta,truncated:!0,truncation_message:`Response truncated to stay under ${t} characters (${n.list??"items"} ${r.length} to ${i}). ${c}`}}};if(id(i(1))>t)return null;let s=1,o=r.length-1;for(;s<o;){const e=Math.ceil((s+o)/2);id(i(e))<=t?s=e:o=e-1}return i(s)}(e,t,n);if(r)return r;const a=function(e,t,n){const r=void 0===n.list?e.data:e.data?.[n.list];if(!Array.isArray(r)||0===r.length)return null;const a=void 0===n.list?{...e,data:r.slice(0,1)}:{...e,data:{...e.data,[n.list]:r.slice(0,1)}};if(id(a)<=t)return null;const i=r[0],s=i&&"object"==typeof i?i.id??i.item_id??i.name:void 0,o="string"==typeof s||"number"==typeof s?String(s):"1",l={...e.meta??{}},c=r.length>1||!0===l.has_more;let d="";if("none"===n.resume);else if(n.resume){const e=n.resume(1);Object.assign(l,e.meta??{}),d=e.next,l.has_more=c}else{const e="number"==typeof l.offset?l.offset:0,t="number"==typeof l.total_count?l.total_count:void 0,n=void 0!==t?e+1<t:c;l.has_more=n,n?(l.next_offset=e+1,d=`offset=${e+1}`):delete l.next_offset}const u={...l,returned:0,truncated:!0,truncation_message:`Response truncated to stay under ${t} characters: row ${o} alone is larger than that, so this answer shows it only as a text preview and returns no other row. `+(d&&l.has_more?`Call again with ${d} to continue after it. `:"")+`Read row ${o} on its own (atoms_get_item for an item) or narrow the request to see it whole.`};return dd(e,t,()=>u)}(e,t,n);if(a)return a}const a=n=>({...e.meta??{},truncated:!0,truncation_message:`Response truncated to stay under ${t} characters (${n}). Narrow the request to see more results.`});if(Array.isArray(e.data)){const n=e.data.length;let r=e.data,i={...e,data:r,meta:a(`${n} items cut`)};for(;id(i)>t&&r.length>1;)r=r.slice(0,Math.max(1,Math.floor(r.length/2))),i={...e,data:r,meta:a(`from ${n} to ${r.length} items`)};return id(i)<=t?i:dd(e,t,a)}if(e.data&&"object"==typeof e.data){const n={...e.data},r=[],i={},s=()=>({...e,data:n,meta:a(`arrays cut: ${r.join(", ")}`)});for(;;){if(id(s())<=t)return s();let e,a=0;for(const[t,r]of Object.entries(n))if(Array.isArray(r)&&r.length>1){const n=JSON.stringify(r).length;n>a&&(e=t,a=n)}if(!e)break;const o=n[e];i[e]??=o.length,n[e]=o.slice(0,Math.floor(o.length/2));const l=`${e} ${i[e]} to ${n[e].length}`,c=r.findIndex(t=>t.startsWith(`${e} `));c>=0?r[c]=l:r.push(l)}}return dd(e,t,a)}function dd(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-id({...e,data:{preview:""},meta:r})-200);for(;;){const n={...e,data:{preview:a.slice(0,i)},meta:r},s=id(n)-t;if(s<=0||0===i)return n;i=Math.max(0,i-s)}}var ud,pd,md,fd,_d,hd,gd,yd,wd,vd=P({"src/core/response-limit.ts"(){rd=25e3,ad=1e3,id=e=>JSON.stringify(e,null,2).length}});function bd(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)}function kd(){const e=_d.now(),t=null===gd?0:Math.max(0,e-gd);return hd=Math.min(md.capacity,hd+t/1e3*md.refillPerSecond),gd=e,!(hd<1||(hd-=1,0))}function jd(e,t){t.openUntil=_d.now()+fd.cooldownMs,t.probeAt=0,console.warn(`[atoms-mcp] busy breaker opened for project ${e}: ${t.failures} of ${t.calls} calls failed`)}function xd(e,t,n){const r=yd.get(e);if(n){if(!r)return;return void(t?jd(e,r):(yd.delete(e),console.warn(`[atoms-mcp] busy breaker closed for project ${e}`)))}if(r?.openUntil)return;if(!r&&!t)return;const a=_d.now();!r&&yd.size>=fd.maxScopes&&yd.delete(yd.keys().next().value);const i=r??{windowStart:a,calls:0,failures:0,openUntil:0,probeAt:0};a-i.windowStart>fd.windowMs&&Object.assign(i,{windowStart:a,calls:0,failures:0}),i.calls+=1,t&&(i.failures+=1),yd.set(e,i),i.calls>=fd.minCalls&&i.failures/i.calls>=fd.failureRatio&&jd(e,i)}async function Sd(e,t={}){const{scope:n,afterWrite:r=!1}=t,a=t.delays??(r?pd:ud),i=void 0===n||r?"pass":function(e){const t=yd.get(e);if(!t||0===t.openUntil)return"pass";const n=_d.now();return n<t.openUntil?"shed":n-t.openUntil>=fd.windowMs?(yd.delete(e),"pass"):0!==t.probeAt&&n-t.probeAt<fd.cooldownMs?"shed":(t.probeAt=n,"probe")}(n);if("shed"===i)return{data:null,error:{code:"55P03",message:"item_save_busy: this project is answering busy; retry in a few seconds"}};const s="probe"===i;let o;try{if(o=await e(),!s)for(const t of a){if(!bd(o.error))break;if(!r&&!kd())break;await _d.sleep(Math.round(t*_d.jitter())),o=await e()}}catch(e){throw void 0!==n&&xd(n,!0,s),e}return void 0!==n&&xd(n,function(e){const t=e.error;return bd(t)||"57014"===t?.code||/statement timeout/i.test(t?.message??"")||$d(e)}(o),s),o}function $d(e){return null!=e.error&&[0,502,503,504].includes(e.status??-1)}async function Ad(e){const t=await e();return $d(t)?(await _d.sleep(250),e()):t}var Id,qd,Md,Od,Ed,zd,Rd=P({"src/core/busy-retry.ts"(){ud=[200,400,800],pd=[100,200,400,800,1600],fd={windowMs:1e4,minCalls:5,failureRatio:.5,cooldownMs:5e3,maxScopes:1e3},_d={sleep:e=>new Promise(t=>setTimeout(t,e)),jitter:()=>Math.random(),now:()=>Date.now()},hd=(md={capacity:60,refillPerSecond:10}).capacity,gd=null,yd=new Map,wd=[250,1e3,3e3]}});function Td(){return{status:"error",message:Id,next_steps:["Do not retry this call","Tell the user that a person can restore it from Trash in ATOMS"],code:qd,retryable:!1}}function Cd(e,t){const n=function(e){const t=e.status??-1;return 0===t||t>=500||bd(e)||"57014"===e.code||/timeout|timed out|canceling statement/i.test(e.message)}(t),r=Md.find(([e])=>e.test(`${t.code??""} ${t.message}`));return{status:"error",message:`${e} is back from Trash, but its links could not be rebuilt (${t.message}). The links are still stored on the item, so none is lost, but some may not show until they are rebuilt.`,next_steps:n?[`Call atoms_restore_item again for ${e}: it is no longer in Trash, so the call only rebuilds its links, and it answers that ${e} is not deleted once they are rebuilt`,`If it keeps failing, tell the user that ${e} is back but some of its links may be missing, and to ask ATOMS support to rebuild them`]:[r?r[1](e):`Tell the user that ${e} is back but some of its links may be missing, and to ask ATOMS support to rebuild them`,`Until then ${e} may show without some of its links; ATOMS support can rebuild them`],code:"restore_links_not_rebuilt",retryable:n}}function Pd(e){const t=e.trashed_by,n=t?.name?.trim()||"Someone";return t?.agent?`${n}'s agent`:n}function Dd(e){return(e.deleted_at??"").slice(0,10)}function Nd(e,t){const n=`Restored ${e.item_id} from Trash. It was moved there by ${Pd(e)} on ${Dd(e)}`;return e.trashed_by?.user_id&&e.trashed_by.user_id!==t?`${n}; they have been notified.`:`${n}.`}var Hd,Fd,Ld,Ud,Wd,Vd,Bd,Gd,Jd,Qd=P({"src/core/restore-confirm.ts"(){Rd(),Id="This item has been in Trash for more than 7 days. Only a person can restore it, from Trash in ATOMS.",qd="item_trash_too_old",Md=[[/change_open_by_other/i,e=>`Tell the user that a change another person opened on an item linked to ${e} stops its links from being rebuilt: once that change is approved or withdrawn, call atoms_restore_item again for ${e}`],[/suspended/i,e=>`Tell the user that their account or organization is suspended, so the links of ${e} cannot be rebuilt: an organization admin or ATOMS support must lift the suspension first`],[/42501|permission denied|access denied/i,e=>`Tell the user that rebuilding the links of ${e} needs editor access to this project: an admin of the project can grant it, and then atoms_restore_item can be called again for ${e}`]],Od=["Show the user this message","Call atoms_restore_item again with confirm: true only after the user agrees"],Ed='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',zd="true only after the user has seen the needs_confirmation message and agreed to the restore"}}),Yd={};function Kd(e,t=Fd){if("string"!=typeof e)return"";const n=e.replace(Wd,"").replace(Vd,"");return n.length<=t?n:n.slice(0,t)+"..."}function Zd(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Xd(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function eu(e,t,n){return{total_count:e,limit:t,offset:n,has_more:n+t<e}}function tu(e,t,n={}){return{status:"error",message:e,next_steps:t,...n}}function nu(e,t){return tu(`${e} '${Kd(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function ru(e){return"account"===e?tu("Account suspended.",["Your ATOMS account is suspended, so ATOMS tools are unavailable","Contact ATOMS support or your organization admin to restore access"]):tu("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 au(e){const t=/\b(account|organization) suspended\b/i.exec(e);return t?t[1].toLowerCase():null}function iu(e){return tu(`${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 su(e,t=Ld){return tu(`Validation error: ${Kd(e,t)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function ou(){return tu("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 lu(){return tu("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 cu(e){return tu("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 du(e){return tu("Tool call rejected: this project's organization is outside the configured ATOMS_MCP_ORG_ID scope.",[`This MCP session is bound to organization ${e}`,"Use a project of that organization, or restart without ATOMS_MCP_ORG_ID to reach other organizations"])}function uu(e){return function(e){const t=e&&e>0?Math.ceil(e):Gt;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 pu(){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 mu(e){return tu(`Parse error: ${Kd(e,Ld)}`,["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 fu(e){return Yt(e)}function _u(){return tu("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 hu(){return tu("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 gu(){return tu("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 yu(){return tu("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 wu(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 vu(e,t={}){const n=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(a=n,Ut.some(e=>e.test(a)))return su(n,Ud);var a,i;if(e instanceof Wt)return su(n);if(Xt(n))return bu(e);if(jr(n))return xr();if(Ha(n))return Fa();if(po(n))return"function_items"===(i=po(n))?{status:"error",code:"rollout_switched",key:"function_items",retryable:!1,message:oo,next_steps:["This project's Functions are not items yet, so it keeps using its function tags for now","Ask an org admin to turn on Function items for this project if it should have Function items","Do not retry this call"]}:"hazard_goal_items"===i?_o():"model_designs"===i?Qs():{status:"error",code:"rollout_switched",retryable:!0,message:so,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(mo(n))return fo();if(ho(n))return go();if(yo(n))return{status:"error",code:"hazard_goal_restore_refused",retryable:!1,message:"Validation error: This Hazard or Safety goal item cannot be restored, because Hazard and Safety goal items are for ISO 26262 (automotive) projects. It stays in the trash.",next_steps:["Leave the item in the trash, or change the project's industry to Automotive (ISO 26262) on the project settings page and restore it then","Do not retry this call"]};if(/^auth_unavailable:/.test(n))return Mt();if(/^read_timed_out:/.test(n))return td();if(t.read&&nd(r,n))return td();if(/not authenticated/i.test(n))return ou();const s=function(e){const t=function(e){if(e instanceof Lc)return e.names;if(e&&"object"==typeof e&&e.code===Fc){const t=e.names;if(Array.isArray(t))return t.filter(e=>"string"==typeof e)}return null}(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.filter(e=>null!==pc(e,t)),i={code:Fc,domains:[...e]};return a.length>0&&(i.unregistered=[...a]),{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"}. A function is an item: create one with atoms_create_item type 'function', in a project with Function items turned on. Nothing was written.`,next_steps:["Create the Function with atoms_create_item type 'function' and name it by its id","Or choose a function name that is not already a domain"],details:i}}(t,Array.isArray(n)?n.filter(e=>"string"==typeof e):[])}(e);if(null!==s)return s;if(wu(e))return lu();if(Sr(n))return $r();const o=rn(n);if(null!==o)return o;if(function(e){return/item_trash_too_old/i.test(e)}(n))return Td();if(Ar(n))return Ir();const l=zr(n);if(null!==l)return l;const c=qr(n);if(null!==c)return c;const d=Mr(n);if(null!==d)return d;const u=Y(n);if(null!==u)return u;if("55P03"===r||function(e,t){return"40P01"===e||/deadlock detected/i.test(t)}(r,n)||function(e,t){return"55P03"===e||/canceling statement due to lock timeout|lock timeout/i.test(t)}(r,n)||/item_save_busy/i.test(n))return hu();if(Er(n))return{status:"error",message:"Nothing was saved: one save may name at most 50 items, counting both ends of each link, and this one names more.",next_steps:["Send the links in smaller batches (49 links from one item at a time, for example)","Do not send the same call again unchanged"],code:"too_many_items",retryable:!1};if(function(e,t){return!/^[0-9A-Z]{5}$/.test(e)&&function(e){return/(?:^|:\s*)invalid url\b|uri too long|request-uri too (?:long|large)|url too long|(?<![\w.-])414(?![\w-])/i.test(e)}(t)}(r,n))return{status:"error",message:"The request was too large to send to the database (its URL passed the length limit), so nothing was read or written. Waiting does not change it.",next_steps:["Do not retry this call unchanged: the same request is refused every time.","Narrow it (fewer ids, a smaller depth, or a filter), and report the tool and item to ATOMS support."],code:"request_too_large",retryable:!1};if(function(e,t){return!/^[0-9A-Z]{5}$/.test(e)&&/rate.?limit|too many requests|(?<![\w.-])429(?![\w-])/i.test(t)}(r,n))return uu();if(fu(n))return _u();if(/soft_deleted_item_write/i.test(n))return yu();if(/save_temporarily_unavailable/i.test(n))return gu();if("55P03"===r||nd(r,n)||/item_save_busy/i.test(n))return hu();const p=au(n);return p?ru(p):"42501"===r&&/org_project_field_admin_required/i.test(n)?tn("organization"):"42501"===r&&/project_field/i.test(n)?tn("project"):"P0002"===r&&/project_field/i.test(n)?tu("Project field not found.",["Refresh the field list and retry with an existing field name"]):"22023"===r&&/^project_field_values_incompatible:/i.test(n)?su(n.replace(/^project_field_values_incompatible:\s*/i,"")):["22023","23505","23514"].includes(r)&&/project_field/i.test(n)?su(n.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(n)?mu(n):ju(n)}function bu(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??"");if(!Xt(t)&&!en(t))return null;const n=t.indexOf(Bd);return tu((n>=0?t.slice(n+Bd.length):t).trim(),["Wait a moment, read the item again (atoms_get_item), then send your change again"],{code:"rollout_switched",retryable:!0})}function ku(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??""):"",r=Y(t);return["40001","PT409","55P03","57014"].includes(n)||null!==po(t)||null!==r&&"mcp_policy_block_destructive"!==r.code||/stale_item_write|soft_deleted_item_write|save_temporarily_unavailable|item_save_busy|lock timeout|statement timeout|request timeout|upstream request timeout|fetch failed|network error|connection (?:closed|reset|refused)/i.test(t)}function ju(e){if(/^auth_unavailable:/.test(e))return Mt();const t=rn(e);if(null!==t)return t;if(Kt(e))return uu();if(Zt(e))return lu();if(/^not authenticated/i.test(e))return ou();if(Sr(e))return $r();if(jr(e))return xr();if(Ha(e))return Fa();if(mo(e))return fo();if(ho(e))return go();if(yo(e))return{status:"error",code:"hazard_goal_restore_refused",retryable:!1,message:"Validation error: This Hazard or Safety goal item cannot be restored, because Hazard and Safety goal items are for ISO 26262 (automotive) projects. It stays in the trash.",next_steps:["Leave the item in the trash, or change the project's industry to Automotive (ISO 26262) on the project settings page and restore it then","Do not retry this call"]};if(Ar(e))return Ir();const n=zr(e);if(null!==n)return n;const r=qr(e);if(null!==r)return r;const a=Mr(e);if(null!==a)return a;const i=Y(e);return null!==i?i:Er(e)?{status:"error",message:"Nothing was saved: one save may name at most 50 items, counting both ends of each link, and this one names more.",next_steps:["Send the links in smaller batches (49 links from one item at a time, for example)","Do not send the same call again unchanged"],code:"too_many_items",retryable:!1}:/row.level security|permission denied for/i.test(e)?tu("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"]):tu(`Database error: ${Kd(e,Ld)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function xu(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function Su(e){return"string"!=typeof e?e:e.replace(/<\s*\/?\s*user_content\s*>/gi,"")}function $u(e){return Gd.has(e)}function Au(e,t,n=!1){return"string"==typeof e?n||null!=t&&Gd.has(t)?xu(e):e:Array.isArray(e)?e.map(e=>Au(e,t,n)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Au(t,e,n||Jd.has(e))])):e}function Iu(e,t={}){const n=t.complete?e:cd(e,void 0,t.paging,t.receipt);return{content:[{type:"text",text:JSON.stringify(Au(n),null,2)}],structuredContent:n}}function qu(e){return{content:[{type:"text",text:JSON.stringify(Au(e),null,2)}],structuredContent:e,isError:!0}}D(Yd,{CHARACTER_LIMIT:()=>Hd,USER_CONTENT_KEYS:()=>Gd,VALIDATION_MESSAGE_LONG:()=>Ud,accessDeniedError:()=>iu,authError:()=>ou,classifyError:()=>vu,dbError:()=>ju,errorResponse:()=>tu,formatErrorResult:()=>qu,formatToolResult:()=>Iu,isAutoWrappedKey:()=>$u,isItemSaveStopError:()=>ku,isJwtExpiredErrorForTool:()=>wu,isStaleWriteErrorMessage:()=>fu,jwtExpiredError:()=>lu,notFoundError:()=>nu,orgScopeError:()=>du,paginationMeta:()=>eu,parseError:()=>mu,policyNotLoadedError:()=>pu,rateLimitError:()=>uu,sanitizeForEcho:()=>Kd,sanitizeTagOrLevel:()=>Zd,saveBusyError:()=>hu,saveUnavailableError:()=>gu,scopeError:()=>cu,softDeletedItemError:()=>yu,staleWriteError:()=>_u,stripUserContentMarkers:()=>Su,success:()=>Xd,suspendedError:()=>ru,suspensionKind:()=>au,switchRedoFailedError:()=>bu,validationError:()=>su,wrapMcpUserContentFields:()=>Au,wrapUserContent:()=>xu});var Mu,Ou,Eu,zu=P({"src/tools/_base.ts"(){an(),$o(),ed(),zt(),sd(),re(),vd(),ai(),Qd(),Hd=25e3,Fd=50,Ld=200,Ud=600,Wd=new RegExp("[\\u0000-\\u001F\\u007F]","g"),Vd=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g"),Bd="rollout_switched:multiuser_saving: ",Gd=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","source_function_title","rerun_scope","report_text","reason","model_mermaid","box_label","arrow_label","creator_name","updated_by_name"]),Jd=new Set(["fields","diff","point","theirs_value","base_value","your_value","old_value","new_value"])}});async function Ru(e,t){const n=Ou.get(t),r=Date.now();if(n&&r-n.at<Mu)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 Ou.set(t,{status:s,at:r}),s}function Tu(e){return JSON.stringify(Au(e),null,2)}var Cu,Pu,Du,Nu,Hu,Fu,Lu,Uu,Wu=P({"src/middleware/status-gate.ts"(){zu(),fe(),Mu=3e4,Ou=new Map,Eu="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."}}),Vu={};async function Bu(){if(Cu)try{const e=await Ze();e&&e.expires_at>Hu&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),Gu())}catch{}if(Cu&&Nu>Date.now()+6e4)return Cu;Cu&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:n}=await async function(){if(Fu&&Date.now()-Fu.at<1e3*xt)throw Fu.error;return Lu??=Ct().then(e=>(Fu=null,e)).catch(e=>{throw e instanceof $t&&(Fu={at:Date.now(),error:e}),e}).finally(()=>{Lu=null}),Lu}(),a=e.split(".");if(3===a.length)try{const e=JSON.parse(Buffer.from(a[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());Nu=1e3*(e.exp??0)}catch{Nu=Date.now()+36e5}try{const e=await Ze();Hu=e?.expires_at??0}catch{Hu=0}const i=function(e,t){try{Object.defineProperty(e,ni,{value:t,enumerable:!1,configurable:!0})}catch{}return e}(r.createClient(gt,yt,{global:{headers:{Authorization:`Bearer ${e}`},fetch:pi({supabaseUrl:gt,anonKey:yt,accessToken:e},gi())}}),{supabaseUrl:gt,anonKey:yt,accessToken:e});return Pu=t,Du=n,Cu=i}function Gu(){Fu=null,Cu=null,Pu=null,Du=null,Uu=void 0,Nu=0,Hu=0,Ou.clear()}function Ju(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 Qu(e){try{return await e()}catch(t){if(!Ju(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),Gu(),await e()}}function Yu(){if(!Pu)throw new Error("Not authenticated. Call getClient() first.");return Pu}function Ku(){return Du??""}async function Zu(e){const t=Yu();if(Uu&&Uu.userId===t)return Uu.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 Uu={userId:t,name:a},a}catch{return null}}function Xu(e){if(e&&e.deleted_at)throw new Error(Pn)}async function ep(e,t){const{data:n,error:r}=await e.from("projects").select("deleted_at").eq("id",t).maybeSingle();if(r||!n)throw Or(t,r);Xu(n)}async function tp(e,t){const n=Yu(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Or(t,a);Xu(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 np(e,t){const n=Yu(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Or(t,a);Xu(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";throw new Error("PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED")}D(Vu,{assertProjectLive:()=>ep,getClient:()=>Bu,getUserEmail:()=>Ku,getUserId:()=>Yu,getUserName:()=>Zu,invalidateClient:()=>Gu,isJwtExpiredError:()=>Ju,requireProjectFieldDefinitionAccess:()=>np,requireWriteAccess:()=>tp,throwIfProjectInTrash:()=>Xu,withJwtRetry:()=>Qu});var rp,ap,ip,sp=P({"src/db/client.ts"(){Ht(),zt(),ut(),It(),ai(),hi(),xi(),Wu(),Cu=null,Pu=null,Du=null,Nu=0,Hu=0,Fu=null,Lu=null}}),op={};async function lp(){const e=i.randomBytes(32).toString("base64url"),t=i.createHash("sha256").update(e).digest("base64url"),n=`http://localhost:${rp}${ap}`,r=new s.URL(`${wt}/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:${rp}`);if(i.pathname!==ap)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(mp("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(`${gt}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:yt},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(mp(`Code exchange failed: ${e}`)),o(),l.close(),void n(new Error(`Code exchange failed: ${e}`))}let c;try{c=await cp(s,s.access_token)}catch(e){if(!(e instanceof ip))throw e;return a.writeHead(200,{"Content-Type":"text/html"}),a.end(mp(e.page)),o(),l.close(),void n(e)}return a.writeHead(200,{"Content-Type":"text/html"}),a.end(function(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>`}(c)),o(),l.close(),void t({email:c})}a.writeHead(400,{"Content-Type":"text/html"}),a.end(mp("This page did not receive an authorization code, so nothing was saved. If you are signing in, finish it in the sign-in tab. Otherwise run the login command again."))}catch(e){a.writeHead(500),a.end("Authentication failed"),o(),l.close(),n(e)}});l.listen(rp,"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`),process.stderr.write("Sign in with email and password instead: npx @atoms-tech/atoms-mcp@latest login --email\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)})}async function cp(e,t){let n="authenticated";try{n=JSON.parse(Buffer.from(t.split(".")[1],"base64").toString()).email??n}catch{}const{createClient:r}=await import("@supabase/supabase-js"),a=r(gt,yt,{global:{headers:{Authorization:`Bearer ${t}`}}}),{data:i,error:s}=await a.from("org_members").select("org_id").limit(1);if(s||!i||0===i.length)throw new ip("No ATOMS account found. Sign up at atoms.tech first.",'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.');if(!e.refresh_token)throw new ip("No refresh token issued by Supabase, so the session cannot be kept.","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.");return await Xe({access_token:t,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:n}),n}async function dp(e,t){const n=await fetch(`${gt}/auth/v1/token?grant_type=password`,{method:"POST",headers:{"Content-Type":"application/json",apikey:yt},body:JSON.stringify({email:e,password:t})}).catch(e=>{throw new Error(`Sign-in failed: could not reach ATOMS (${e instanceof Error?e.message:String(e)}).`)}),r=await n.json().catch(()=>({}));if(!n.ok||!r.access_token)throw new Error(`Sign-in failed: ${r.error_description??r.msg??`HTTP ${n.status}`}`);return{email:await cp(r,r.access_token)}}async function up(e,t=process.stdin,n=process.stderr){return dp(e?.trim()||(await pp("Email: ",!1,t,n)).trim(),await pp("Password: ",!0,t,n))}function pp(e,t,n,r){return n.isTTY?new Promise((a,i)=>{let s="";const o=e=>{n.off("data",l),n.setRawMode(!1),n.pause(),r.write("\n"),e?i(e):a(s)},l=e=>{for(const n of e){if("\r"===n||"\n"===n)return o();if(""===n||""===n)return o(new Error("Sign-in cancelled."));""===n||"\b"===n?(s&&!t&&r.write("\b \b"),s=s.slice(0,-1)):(s+=n,t||r.write(n))}};r.write(e),n.setRawMode(!0),n.setEncoding("utf8"),n.on("data",l),n.resume()}):Promise.reject(new Error("login --email needs an interactive terminal to ask for the password."))}function mp(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>`}D(op,{login:()=>lp,loginWithEmail:()=>up,loginWithPassword:()=>dp});var fp=P({"src/auth/login.ts"(){ut(),It(),rp=19275,ap="/callback",ip=class extends Error{constructor(e,t){super(e),this.page=t}page}}}),_p={};async function hp(){const{getValidToken:e,readValidToken:t}=await Promise.resolve().then(()=>(Ht(),Rt)),{runExclusiveAuth:n}=await Promise.resolve().then(()=>(vt(),pt)),{login:r}=await Promise.resolve().then(()=>(fp(),op));try{return(await e()).email}catch(e){if(e instanceof $t)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}}D(_p,{startupAuth:()=>hp});var gp,yp,wp,vp=P({"src/auth/startup.ts"(){zt()}});function bp(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&&gp.has(n.level)?{level:n.level,source:"string"==typeof n.source?n.source:null,dismissed:!0===n.dismissed}:null}function kp(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?bp(e.data):null;return a&&(r.asil_pending_lower={value:a.level,source:a.source,dismissed:a.dismissed,since:t.since}),r}function jp(e){return{op_id:"",status:"forbidden",reason:"asil_lower_needs_person",item_id:e,path:[...yp],seq:null}}var xp,Sp,$p,Ap=P({"src/core/asil-read.ts"(){gp=new Set(["QM","A","B","C","D"]),yp=["asil_confirm_lower"],wp="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 Ip(e){return e.startsWith("req_type '")}function qp(e,t){if("requirement"!==t)return`req_type applies only to requirements (type='requirement'), not '${t}'.`;const n=`Plain requirement types: ${xp.join(", ")}.`;return"safety-goal"===e?`req_type '${e}' is the type of a row of a HARA, a risk analysis or a security risk analysis, not of a plain requirement, so atoms_create_item and atoms_update_item refuse it. To make a Safety goal item (SG-n), call atoms_create_item with type 'goal' (automotive projects where Hazard and Safety goal items are on). To add a row to an analysis, call atoms_propose_rows, or atoms_create_analysis for a new analysis. ${n}`:"failure-mode"===e?`req_type '${e}' is the type of an FMEA row (a DFMEA, PFMEA, Software FMEA or Use FMEA), not of a plain requirement, so atoms_create_item and atoms_update_item refuse it. To add a row to an FMEA, call atoms_propose_rows, or atoms_create_analysis for a new one. ${n}`:xp.includes(e)?null:`Unknown req_type '${e.slice(0,50)}'. Allowed: ${xp.join(", ")}.`}var Mp,Op,Ep,zp,Rp=P({"src/core/req-type.ts"(){xp=["functional","interface","performance","safety"],Sp=["safety-goal","failure-mode"],$p="Requirement classification (functional|interface|performance|safety). safety-goal and failure-mode are the types of analysis rows, not of plain requirements, and are refused here: make a Safety goal item with atoms_create_item type 'goal', and add analysis rows with atoms_propose_rows or atoms_create_analysis."}});function Tp(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Ep)if(t.test(e.trim()))return"[redacted]";return e.length>zp?e.slice(0,zp)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Tp(e,t+1));if(null!==e&&"object"==typeof e){const n={};for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();Mp.has(e)?n[r]="[redacted]":Op.has(e)?n[r]="string"==typeof a?"[content]":Tp(a,t+1):n[r]=Tp(a,t+1)}return n}return e}function Cp(e){return Tp(e)}var Pp,Dp,Np,Hp,Fp,Lp,Up,Wp,Vp=P({"src/middleware/audit.ts"(){Mp=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),Op=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Ep=[/^[^\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_-]+$/],zp=200}}),Bp=P({"src/middleware/rate-limiter.ts"(){Pp=60,Dp=6e4}}),Gp={};function Jp(){return z.default.join(t.homedir(),".atoms","update-check.json")}async function Qp(){if(!Wp&&(Wp=!0,"1"!==process.env.ATOMS_MCP_NO_UPDATE_CHECK))try{const e=await async function(){try{const e=JSON.parse(await o.promises.readFile(Jp(),"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<Hp)return void(Lp=e.latest);const t=new AbortController,n=setTimeout(()=>t.abort(),Fp);try{const e=await fetch(process.env.ATOMS_MCP_UPDATE_URL??Np,{signal:t.signal});if(!e.ok)return;const n=await e.json();if("string"!=typeof n.version)return;Lp=n.version,await async function(e){try{await o.promises.mkdir(z.default.dirname(Jp()),{recursive:!0}),await o.promises.writeFile(Jp(),JSON.stringify({checked_at:Date.now(),latest:e}),"utf8")}catch{}}(n.version)}finally{clearTimeout(n)}}catch{}}function Yp(e){return null!==Lp&&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,Lp)?{current:e,latest:Lp,args:["@atoms-tech/atoms-mcp@latest"],command:"npx @atoms-tech/atoms-mcp@latest"}:null}function Kp(e){const t=Yp(e);return t?Rr(t.current,t.latest):null}function Zp(e){if(Up)return null;const t=Kp(e);return null===t?null:(Up=!0,t)}function Xp(e,t){const n=Zp(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 em(e,t){const n=Yp(t);if(null===n||!e||"object"!=typeof e)return e;const r=Rr(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 tm(){Lp=null,Up=!1,Wp=!1}D(Gp,{UPDATE_CHECK_TIMEOUT_MS:()=>Fp,attachUpdateAvailable:()=>em,attachUpdateNotice:()=>Xp,getUpdateAvailable:()=>Yp,resetUpdateCheckForTests:()=>tm,startUpdateCheck:()=>Qp,takeUpdateNotice:()=>Zp,updateStatusSentence:()=>Kp});var nm,rm,am,im,sm,om,lm,cm,dm,um,pm,mm,fm,_m,hm,gm,ym,wm=P({"src/middleware/update-check.ts"(){ai(),Np="https://registry.npmjs.org/@atoms-tech/atoms-mcp/latest",Hp=864e5,Fp=3e3,Lp=null,Up=!1,Wp=!1}}),vm=P({"src/core/timestamps.ts"(){}});function bm(e){return 32===e||9===e||13===e||10===e}function km(e){if("string"!=typeof e)return NaN;const t=nm.exec(function(e){let t=0,n=e.length;for(;t<n&&bm(e.charCodeAt(t));)t++;for(;n>t&&bm(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 f=0;if("Z"!==c.toUpperCase()){const e="-"===c[0]?-1:1,t=c.slice(1).replace(":","");f=e*(60*Number(t.slice(0,2))+(t.length>2?Number(t.slice(2,4)):0))}return 1e3*(m-6e4*f)+Number(`${l}000000`.slice(0,6))}function jm(e,t){const n=km(e),r=km(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 xm(e){return"passed"===e||"failed"===e||"blocked"===e}function Sm(e){const t=[];return e.forEach((e,n)=>{e&&void 0!==e.date&&null!==e.date&&t.push(n)}),t}function $m(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 Am(e){const t=[];return e.forEach((e,n)=>{const r=e?.release_id;"string"==typeof r&&""!==r.trim()||t.push(n)}),t}function Im(e){return`No release_id was sent on ${e.length} ${1===e.length?"entry":"entries"} (results[${e.join(", ")}]), so ${1===e.length?"that run counts":"those runs count"} toward no Release: atoms_verification_status and the app's Release views do not read them, and their Release cannot be set later. A run counts toward a Release only when it is recorded with that Release's release_id (atoms_list_baselines lists the Releases).`}function qm(e,t,n){if(Array.isArray(e))for(const n of e)if(n&&"object"==typeof n&&n.op_id===t){const e=n.result;if("string"==typeof e)return e}return null!=n?.step_results?null:String(n?.result??"")}function Mm(e,t){const n=[];return Array.isArray(t)?(e.forEach((e,r)=>{const a=t[r]?.result;"string"==typeof a&&a!==e?.result&&n.push(r)}),n):n}function Om(e,t=!1){return(t?"This run was":`${1===e.length?"The run of":"The runs of"} results[${e.join(", ")}] ${1===e.length?"was":"were"}`)+" stored with another result than the one sent: a run sent with step_results takes its verdict from them and the result sent with it is not used. Each result in this answer is the verdict as stored."}function Em(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 zm(e,t){return"string"==typeof e?t(e):Array.isArray(e)?e.map(e=>zm(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,zm(n,t)])):e}function Rm(e,t){const n=zm(e,t);return _m(n?.point)&&(n.point=Object.fromEntries(Object.entries(n.point).map(([e,n])=>[t(e),n]))),n}function Tm(e,t){if(!Array.isArray(e)||!Array.isArray(t))return e;const n=["source","plus","minus"];return e.map(e=>{if(!_m(e)||n.some(t=>t in e))return e;const r=t.find(t=>_m(t)&&t.name===e.name);return _m(r)&&JSON.stringify(r.values)===JSON.stringify(e.values)?{...e,...Object.fromEntries(Object.entries(r).filter(([e])=>n.includes(e)))}:e})}function Cm(e){const t=e.data?.status,n="test-case"===e.type?Lm(e.data):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||jm(r.date,n.date)<0)&&(n=r);return n}(e,e=>xm(e.result))?.result;return xm(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 Pm(e){const t=e.data?.runs;return"test-case"===e.type&&Array.isArray(t)&&t.length>0}function Dm(e){return`${e} has runs: ${hm}. Record a run: atoms_record_test_result(s).`}function Nm(e,t){return"test-case"===e.type&&!Pm(e)&&("passed"===t||"failed"===t||"blocked"===t)}function Hm(e){return`${e} has no runs: ${gm}. Record a run: atoms_record_test_result(s).`}function Fm(e,t){const n="string"==typeof e.result?e.result:void 0;if(xm(n))return n;if(!Array.isArray(e.step_results)||0===e.step_results.length)return"not-run";const r=e.step_results.map(e=>_m(e)?e.status:void 0);if(r.includes("failed"))return"failed";if(r.includes("blocked"))return"blocked";const a=r.filter(e=>"passed"===e||"skipped"===e).length;return a>=Math.max(t??r.length,1)&&a===r.length&&r.includes("passed")?"passed":"not-run"}function Lm(e){const t=e?.runs;if(!Array.isArray(t))return t;const n=Array.isArray(e?.steps)?e.steps.length:void 0;return t.map(e=>_m(e)?{...e,result:Fm(e,n)}:e)}var Um,Wm,Vm,Bm,Gm,Jm,Qm,Ym,Km,Zm=P({"src/core/run-order.ts"(){nm=/^([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,rm="No release_id was sent, so this run counts toward no Release: atoms_verification_status and the app's Release views do not read it, and its Release cannot be set later. A run counts toward a Release only when it is recorded with that Release's release_id (atoms_list_baselines lists the Releases).",am="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.",im="Ignored: the run is stamped with server time. A supplied date is reported in the response warning, never stored.",sm="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.",om="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.",lm="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).",cm="Ignored: the server pins the test case's current steps revision itself",dm="Link to evidence kept elsewhere, at most 2048 characters. Stored as text; ATOMS does not open it",um="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",pm="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.",mm="Step id, required on every step. A step that already exists keeps the id atoms_get_item returned. A NEW step needs an id of the form st_ followed by exactly 16 lowercase hexadecimal characters, for example st_0f3a9c1d2b4e5f60; on a project that saves one field at a time any other new id is refused with bad_row_id.",fm="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.",_m=e=>!!e&&"object"==typeof e&&!Array.isArray(e),hm="its status comes from its runs and cannot be set",gm="a result can only come from a run",ym="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 Xm(e){return"requirement"===e.type&&"string"==typeof e.data?.req_type&&Sp.includes(e.data.req_type)}function ef(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 tf(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||!Xm(a)&&"goal"!==a.type)return;if("requirement"!==i.type||Xm(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}function nf(e,t){const n=tf(e,t),r=new Map;for(const t of e)r.set(t.id,t);const a=new Map;for(const e of t){const[t,n]="event_goal"===e.type?[e.from_id,e.to_id]:"goal_events"===e.type?[e.to_id,e.from_id]:[null,null];if(!t||!n||a.has(t))continue;const i=r.get(t);i&&Xm(i)&&"goal"===r.get(n)?.type&&a.set(t,n)}const i=new Map;for(const[e,t]of n)Xm(r.get(e))&&i.set(e,t);for(const[e,t]of a){const r=n.get(t)??[];0!==r.length&&i.set(e,[...new Set([...i.get(e)??[],...r])].sort((e,t)=>e.localeCompare(t)))}return i}function rf(e){const t={};for(const n of["req_type","relationships","tags","status"])null!=e[n]&&(t[n]=e[n]);return{id:e.id,type:e.type??void 0,title:e.title??void 0,data:t}}async function af(e,t){return Sn(()=>e.from("items").select(Um).eq("project_id",t).eq("type","requirement").is("deleted_at",null).not("data->relationships->mitigates","is",null).neq("data->relationships->mitigates","[]"),pn)}function sf(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 cf(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 cf(t.data?.relationships?.mitigated_by))r.push({from_id:t.id,to_id:e,type:"mitigated_by"})}const a=nf([...n.values()],r);for(const t of e){const e=a.get(t.id);e&&a.set(t.id,[...new Set([...cf(t.data?.relationships?.mitigated_by).filter(t=>e.includes(t)),...e])])}return a}async function of(e,t,n,r){return sf([n],[...r.map(e=>({id:e.id,type:e.type,req_type:e.data?.req_type,mitigates:e.data?.relationships?.mitigates})),...await af(e,t)]).get(n.id)??[]}function lf(e,t,n,r){return(e?.asil!==n||e?.asil_source!==t)&&(r||e?.asil_source===t)}function cf(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function df(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)}function uf(e,t){return`${e} is not linked to ${t}: neither ${e}'s mitigated_by nor ${t}'s mitigates names the other, so there is nothing to remove and nothing was changed.`}function pf(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 mf(e,t,n){return e.filter(e=>!t.has(e)&&(n.get(e)?.length??0)>0).length}var ff,_f,hf=P({"src/core/coverage-mitigation.ts"(){kr(),Wc(),Rp(),Um="id, type, updated_at, content_changed_at, req_type:data->>req_type, mitigates:data->relationships->mitigates",Wm="id, type, title, req_type:data->req_type, relationships:data->relationships, tags:data->tags, status:data->status",Vm=3,Bm=0,Gm=[],Jm=["severity","exposure","controllability"],Qm="role, control_type and override apply to action add only; omit them to remove a link.",Ym="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.",Km="coverage.covered and coverage.percent count a requirement's own linked test cases, and a requirement closed with a document (coverage.covered_by_document). 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."}});async function gf(e,t){const{data:n,error:r}=await e.rpc("verification_document_closures",{p_project_id:t});if(r)throw r;const a=n??{};return!0!==a.enabled?null:(Array.isArray(a.document_closures)?a.document_closures:[]).map(e=>{const t=e;return{requirement_id:String(t.requirement_id??""),label:String(t.label??""),document_name:String(t.document_name??""),link:"string"==typeof t.link?t.link:null,closed_by:String(t.closed_by??""),closed_at:String(t.closed_at??"")}})}function yf(e,t,n){if(!n)return e;const r=new Set(n.map(e=>e.requirement_id)),a={verified:0,failing:0,incomplete:0,not_run:0,stale:0,points_total:0,points_run:0};let i=0;for(const e of t){if(!r.has(e.requirement_id))continue;i+=1;const t=!0===e.stale;"verified"!==e.state||t||(a.verified+=1),"failing"===e.state&&(a.failing+=1),"incomplete"!==e.state||t||(a.incomplete+=1),"not-run"===e.state&&(a.not_run+=1),t&&(a.stale+=1),a.points_total+=Number(e.points_total??0)||0,a.points_run+=Number(e.points_run??0)||0}const s={...e};for(const[t,n]of Object.entries(a))n>0&&(s[t]=(Number(e[t]??0)||0)-n);const o=new Set(t.map(e=>e.requirement_id)),l=[...r].filter(e=>!o.has(e)).length;return l>0&&(s.requirements=(Number(e.requirements??0)||0)+l),s.closed_by_document=i+l,s}function wf(e,t,n){if(!n)return{covered:e.slice(),uncovered:t.slice(),coveredByDocument:null};const r=new Set(n.map(e=>e.requirement_id)),a=t.filter(e=>r.has(e.id)),i=a.map(e=>e.id).sort();return{covered:[...e,...a],uncovered:t.filter(e=>!r.has(e.id)),coveredByDocument:{count:i.length,ids:i}}}var vf,bf,kf=P({"src/core/document-closures.ts"(){ff="covered_by_document is present only while Close with a document is switched on for the project and the report reads the current state (no baseline_id, no as_of): it is { count, ids } for the requirements with no linked test case that an editor or admin closed in the app with a document, which the app reads as covered and done, so they are counted in covered and coverage_percent and left out of uncovered and uncovered_items. A report at a baseline or a past moment reads no closures and keeps the coverage that moment recorded.",_f="coverage.covered_by_document is present only while Close with a document is switched on for the project: it is { count, ids } for the requirements with no linked test case that an editor or admin closed in the app with a document, which the app reads as covered and done, so they are counted in coverage.covered, coverage.percent and coverage_by_domain, and left out of coverage.uncovered and coverage.via_mitigation."}});function jf(e,t){return t>0?Math.round(e/t*1e3)/10:vf}var xf,Sf,$f=P({"src/core/project-summary.ts"(){Zm(),vf=100,bf="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 Af(e,t){const n=Sf.find(t=>t.type===e);return n?t?n.lane:n.incoming:void 0}function If(e){const t={};for(const n of Sf){const r=e[n.lane]??[];(n.always||r.length>0)&&(t[n.lane]=r)}return t}function qf(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 xf){const a=e[n];if(Array.isArray(a))for(const e of a)"string"==typeof e&&i(t.id,e,r)}}return a}var Mf,Of,Ef,zf,Rf,Tf=P({"src/core/relationship-sync.ts"(){xf=[["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"],["event_hazard","event_hazard"],["hazard_events","hazard_events"],["event_goal","event_goal"],["goal_events","goal_events"]],Sf=[{lane:"parents",type:"parent",incoming:"children",always:!0},{lane:"children",type:"child",incoming:"parents",always:!0},{lane:"related",type:"related",incoming:"related",always:!0},{lane:"verified_by",type:"verified_by",incoming:"verifies",always:!0},{lane:"verifies",type:"verifies",incoming:"verified_by",always:!0},{lane:"mitigated_by",type:"mitigated_by",incoming:"mitigates",always:!0},{lane:"mitigates",type:"mitigates",incoming:"mitigated_by",always:!0},{lane:"affects",type:"affects",incoming:"affected_by",always:!0},{lane:"affected_by",type:"affected_by",incoming:"affects",always:!0},{lane:"allocated_to",type:"allocated_to",incoming:"allocated_from",always:!1},{lane:"allocated_from",type:"allocated_from",incoming:"allocated_to",always:!1},{lane:"traces_to",type:"traces_to",incoming:"traced_by",always:!1},{lane:"traced_by",type:"traced_by",incoming:"traces_to",always:!1},{lane:"decomposes_to",type:"decomposes_to",incoming:"decomposed_from",always:!1},{lane:"decomposed_from",type:"decomposed_from",incoming:"decomposes_to",always:!1}]}});function Cf(e){const t=e?.trim();return t?`Release ${t}`:Mf}function Pf(e){const t=(e??[]).filter(e=>null!=e.release_version);return t.find(e=>"released"===e.release_status)??t.slice().sort((e,t)=>String(t.snapshot_at??"").localeCompare(String(e.snapshot_at??"")))[0]}async function Df(e,t){try{const{data:n,error:r}=await e.from("baselines").select("id, release_version, release_status, snapshot_at").eq("project_id",t).is("deleted_at",null);if(r)return Of;const a=Pf(n);return a?{releaseId:a.id,label:Cf(a.release_version)}:Of}catch{return Of}}async function Nf(e,t,n,r){return On([...new Set(n)],n=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:r,p_requirement_ids:n}))}async function Hf(e,t,n){const r=n.filter(e=>"requirement"===e.type).map(e=>e.id),a=n.filter(e=>"test-case"===e.type);if(0===r.length&&0===a.length)return{flags:new Map,scope:null};const i=await Df(e,t),s=new Set(r);if(a.length>0){const n=a.map(e=>e.id),r=[],i=[];for(let s=0;s<n.length;s+=200){const o=n.slice(s,s+200),l=[...await Sn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verified_by").in("to_id",o),mn),...await Sn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verifies").in("from_id",o),mn)];r.push(...l);const c=new Set(l.map(e=>"verified_by"===e.type?e.from_id:e.to_id));for(const e of a.slice(s,s+200)){const t=e.data?.relationships;for(const e of Ef(t?.verifies))c.add(e)}i.push(...await Sn(()=>e.rpc("tcm_requirements_for_test_cases",{p_project_id:t,p_test_case_ids:o,p_requirement_ids:[...c]}),pn))}const o=new Set(i.map(e=>e.id)),l=new Set(n),c=qf([...a,...i.map(e=>({id:e.id,data:{relationships:{verified_by:Ef(e.verified_by)}}}))],r);for(const e of c)"verified_by"===e.type&&o.has(e.from_id)&&l.has(e.to_id)&&s.add(e.from_id),"verifies"===e.type&&l.has(e.from_id)&&o.has(e.to_id)&&s.add(e.to_id)}const o=new Map,l=s.size>0?await Nf(e,t,s,i.releaseId):[],c=new Set(l.map(e=>e.requirement_id)),d=function(e){return new Set(e.flatMap(e=>e.test_case_ids??[]))}(l);for(const e of r)o.set(e,c.has(e));for(const e of a)o.set(e.id,d.has(e.id));return{flags:o,scope:i}}function Ff(e,t){const n=e?.flags.get(t);return void 0!==n&&e?.scope?{needs_rerun:n,rerun_scope:e.scope.label}:{}}var Lf,Uf,Wf,Vf=P({"src/core/rerun.ts"(){kr(),Tf(),Of={releaseId:null,label:Mf="All runs"},Ef=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],zf="needs_rerun (requirements and test cases, live reads only): true when a linked test case passed before the requirement's content last changed. The app shows such a test case as Rerun (R) instead of Passed, and the requirement as Rerun unless it is failing: report it as needing a rerun, never as passed. status keeps the verdict of the newest run. "+'Judged as the Matrix judges it: in the project\'s current formal Release when it has one (only runs bound to that Release count), otherwise on every recorded run; rerun_scope names the scope read ("Release 1.1" or "All runs", the label the Matrix prints), so say which runs you judged.'+" atoms_get_item carries rerun_scope beside needs_rerun, atoms_list_items once in meta.rerun_scope.",Rf='rerun.requirements counts the requirements with a linked test case that passed before the requirement\'s content last changed (the Matrix reads them Rerun unless failing); rerun.test_cases counts the test cases whose status reads passed but need such a rerun (the app shows R): they are part of test_status.passed, so report them as needing a rerun, not as passed. Judged as the Matrix judges it: in the project\'s current formal Release when it has one (only runs bound to that Release count), otherwise on every recorded run; rerun_scope names the scope read ("Release 1.1" or "All runs", the label the Matrix prints), so say which runs you judged.'}});async function Bf(e,t){try{const{data:n,error:r}=await e.rpc("project_function_mode",{p_project_id:t});return r?function(e){return!!e&&("PGRST202"===e.code||"42883"===e.code||/Could not find the function public\.project_function_mode/i.test(String(e.message??"")))}(r)?"tags":"unknown":"items"===n?"items":"tags"===n?"tags":"unknown"}catch{return"unknown"}}function Gf(e){const t=["requirement","test-case","note","table"];return"items"===e?[...t,"function"]:t}function Jf(e){return"items"===e?null:"unknown"===e?{status:"error",message:Wf,next_steps:["Send the same call again in a moment"],code:"function_mode_unreadable",retryable:!0}:{status:"error",message:Lf,next_steps:Uf,code:"function_items_off",retryable:!1}}var Qf,Yf,Kf,Zf,Xf,e_,t_,n_,r_,a_,i_,s_=P({"src/core/function-mode.ts"(){Lf="Function items are not turned on for this project, so a Function cannot be created or allocated to yet. Nothing was written. Ask an ATOMS administrator to convert the project's functions to Function items.",Uf=["Until the project is converted its functions stay named by its function tags, which are not domains. Ask an ATOMS administrator to convert the project to Function items","Do not retry: the answer stays the same until an administrator converts the project"],Wf="The project's Function setting could not be read just now. Nothing was written. Send the same call again in a moment."}});function o_(e){return(e??"").trim().toLowerCase()}function l_(e){const t=e.analysis_props;return t&&"object"==typeof t?t:{}}function c_(e){return"string"==typeof e?e:""}function d_(e,t,n,r){const a=l_(e),i=c_(a.source_function),s={id:null,title:null,label:i,state:"legacy-text"};if(!t||!Qf.has(t))return s;let o=c_(a.source_function_id).trim();if(!o){const e=o_(i);if(!e)return s;const t=(r??[]).find(t=>t.tag_key===e&&!t.reverted_at);if(!t)return s;o=t.item_id}const l=n.get(o),c=!!l&&"function"===l.type&&!l.deleted_at;return{id:o,title:l&&"function"===l.type?l.title??"":null,label:i,state:c?"live":"trashed"}}function u_(e,t,n,r){const a=d_(e,t,n,r);if("live"!==a.state||!a.id)return null;const i=n.get(a.id);return i?.content_changed_at??i?.updated_at??null}function p_(e,t){const n=e_[e]?.[t]??`Create a Function with ${Yf}.`;return`${t} was removed in ATOMS MCP ${Kf}, with no deprecation period. ${n} Nothing was written.`}function m_(e,t){const n=function(e,t){const n=e_[e];return n&&t&&"object"==typeof t?Object.keys(n).filter(e=>void 0!==t[e]):[]}(e,t);return 0===n.length?null:{status:"error",message:`Validation error: ${n.map(t=>p_(e,t)).join(" ")}`,next_steps:[`Create a Function with ${Yf}, then name it by its id, on a project with Function items turned on; a project without them needs an ATOMS administrator to convert it first`,"Do not send the removed input again: it is refused on every project"],code:"input_removed",retryable:!1}}function f_(e){return(t,n)=>{if("unrecognized_keys"===t.code){const n=e_[e]??{},r=(t.keys??[]).filter(e=>e in n);if(r.length>0)return{message:r.map(t=>p_(e,t)).join(" ")}}return{message:n.defaultError}}}function __(e){const t=[];for(const n of e){const e="string"==typeof n?n.trim():"";e&&!t.includes(e)&&t.push(e)}return t}function h_(e){const t=e.map(e=>`${e.id} (${e.problem})`).join(", ");return{status:"error",message:`Validation error: ${1===e.length?"This id does":"These ids do"} not name a live Function of this project: ${t}. An analysis row names a Function item by its id. Nothing was written.`,next_steps:["Find the project's Functions with atoms_list_items type 'function'",`Or create the Function first with ${Yf}`],code:"function_id_invalid",retryable:!1,invalid_function_ids:e.map(e=>e.id)}}function g_(e){return{status:"error",message:'Validation error: a Function id must be a non-blank string such as "FN-001"; an empty or whitespace-only id names no Function. Nothing was written.',next_steps:["Find the project's Functions with atoms_list_items type 'function'","Drop the blank entry from the list"],code:"function_id_invalid",retryable:!1,invalid_function_ids:e.filter(e=>"string"!=typeof e||""===e.trim()).map(e=>"string"==typeof e?e:String(e))}}async function y_(e,t,n){return w_(e,t,n,await Bf(e,t))}async function w_(e,t,n,r){const a=Jf(r);if(a)return{ok:!1,error:{...a}};if(function(e){return e.some(e=>"string"!=typeof e||""===e.trim())}(n))return{ok:!1,error:g_(n)};const i=__(n);if(0===i.length)return{ok:!0,functions:[]};const s=await v_(e,t,i),o=[],l=[];for(const e of i){const t=s.get(e);t?"function"!==t.type?o.push({id:e,problem:"not a Function"}):t.deleted_at?o.push({id:e,problem:"in Trash"}):l.push({id:e,title:t.title??""}):o.push({id:e,problem:"no item with this id in this project"})}return o.length>0?{ok:!1,error:h_(o)}:{ok:!0,functions:l}}async function v_(e,t,n){const r=new Map;if(0===n.length)return r;let a;try{a=await On([...new Set(n)],n=>e.from("items").select("id, type, title, deleted_at, content_changed_at, updated_at").eq("project_id",t).in("id",n))}catch(e){throw new Error(`Function read failed: ${e?.message||"unknown error"}`)}for(const e of a)r.set(e.id,e);return r}function b_(e){return e.functionId?{source_function:e.text,source_function_id:e.functionId}:{source_function:e.text}}function k_(e,t){return t.functionId?{id:e,source_function:t.text,source_function_id:t.functionId,source_function_title:t.text}:{id:e,source_function:t.text}}function j_(e){return!!e&&Qf.has(e)}async function x_(e,t,n){if(j_(e)){if(!t.includes("source_function"))return null;const r=`source_function was removed in ATOMS MCP ${Kf}, with no deprecation period: a ${e} row names its Function by id.`,a=await n();return"items"===a?`${r} Pass source_function_id (find the id with atoms_list_items type 'function', or create the Function with ${Yf}). Nothing was written.`:"tags"===a?`${r} This project has no Function items turned on, so source_function_id and creating a Function are refused here. A person sets the row's Function in the row panel of the ATOMS app, or ask an ATOMS administrator to convert the project to Function items. Send the row's other fields again without source_function. Nothing was written.`:`${r} Which step applies depends on whether the project has Function items turned on, which could not be read just now. Send the call again without source_function (the same call is refused on every project). Nothing was written.`}return t.includes(Zf)?"security_tir57"===e?"A security_tir57 row names an asset as text in source_function, never a Function: source_function_id is refused. Nothing was written.":`source_function_id applies to a HARA or a risk analysis row only; a ${e} row names no Function. Nothing was written.`:null}function S_(e,t=[]){return{status:"error",message:`Validation error: ${e}`,next_steps:t.length>0?[...t]:["Check the parameter types and constraints in the tool description"],code:"validation_error",retryable:!1}}function $_(e){return e?b_(e):{source_function:null}}function A_(e,t,n){return"hara"!==e?{source_req:n??null}:t?{source_function:t.text,source_function_id:t.functionId,source_function_title:t.text}:{source_function:null}}var I_,q_,M_=P({"src/core/functions.ts"(){ai(),s_(),kr(),Qf=new Set(["hara_iso26262","hazard_iso14971"]),Kf="0.62.0",Zf="source_function_id",e_={atoms_update_domain:{is_function:`A function is no longer a flagged domain tag: it is an item. Create one with ${Yf="atoms_create_item type 'function'"}, on a project with Function items turned on. ${Xf="A project without Function items cannot create a Function or name one by id over MCP: ask an ATOMS administrator to convert the project to Function items."}`},atoms_create_analysis:{source_functions:`Seed a HARA or a risk analysis with source_function_ids, the ids of Function items, on a project with Function items turned on (find them with atoms_list_items type 'function', or create one with ${Yf}); seed a security risk analysis with source_assets, its asset names. ${Xf}`},atoms_propose_rows:{source_function:`Pass source_function_id, the id of a Function item, on a project with Function items turned on (find it with atoms_list_items type 'function', or create one with ${Yf}). ${Xf}`},atoms_mutate_scenario_catalog:{function_tags:`Pass function_ids, the ids of the Function items the entry applies to, on a project with Function items turned on (find them with atoms_list_items type 'function', or create one with ${Yf}). A project without Function items takes function_ids: [] (every function); a person tags an entry by function tag on the Scenario catalogs page of the ATOMS app, or an ATOMS administrator converts the project to Function items.`}},t_="Function items are not turned on for this project, so a catalog entry cannot name a Function by id (function_ids) yet. Nothing was written.",n_=["To apply the entry to every function, send function_ids: [] or leave function_ids out","To tag the entry with one of the project's function tags, a person opens the project's Scenario catalogs page in the ATOMS app and ticks the tag on the entry (MCP tools do not tag by function name)","Or ask an ATOMS administrator to convert the project to Function items, then send the Function ids","Do not retry the same call: the answer stays the same until the project is converted"],r_='Function items are not turned on for this project, so source_function_id "" cannot clear the row\'s Function over MCP: on this project a row names its function by function tag, and MCP tools do not change function tags. Nothing was written.',a_=["To clear the row's Function, a person opens the row panel in the ATOMS app (the row's ID in the analysis grid opens it) and empties the Function field in its Analysis section; the grid's Function cell is read-only",'Or ask an ATOMS administrator to convert the project to Function items, then send source_function_id "" again',"Do not retry the same call: the answer stays the same until the project is converted"],i_=50}});function O_(e){return e?I_.indexOf(e):-1}function E_(e,t){const n=e?.[t];return"string"==typeof n?[n]:Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}function z_(e){return[...E_(e,"event_hazard"),...E_(e,"event_goal")]}function R_(e){const t=e.analysis_props;return"requirement"===e.type&&!!t&&"object"==typeof t}function T_(e){return!!e&&!e.deleted_at}function C_(e,t){const n=e.verified?"verified":"not verified";return 0===e.viaRows.length?`${e.id} ${n}`:`${e.id} ${n} via ${e.viaRows.map(t).join(", ")}`}var P_,D_,N_,H_,F_,L_,U_,W_,V_,B_,G_,J_,Q_,Y_,K_,Z_,X_,eh,th,nh,rh=P({"src/core/safety-index.ts"(){Wc(),hf(),M_(),I_=["QM","A","B","C","D"],q_=new WeakMap}});function ah(e){return"safety_goal"===e?"goal":e}function ih(e){return"hazard"===e||"goal"===e}async function sh(e,t){try{const{data:n,error:r}=await e.from("metadata").select("industry").eq("project_id",t).maybeSingle();if(r)return null;const a=Hl(n),i="automotive"===(a??"automotive")&&await $i(e,t,"automotive"),{data:s,error:o}=await e.rpc("rollout_state",{p_project_id:t});if(o||!s||"object"!=typeof s)return null;const l=s;return{industry:a,holdsAnalysisOutsideAutomotive:i,hazardGoalItemsOn:!0===l.hazard_goal_items,multiuserSavingOn:!0===l.multiuser_saving}}catch{return null}}function oh(e){if(!e)return{status:"error",message:J_,next_steps:["Send the same call again in a moment"],code:"hazard_goal_unreadable",retryable:!0};const t=Ai(e);return null===t?null:t===ki?go():_o()}async function lh(e,t){return oh(await sh(e,t))}function ch(e){const t={},n={};for(const[r,a]of Object.entries(e??{})){const e=Y_[r];if(!e){n[r]=a;continue}if("string"!=typeof a)return{picks:{},rest:{},error:`${r} must be the id of a ${"goal"===K_[e]?"Safety goal":"Hazard"} item (or "" to clear it)`};const i=a.trim();t[e]=""===i?null:i}return{picks:t,rest:n,error:null}}function dh(e){return Object.keys(e).length>0}function uh(e,t){const n=`${e}: hazard_id and goal_id apply only to the hazardous event rows of a stamped ISO 26262 HARA (one that uses Hazard and Safety goal items)`,r=nl[t];return r.includes("hazard")&&r.includes("safety_goal")?`${n}, and this analysis is not one. Write the row's hazard or safety_goal text instead. Nothing was written.`:`${n}. A ${Ol[t].parent} row has no hazard or safety_goal field and cites no Hazard or Safety goal item. Write its own fields with atoms_fill_row (${[...r,"effect"].join(", ")}) and link the requirement that mitigates it with atoms_link_mitigation. Nothing was written.`}function ph(e,t,n){const r=K_[e];if(n&&n.type===r&&(null===n.deleted_at||void 0===n.deleted_at))return null;const a="goal"===r?"Safety goal":"Hazard";return`${X_[e]} ${t} is not a live ${a} item of this project. Create one with atoms_create_item type "${r}", or name an existing one. Nothing was written.`}function mh(e,t,n,r={}){for(const a of["event_hazard","event_goal"]){const i=Z_[a];if(!n.includes(i))continue;const s=void 0!==r[a]?r[a]:E_(t,a)[0]??null;if(!s)continue;const o="goal"===K_[a]?"Safety goal":"Hazard";return`${e} names its ${o} as an item (${s}), so its ${i} text is read-only. Pick another ${o} with ${X_[a]}, or change the item itself with atoms_update_item. Nothing was written.`}return null}function fh(e,t){const n=[];for(const r of["event_hazard","event_goal"]){if(void 0===t[r])continue;const a=E_(e,r),i=t[r];for(const e of a)e!==i&&n.push({kind:"remove",path:["relationships",r],value:e});i&&!a.includes(i)&&n.push({kind:"add",path:["relationships",r],value:i})}return n}async function _h(e,t,n,r,a,i,s,o){if(!dh(i))return null;if(!a)return{kind:"validation",message:uh(n,r)};const l=fh(s,i).filter(e=>"add"===e.kind);if(0===l.length)return null;const c=oh(await sh(e,t));if(c)return{kind:"tool",error:c};for(const e of l){const t=ph(e.path[1],e.value,await o(e.value));if(t)return{kind:"validation",message:t}}return null}function hh(e,t){const n={};for(const r of["event_hazard","event_goal"])void 0!==t[r]?n[X_[r]]=t[r]??null:E_(e,r).length>0&&(n[X_[r]]=E_(e,r)[0]);return n}function gh(e){return e.filter(e=>eh.has(e.trim().toLowerCase().replace(/[\s-]+/g,"_")))}function yh(e,t){return`${e} is a Safety goal item: its safe state and FTTI are recorded on the hazardous event rows that cite it (atoms_fill_row on each row), never on the goal. ${t.join(", ")} was not saved.`}function wh(e,t){const n=Ol[e];return"hara_iso26262"===e&&"hazard_goal"===t?{...n,row:th}:n}function vh(e,t){return"hara_iso26262"===e&&"hazard_goal"===rc(t)}function bh(e){return/^SG-/.test(e)?`Event ${e}`:e}function kh(e){return{event_label:th,display_id:bh(e)}}function jh(e){return"requirement"===e.type&&e.data?.req_type===nh}function xh(e,t){if(!jh(e)||"analysis"!==t?.type)return!1;const n=t.data??null,r=n?.analysis_props?.variant;return vh(Fl("dfmea"===n?.analysis?.subtype?"dfmea":"hara","string"==typeof r?r:null,null),{analysis_props:n?.analysis_props})}function Sh(e,t,n){return"goal"===t||"hazard"===t?`${e} is a ${"goal"===t?"Safety goal item":"Hazard item"}, not a hazardous event row.${"atoms_link_mitigation"===n?" A mitigation links to a Safety goal item (SG-n), or to a hazardous event row, which redirects the link to the row's Safety goal.":""} Change its title or text with atoms_update_item; ${"goal"===t?"its ASIL, safe state and FTTI are recorded on the hazardous event rows that cite it (atoms_fill_row on each row)":"its highest ASIL comes from the hazardous event rows that cite it"}. Nothing was written.`:`Item ${e} is not an analysis row (req_type must be 'safety-goal' or 'failure-mode')`}function $h(e){return e.map(e=>{const t=e.data??{};return{id:e.id,type:e.type,title:e.title??null,req_type:t.req_type,analysis_props:t.analysis_props??null,relationships:t.relationships??null,deleted_at:e.deleted_at??null}})}function Ah(e){const t=$h(e);return function(e,t){const n=q_.get(e);if(n&&n.links===t)return n.index;const r=function(e,t){const n=new Map;for(const t of e)n.set(t.id,t);const r=e=>T_(n.get(e)),a=e=>r(e)&&"goal"===n.get(e)?.type,i=new Map,s=new Map;for(const t of e){if(!R_(t))continue;const e=E_(t.relationships,"event_goal")[0],r=e?n.get(e):void 0;!e||r&&"goal"!==r.type||i.set(t.id,e);const a=E_(t.relationships,"event_hazard")[0];a&&s.set(t.id,a)}const o=(t,r,a)=>{for(const i of[...e].sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0))if(i.type===t)for(const e of E_(i.relationships,r)){const t=n.get(e);t&&R_(t)&&!a.has(e)&&a.set(e,i.id)}};o("goal","goal_events",i),o("hazard","hazard_events",s);const l=e=>{const t=new Map;for(const[n,a]of e){if(!r(n))continue;let e=t.get(a);e||t.set(a,e=[]),e.push(n)}for(const e of t.values())e.sort();return t},c=l(i),d=l(s),u=e=>mc(n.get(e)?.analysis_props),p=e=>{let t=-1;for(const n of e)t=Math.max(t,O_(u(n)));return t<0?"QM":I_[t]},m=new Set;for(const t of e)if(T_(t))if("test-case"===t.type)for(const e of E_(t.relationships,"verifies"))m.add(e);else for(const e of E_(t.relationships,"verified_by")){const r=n.get(e);T_(r)&&"test-case"===r.type&&m.add(t.id)}const f={get:e=>n.get(e)},_=e=>{const t=new Set;for(const r of e){const e=n.get(r);if(!e)continue;const a=d_(e,"hara_iso26262",f);"live"===a.state&&a.id&&t.add(a.id)}return[...t].sort()},h=t=>e.filter(e=>e.type===t&&T_(e)).map(e=>e.id).sort(),g=e=>a(e)?[...t.byRow.get(e)??[]].filter(r).sort():[];return{goalOf:e=>i.get(e)??null,hazardOf:e=>s.get(e)??null,rowsOfGoal:e=>c.get(e)??[],rowsOfHazard:e=>d.get(e)??[],goalAsil:e=>p(c.get(e)??[]),hazardAsil:e=>{const t=d.get(e)??[];return{level:p(t),count:t.length}},satisfiers:g,goalCoverage:(e,n)=>{const i=g(e),s=a(e)?c.get(e)??[]:[],o=n?s.filter(e=>n.includes(e)):s,l=new Set(i),d=new Set,p=[],f=[];for(const e of o){const n=(t.byRow.get(e)??[]).filter(r);for(const e of n)l.has(e)||d.add(e);O_(u(e))<=0||(0===i.length&&0===n.length?p.push(e):[...n,...i].some(e=>m.has(e))||f.push(e))}return{satisfiers:i,rowMitigators:[...d].sort(),uncoveredRows:p,untestedRows:f}},goalVerification:e=>{const n=g(e),i=new Set(n),s=new Map;for(const n of a(e)?c.get(e)??[]:[])for(const e of t.byRow.get(n)??[]){if(!r(e)||i.has(e))continue;let t=s.get(e);t||s.set(e,t=new Set),t.add(n)}const o=[...n,...s.keys()].sort((e,t)=>e<t?-1:e>t?1:0).map(e=>({id:e,verified:m.has(e),viaRows:[...s.get(e)??[]].sort()}));return{requirements:o,verified:o.filter(e=>e.verified).length,total:o.length}},directMitigators:e=>[...t.byRow.get(e)??[]],rowMitigated:e=>{if((t.byRow.get(e)??[]).length>0)return!0;const n=i.get(e);return!!n&&g(n).length>0},requirementVerified:e=>m.has(e),hazardFunctions:e=>_(d.get(e)??[]),goalFunctions:e=>_(c.get(e)??[]),hazardGoals:e=>[...new Set((d.get(e)??[]).map(e=>i.get(e)).filter(e=>!!e&&a(e)))].sort(),hazardIds:h("hazard"),goalIds:h("goal"),isLiveId:r}}(e,t);return q_.set(e,{links:t,index:r}),r}(t,function(e){const t=[],n=[];for(const r of e)if(T_(r)){t.push({id:r.id,type:r.type,data:{req_type:r.req_type,analysis_props:r.analysis_props}});for(const e of E_(r.relationships,"mitigated_by"))n.push({from_id:r.id,to_id:e,type:"mitigated_by"});for(const e of E_(r.relationships,"mitigates"))n.push({from_id:r.id,to_id:e,type:"mitigates"})}return{byRow:tf(t,n)}}(t))}async function Ih(e,t){return await Sn(()=>e.from("items").select("id, title, type, data").eq("project_id",t).is("deleted_at",null),pn)}async function qh(e,t,n,r){const a=E_(n,"event_goal")[0];if(!a)return[];const i=await r(a);if(!i||"goal"!==i.type)return[];const s=[];for(const e of E_(i.data?.relationships,"mitigated_by")){const t=await r(e);t&&s.push(t)}const o=await af(e,t),l=[{id:i.id,type:i.type,data:{}}],c=[];for(const e of s)l.push({id:e.id,type:e.type,data:{req_type:e.data?.req_type}}),c.push({from_id:i.id,to_id:e.id,type:"mitigated_by"});const d=new Set(l.map(e=>e.id));for(const e of o){d.has(e.id)||(d.add(e.id),l.push({id:e.id,type:e.type,data:{req_type:e.req_type}}));for(const t of E_({mitigates:e.mitigates},"mitigates"))c.push({from_id:e.id,to_id:t,type:"mitigates"})}const u=[];for(const e of tf(l,c).get(i.id)??[]){const t=s.find(t=>t.id===e)??await r(e);t?.data?.asil_source===a&&u.push(e)}return u}var Mh,Oh,Eh,zh,Rh,Th,Ch,Ph,Dh,Nh=P({"src/core/hazard-goal-tools.ts"(){Di(),Wc(),Nl(),$o(),rh(),kr(),hf(),D_=["requirement","test-case","note","function","hazard","goal","safety_goal"],N_=`Item type. function only where Function items are on. ${P_="hazard and goal: ISO 26262 (automotive) projects only; in a medical device project hazards are rows of the ISO 14971 risk analysis"}; a Standard project takes neither. safety_goal is another name for goal (a Safety goal item, SG-n); a hazard is HAZ-n.`,H_="ISO 26262 HARA only, where Hazard and Safety goal items are on (automotive only): the Hazard item (HAZ-n) every new row cites. Refused on any other analysis.",F_="ISO 26262 HARA only, where Hazard and Safety goal items are on (automotive only): the Safety goal item (SG-n) every new row cites. Refused on any other analysis.",L_='Hazard and Safety goal items (ISO 26262, automotive only, where they are on): a HARA created there is stamped (event_model hazard_goal) and its rows are hazardous events with HE-n ids. On such a row, hazard_id and goal_id name its Hazard item (HAZ-n) and its Safety goal item (SG-n), one each ("" clears it); the row\'s hazard and safety_goal text is then read-only. A write that changes either on an approved row clears the approval and answers approval_cleared: true. hazard_id and goal_id are refused on any other row: an unstamped HARA, an ISO 14971 risk analysis (it keeps its hazardous situations as row text) and a security risk analysis keep a hazard and a safety_goal text, and a DFMEA, PFMEA, Software FMEA or Use FMEA row has neither field.',U_='On a stamped HARA (event_model hazard_goal) each row also carries hazard_id, goal_id and goal_asil (the highest event ASIL over the live rows citing the goal), goal_display, event_label ("Hazardous event") and display_id ("Event SG-n" for a row that kept its SG id). A row rated ASIL A to D is a gap (is_gap true, and is_critical true at C or D) when no requirement covers it: none is linked to the row itself and none satisfies its live Safety goal; gap_rule then names the goal. A covered row is not a gap, whether or not a test case verifies its requirements (atoms_get_gaps reports a covered untested row under its goal). A row with no live goal (no goal, or its goal in Trash) is covered only by a requirement linked to it. counts.gaps is the number of rows whose own gap rule matched (is_gap true, the rows atoms_get_gaps lists in gaps) and counts.critical the critical ones; it is not the number of gap lines, so a Safety goal with 3 uncovered rows adds 3 to counts.gaps and 1 to the count of atoms_get_gaps. atoms_get_analysis returns no gap_kinds list: it returns gap_rule per row and, in acceptance.open_gaps_at_acceptance, the kinds that were open when the analysis was accepted; for the gap kinds open now and their total call atoms_get_gaps.',W_="On a stamped HARA (event_model hazard_goal) the gap kinds are row_no_goal, goal_no_safety_req, goal_no_test, hazard_uncited and goal_trashed (the last two informational, not counted), beside the HARA's own no_parent, catalog_draft and not_accepted. A goal is judged row by row over the analysis's rows rated ASIL A to D that cite it: a row is covered by a requirement satisfying the goal or one linked to the row itself, and tested when one of those is verified by a test case. goal_no_safety_req lists the uncovered rows and goal_no_test the covered untested ones; a goal with both raises both, 1 gap each. A row with no live goal (no goal, or its goal in Trash) stands as its own goal: row_no_goal when no requirement is linked to it, goal_no_test when none of those is verified; a row whose goal is in Trash is also listed under goal_trashed. A row's own test case never counts on a stamped HARA. On a stamped HARA, count is the sum of the gap_count of the counted kinds, so it is neither a row count nor a goal count: row_no_goal counts rows, goal_no_safety_req and goal_no_test count goals, once per goal per kind (a goal with both uncovered and covered untested rows counts once in each, and each kind names the rows that raise it, so 3 rows citing 1 goal are 1), goal_no_test also counts each row with no live goal that is linked to requirements none of which is verified, no_parent counts requirements, and catalog_draft and not_accepted count 1 each and name nothing. gaps lists only the rows whose own gap rule matched, so count can differ from gaps.length, and counts.gaps of atoms_get_analysis is that row number, not count. A gaps entry carries no hazard_id or goal_id: read them with atoms_get_analysis.",V_="row_id may name a Safety goal item (SG-n, where Hazard and Safety goal items are on): the safety requirement then satisfies the goal and takes its ASIL (asil and asil_source in the answer). A link added to a hazardous event row that cites a live Safety goal goes to that goal (redirected_from names the row). A hazardous situation row of an ISO 14971 risk analysis links as before.",B_='A Hazard item (HAZ-n) also carries safety: { highest_asil, event_count, events, functions, goals } and a Safety goal item (SG-n) safety: { asil, source_rows, events, functions, satisfied_by, verified_satisfiers, row_mitigators, uncovered_rows, untested_rows }, derived from the hazardous event rows that cite it. satisfied_by and verified_satisfiers are the goal\'s own links; row_mitigators are the requirements linked to its rows directly. uncovered_rows are the rows rated ASIL A to D that neither a requirement satisfying the goal nor one linked to the row covers (goal_no_safety_req); untested_rows are the covered ones with none of those requirements verified by a test case (goal_no_test, raised beside goal_no_safety_req when the goal also has uncovered rows). A row\'s own test case is not a test of its goal. verification: { verified, total, requirements } is the goal\'s verification rollup: every live requirement linked to the goal or to a live row citing it, each once, verified when a live test case verifies it; each entry is { id, verified, via_rows, text }, via_rows naming the rows it was counted through (empty for a requirement linked to the goal itself) and text saying so ("REQ-020 verified via Event SG-001"). satisfied_by and verified_satisfiers keep counting the goal\'s own links. A hazardous event row of a stamped HARA (a requirement, req_type safety-goal) also carries event_label ("Hazardous event") and display_id ("Event SG-n" for a row that kept its SG id), so it is not read as the Safety goal item with the same id.',G_=["requirement","test-case","note","table","analysis","function","hazard","goal"],J_="Could not read whether this project takes Hazard and Safety goal items, so nothing was written. Send the same call again in a moment.",Q_=["event_hazard","hazard_events","event_goal","goal_events"],Y_={hazard_id:"event_hazard",goal_id:"event_goal"},K_={event_hazard:"hazard",event_goal:"goal"},Z_={event_hazard:"hazard",event_goal:"safety_goal"},X_={event_hazard:"hazard_id",event_goal:"goal_id"},eh=new Set(["safe_state","ftti"]),th="Hazardous event",nh="safety-goal"}});function Hh(e){if(e.title)return e.title;const t=e.data??{},n=t.req_type;if("requirement"!==e.type||"safety-goal"!==n&&"failure-mode"!==n)return e.title??"";const r=t.analysis_props??{};return["safety-goal"===n?r.source_function:r.source_req,r.failure_mode].filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim()).join(", ")||e.id}function Fh(e,t){return"mitigated_by"===e.type&&"goal"===t(e.from_id)||"mitigates"===e.type&&"goal"===t(e.to_id)?{...e,from_id:e.to_id,to_id:e.from_id}:e}function Lh(e,t){const n=Co(e.data);return xh(e,n?t.get(n):void 0)?kh(e.id):{}}function Uh(e){return Math.min(Math.max(e??5,1),10)}var Wh,Vh,Bh,Gh,Jh,Qh,Yh,Kh=P({"src/core/trace-graph.ts"(){Nl(),vd(),Nh(),Mh=new Set(["parent","verifies","mitigated_by","allocated_to","event_hazard","goal_events"]),Oh=new Set(["child","verified_by","mitigates","allocated_from","hazard_events","event_goal"]),Eh=["allocated_to","allocated_from"],zh={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",mitigated_by:"mitigates",mitigates:"mitigated_by",allocated_to:"allocated_from",allocated_from:"allocated_to",event_hazard:"hazard_events",hazard_events:"event_hazard",event_goal:"goal_events",goal_events:"event_goal",related:"related"},Rh=["parent","verifies","mitigated_by","traces_to","allocated_to","decomposed_from","event_hazard","goal_events"],Th=["child","verified_by","mitigates","allocated_from","decomposes_to","traced_by","hazard_events","event_goal"],Ch={...zh,traces_to:"traced_by",traced_by:"traces_to",allocated_to:"allocated_from",allocated_from:"allocated_to",decomposes_to:"decomposed_from",decomposed_from:"decomposes_to",event_hazard:"hazard_events",hazard_events:"event_hazard",event_goal:"goal_events",goal_events:"event_goal"},Ph="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_to and decomposed_from upstream, traced_by, allocated_from and decomposes_to downstream, so a Function is upstream of the requirements allocated to it. The Hazard and Safety goal lanes of an ISO 26262 project are followed too: event_hazard and goal_events upstream, hazard_events and event_goal downstream (a Hazard leads to its hazardous events, an event to its Safety goal), and the safety requirements that satisfy a Safety goal are downstream of it. 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.",Dh="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. allocated_to and allocated_from links (a requirement and its Function) are followed only when relationship_types names them: a requirement's Function is upstream of it. The Hazard and Safety goal lanes are followed by default: a hazardous event's Hazard is upstream of it (event_hazard), its Safety goal downstream (event_goal), and the safety requirements that satisfy a Safety goal are downstream of the goal. A node that is a hazardous event row of a stamped HARA also carries event_label (\"Hazardous event\") and display_id (\"Event SG-n\" for a row that kept its SG id), so it is not read as the Safety goal item with the same id. affects and affected_by links are not followed yet, so a relationship_types filter of only those returns just the starting item."}});function Zh(e){return"string"!=typeof e||""===e.trim()||Vh.has(e)?null:e}function Xh(e){return!e||"object"!=typeof e||Array.isArray(e)?null:Zh(e.reason)}function eg(e){return"string"==typeof e&&""!==e.trim()?e:null}function tg(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}function ng(e){return e.diff_summary&&"object"==typeof e.diff_summary?e.diff_summary:{}}function rg(e,t){const n=ng(e).author;if(n&&"object"==typeof n){const{kind:e,client:t}=n;if("agent"===e){const e="string"==typeof t?t.trim().toLowerCase():"";return["claude","cursor","copilot"].includes(e)?`mcp_${e}`:"mcp_claude"}if("person"===e)return"user"}if("mcp"===e.event_source||"restore"===e.event_source&&e.event_session_id){const n=e.event_session_id?t?.get(e.event_session_id):void 0;return n&&Yh.has(n)?n:"mcp_claude"}return"user"}function ag(e,t,n){return e.flatMap((r,a)=>{const i=e[a+1]??null,s=1===r.revision_number||null===i,o="system"===r.event_source?"system_normalization":1===r.revision_number?"created":"updated",l=s?["(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}(tg(i?.fields_snapshot),tg(r.fields_snapshot)),c=function(e){const t=function(e){if(!e||"object"!=typeof e)return null;const t=e.migration;return t&&"object"==typeof t&&!Array.isArray(t)?t:null}(e);if(!t)return null;const n=eg(t.from_tag),r=eg(t.function_id);return"function_items"===t.kind&&n?`Created from function tag "${n}"`:"function_items_link"===t.kind&&r?`Function linked to ${r} by conversion`:"function_items_unlink"===t.kind&&r?`Function link to ${r} removed by revert`:"hazard_goal_model"===t.kind?Gh:"hazard_goal_model_revert"===t.kind?Jh:eg(e.history)??Bh}(r.diff_summary),d=Xh(r.diff_summary)??n?.get(r.id)??null,u={id:r.id,event_type:o,changed_by:null===c?r.changed_by??null:null,changed_at:r.valid_from,actor:null!==c?"system":rg(r,t),session_id:r.event_session_id??null,fields_changed:l,...null!==c?{summary:c}:{},...null!==d?{reason:d}:{}},p=function(e){const t=ng(e),n=function(e){return Array.isArray(e.ops)?e.ops.flatMap(e=>{if(!e||"object"!=typeof e)return[];const{kind:t,status:n}=e;return"string"!=typeof t||void 0!==n&&"applied"!==n&&"replaced"!==n?[]:[t]}):null}(t);return{trashed:"trashed"===t.lifecycle||(n?.includes("trash_item")??!1),restored:"restored"===t.lifecycle||(n?.includes("restore_item")??!1)||null===n&&!0===t.restored&&void 0===t.baseline_id,otherOps:null===n?null:n.some(e=>!Qh.has(e))}}(r);if(null!==c||!p.trashed&&!p.restored)return[u];const m=1===r.revision_number||(p.otherOps??(null!==i&&l.length>0)),f=(e,t)=>({...u,id:`${r.id}:${e}`,event_type:e,changed_at:t,fields_changed:[`(${e})`]});return[...p.trashed?[f("deleted",r.valid_to??r.valid_from)]:[],...m?[u]:[],...p.restored?[f("restored",r.valid_from)]:[]]})}function ig(e,t,n,r=0){const a=n>t;return{total_count:n>0?Math.max(e,r+Math.min(n,t)):e,limit:t,offset:r,has_more:a,...a?{next_offset:r+t}:{}}}var sg,og,lg=P({"src/core/history.ts"(){Wh="Change rationale, shown with the change in atoms_get_history and on its History line in the app",Vh=new Set(["item_deleted","endpoint_deleted","endpoint_restored","endpoint_removed_by_change"]),Bh="Changed by a data migration run",Gh="Moved to the Hazard and Safety goal model by conversion",Jh="Moved back from the Hazard and Safety goal model by revert",Qh=new Set(["trash_item","restore_item"]),Yh=new Set(["mcp_claude","mcp_cursor","mcp_copilot"])}});function cg(e){return`Paging: offset (integer, optional, default 0) and limit (integer, optional, 1 to 1000, default 1000) page ${e}; meta carries total_count, offset, has_more and, when more remain, next_offset. Call again with offset=next_offset until has_more is false to read every entry; a page the 25,000-character cap cuts says so the same way.`}var dg=P({"src/core/tool-descriptions.ts"(){Zm(),hf(),kf(),$f(),Vf(),Kh(),lg(),B(),uo(),Nh(),sg="Paging: meta carries next_offset while more remain. Call again with offset=next_offset (not offset + limit) until has_more is false: a page the 25,000-character cap cuts holds fewer rows than limit, and its next_offset starts right after the last row it returned.",og={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"|"viewer_only", 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 required.\n\nReturns:\n { status: "success", data: [{ id, name, description, org_id, org_name, created_at }], meta }\n\n${cg("the project list (newest first)")}\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|analysis|function\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, needs_rerun? }], meta: { total_count, limit, offset, has_more, next_cursor?, next_offset? } }\n next_offset (on an offset page while more remain) is the offset of the next page; next_cursor pages by after.\n\n${zf}\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. meta.relationship_counts says how many ids each\n non-empty lane of relationships holds. An item with thousands of links answers a text preview (meta.truncated true):\n the lanes are still counted there, and atoms_trace (depth 1, paged by next_offset) or atoms_impact_analysis reads them.\n\n${zf}\n\n${fm}\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. ${j}\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")\n\n${B_}`,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 },\n covered_by_document?: { count, ids }, uncovered_items: [...] }, meta\n The counts are the whole project's (or filter's); uncovered_items is one page.\n\n${cg("uncovered_items")}\n\n${Ym}\n\n${ff}\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, or a model design's MD id (MD-001) for that design's history\n - limit (number, optional): Max entries (default 20, max 100)\n - offset (number, optional): How many revisions to skip from the newest (default 0)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed, newest first;\n meta { total_count, limit, offset, has_more, next_offset? }. offset and next_offset count revisions: a revision\n that moved the item to Trash or restored it gives more than one entry, and a page never splits one.\n For an MD id: entries newest first with changed_by_name, version, source (web or mcp), agent_label,\n summary (what changed: boxes, arrows and groups added, removed or renamed, links added or removed, the name,\n the description, editors, Trash) and summary_line, the sentence the app's History shows.\n\n${sg}`,atoms_export_mermaid:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Every edge is labelled with what it is\n(parent of, verified by, mitigates, cites hazard, cites goal, allocated to, related to).\nA solid edge is a link the project expects; a dotted edge adds context.\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, note or Function 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|function. atoms_create_item type 'function' creates a Function item (FN-nnn), the function a HARA or risk analysis row names by its id, in a project with Function items turned on; it takes no req_type (REQ-MCS-425) hazard|goal|safety_goal: ${P_}. safety_goal is the same as goal (a Safety goal item, SG-n); a hazard is HAZ-n\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 function tag 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. ${x} ${q}`,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 function tag is not a domain and is rejected), level?, status?, req_type?, fields?, steps?, params?, expected_updated_at?\n - ${ym}\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). ${mm}\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): ${Wh}\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?: the same rationale for every item 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: ${j}\nidempotency_key: ${x}\n${q}`,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|function (a Function only in a project with Function items turned on; its parent_id must be a Function); hazard|goal|safety_goal: ${P_}\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 function tag 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 An item takes only these fields: any other, such as runs, is refused by name and nothing is written.\n\nReturns:\n { created: number, items: [{ id, title, type }], errors: [], link_warnings?: [{ child_id, parent_id, message }], warning? }\n items names every created item, in input order (REQ-MCS-670); when the answer is large, title is left out of\n each entry (it is the title you sent) and only errors may be shortened. link_warnings names each created item\n not yet listed under its parent_id (another writer held the link): relink it with atoms_link_items, do not\n import it again. An import whose every row names a parent locked for agents creates nothing and is an error.\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. ${x} ${q}`,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. A release_note\n when no release_id was sent: ${rm}\n\n${om}\n\n${lm}\n\n${sm}\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. A release_note (with no_release_entries) when any entry\n carried no release_id: that run counts toward no Release.\n\n${om}\n\n${lm}\n\n${sm}\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${Dh}\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], edges, total_count }, meta\n total_count counts the whole trace; items is one page (root first) and edges holds the links whose two ends are the\n root or an item of the page.\n\n${cg("items")}\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, next_offset? }\n\n${sg}`,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, already_referenced_by_items, warning? }\nReturns (array): { batch_id, created, variables, message, already_referenced_by_items, warning? }\nalready_referenced_by_items counts the live items whose body already cites the new name: they now read its value,\nand warning says so. Tell the user before relying on it.',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\nOnly an org admin of the project\'s organization can create a field definition.\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|function); 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, rerun: { requirements, test_cases }, recent_changes, last_updated }\n\n${Rf}\n\n${Km}\n\n${_f}\n\n${bf}\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, analysis, function)\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, next_offset? } }\n\n${sg}\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, default true): also list the items that share a {variable} with the item (no relationship needed), each with shared_variables naming every variable it shares.\n\n${Ph}\n\nReturns:\n { root: { item_id, title, type }, impacted_items: [{ item_id, title, type, depth, relationship_path, shared_variables }], summary: { total_impacted, by_type, max_depth_reached } }\n shared_variables is the sorted names of the variables the item shares with the root: an empty list when it shares none or include_variable_refs is false.\n summary counts the whole impact set; impacted_items is one page.\n\n${cg("impacted_items")}\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)\n\nReturns:\n { baselines: [...], total, offset, limit }, meta: { total_count, limit, offset, has_more, next_offset? }\n\n${sg}`,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\nWhen your organization requires confirmation for this tool, the preview also returns\n{ status: \"confirmation_required\", confirmation_token }, and confirm=true executes only\nwith that confirmation_token; without it confirm=true returns the preview again.\n\nArgs:\n - baseline_id (string, UUID)\n - confirm (boolean, optional, default false)\n - confirmation_token (string, optional): Token from the preview, when confirmation is required\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 naming the Function items it applies to by id (function_ids; a Function is created\nwith atoms_create_item type 'function'), or, for an entry written before the project turned Function\nitems on, the function tags it applies to (function_tags).\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, function_ids?}], acceptance }],\n meta: { total_count, limit, offset, has_more, next_offset? } }\n\n${sg}`,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_ids (string[]): the ids of the Function items this entry applies to (e.g. \"FN-001\"),\n each a live Function of this project (add_entry, edit_entry, tag_entry). [] means the entry\n applies to every function and is accepted on any project: with Function items turned on it\n stores function_ids [] and clears any function tags the entry still holds from before the\n conversion; without them it stores the entry untagged (function_tags []), as the app does,\n and writes no Function id. A list that names ids leaves those old tags as they are (the ids\n decide). A list that names ids needs Function items turned on: a project\n without them refuses it (function_items_off); a person tags such an entry by function tag on\n the app's Scenario catalogs page. A Function is created with\n atoms_create_item type 'function'. function_tags, the name input, was removed in 0.62.0; an\n entry written before keeps the function_tags it holds.\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. rename_catalog does not; tag_entry does when it changes the entry's\n function_ids.",atoms_list_domains:"List the domain tags of a project's taxonomy, with item counts.\n\nA function tag (metadata.function_tags: the function names of a project that has not turned Function\nitems on, kept unchanged once it has) is not a domain: it is left out of this list, exactly as the\napp's domain picker leaves it out, because atoms_create_item, atoms_update_item and atoms_bulk_import\nrefuse it as a domain. A function is an item: list them with atoms_list_items type 'function' and\ncreate one with atoms_create_item type 'function', in a project with Function items turned on.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { domains: [{ name, registered, item_count }], total, registered_count, unregistered_count, note? }\n registered: false marks a tag found on items but not in the taxonomy (an orphan); a function tag\n an item still carries is never counted as an orphan.",atoms_create_domain:'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 tag is refused (a function is not a domain tag). A function is an\nitem: create one with atoms_create_item type \'function\', in a project with Function items turned on.\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 }',atoms_update_domain:'Rename a domain tag.\n\nUpdates 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\nA domain never becomes a function: a function is an item, created with atoms_create_item type \'function\' in a project with Function items turned on.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Current domain name\n - new_name (string): New domain name\n - dry_run (bool, optional): If true, return the impact without making changes (default false)\n\nReturns (dry_run=false):\n { domain: { name }, renamed_from, items_updated, message }\n\nReturns (dry_run=true):\n { dry_run: true, rename: { from, to }, items_affected, message }',atoms_delete_domain:"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 }",atoms_create_analysis:`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 or a risk analysis is seeded from FUNCTIONS, never from requirements: a requirement is an\noutput of the analysis. A Function is an item: atoms_create_item type 'function' creates one, in a\nproject with Function items turned on, and its id seeds a row (source_function_ids). A security\nrisk analysis is seeded from its asset names (source_assets), which stay text. A dfmea (DFMEA or\nFMEA) is seeded from requirements / 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);\n Standard offers no analyses, so every analysis is refused there. 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, and so is a Standard one.\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_function_ids (string[], HARA or risk analysis only, max 50): the ids of the Function items\n to seed rows from (e.g. "FN-001"), one row each. Each must be a live Function of this project\n (atoms_list_items type 'function'); a project without Function items turned on refuses them\n (function_items_off). Each row stores the id and the Function's title as its label. Nothing is\n written to the project's tags. Rejected for dfmea and for a security risk analysis.\n - source_assets (string[], security risk analysis only, max 50): the asset names to seed rows\n from, kept as text on each row (an asset is never a Function). Rejected for every other scheme.\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, source_function_id?, source_function_title? }] (hara) | [{ id, source_req }] (dfmea),\n link_warnings?: [{ row_id, source_function | source_req, message }], warning? }\n A row seeded from a Function carries its id and title; a row seeded from an asset its name.\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 - Writes nothing to the project's tags or function tags (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\n${L_}`,atoms_fill_row:`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,\nsecurity_control (the names the app's columns carry; they write the same fields as failure_mode,\noperating_scenario, effect, hazard and safety_goal, which are accepted too, and sending both names of\none field in one call is refused),\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, rationale and title. It\nrefuses p1, p2, occurrence and detection by name (those belong to the other schemes).\n\nA medical risk analysis row (RSK-n) accepts harm, hazardous_situation, sequence_of_events (the\nnames its columns carry; they write the same fields as hazard, effect and operating_scenario, which\nare accepted too, and sending both names of one field in one call is refused). Note that the stored\nkey hazard is the Harm column: the hazard itself is failure_mode.\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_id, 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_id,\n safety_goal (the risk control statement), s_rationale, p1_rationale, p2_rationale,\n residual_s, residual_p1, residual_p2, benefit_note, effect, title\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 and medical risk analysis source_function_id: the id of the Function item the row analyzes\n (e.g. "FN-001"), a live Function of this project (atoms_list_items type 'function'; create one\n with atoms_create_item type 'function'). The row stores the id and the Function's title as its\n label. "" clears both (the row's Function) only on a project with Function items turned on.\n A project without them refuses an id and "" alike (function_items_off): there a row names its\n function by function tag, which MCP does not change, so a person clears it in the row panel's\n Function field in the ATOMS app. source_function, the name input, was removed in 0.62.0 and is\n refused on these rows; a security risk analysis row keeps source_function as its asset name (text).\n\nReturns:\n { row_id, subtype, written_fields, written_columns, computed_level, asil_propagated_to?, asil_propagation_failed?,\n approval_cleared?, source_function_id?, source_function_title? }\n written_columns pairs each written stored key with the column it filled ([{ key, label }], e.g.\n { key: "hazard", label: "Harm" } on a medical risk analysis row).\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 asil_propagation_failed names the requirements whose ASIL did not update although the row was\n saved (with a warning); repeat the same call to push the ASIL again.\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\n${L_}`,atoms_get_analysis:`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 source_function_id?, source_function_title? (a HARA or risk analysis row that names a\n Function item: its id, and that Function's title while it is live, else null) }],\n counts: { rows, gaps, critical, stale, approved, linked } }, meta\n The vocabulary lists are given once per analysis, never repeated per row. counts are the whole analysis's;\n rows is one page.\n\n${cg("rows")}\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.\n\n${U_}`,atoms_propose_rows:`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_id (string, HARA or risk analysis only): the id of the Function item these rows\n analyse (e.g. "FN-001"), a live Function of this project (create one with atoms_create_item\n type 'function'); each row stores the id and the Function's title as its label. A project\n without Function items turned on refuses it (function_items_off). A security risk analysis\n row names its asset in its own source_function key.\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 medical risk analysis row also takes harm, hazardous_situation,\n sequence_of_events for hazard, effect and operating_scenario). 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 source_function_id?, source_function_title?,\n rows: [{ id, written_fields, written_columns, 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\n${L_}`,atoms_suggest_field:"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, so on a\n medical risk analysis row also harm, hazardous_situation, sequence_of_events)\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, written_columns, source_function_id?, source_function_title?,\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 - A HARA or risk analysis row takes its Function by id: field source_function_id, as\n atoms_fill_row takes it (create a Function with atoms_create_item type 'function'). \"\" clears\n the row's Function only on a project with Function items turned on; a project without them\n refuses it (function_items_off), and a person clears it in the row panel's Function field in\n the ATOMS app. The field source_function, removed in 0.62.0, is refused on these rows.",atoms_link_mitigation:`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), asil_not_written? / control_type_not_written? and warning? (the link is\n saved but that write after it was refused because another write was on the item: call this\n tool again with the same arguments to finish) }\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\n\n${V_}`,atoms_get_gaps:`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 differ from gaps.length either way, which lists only the per-row gap rules (greater when a kind counts what no row rule lists, smaller when one goal line names several gap rows).\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 security: unmitigated, unassessed, not_verified, no_residual, no_justification, safety_no_hazard,\n safety_no_reason, no_parent, no_scope (no threat model method), no_overall (every row is\n controlled and residual-rated but the overall residual risk is not judged) and not_accepted\n (the analysis holds rows and is still a draft)\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 Functions (a HARA or medical risk analysis on a project in Function items mode only):\n function_not_analysed (each live Function no row names, in function_ids; gap_count is\n how many) and function_missing (rows naming a Function that is in Trash or gone)\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.\nA row of a stamped HARA that cites a live Safety goal is also covered by a requirement that\nsatisfies the goal. One rated ASIL A to D that neither covers is in the gaps list (its rule naming\nthe goal; atoms_get_analysis reads it is_critical at C or D) and is named by its goal's\ngoal_no_safety_req; a covered row whose\nrequirements no test case verifies is not in the gaps list (goal_no_test names it). So the gaps\nlist, is_gap, is_critical, counts and gap_kinds agree with the app row by row.\n\n${W_}`,...Gs}}});async function ug(e,t,n){const{data:r,error:a}=await e.rpc("verification_accepted_failures",{p_project_id:t,p_release_id:n});if(a)throw a;const i=r??{};return!0!==i.enabled?null:(Array.isArray(i.accepted_failures)?i.accepted_failures:[]).map(e=>{const t=e;return{test_case_id:String(t.test_case_id??""),requirement_ids:Array.isArray(t.requirement_ids)?t.requirement_ids.map(String):[],label:String(t.label??""),reason:String(t.reason??""),link:"string"==typeof t.link?t.link:null,accepted_by:String(t.accepted_by??""),accepted_at:String(t.accepted_at??"")}})}function pg(e,t){const n=new Set(t.acceptedTestIds),r=t.testsOf.get(e)??[];if(!r.some(e=>n.has(e)))return null;const a=r.filter(e=>!n.has(e));if(0===a.length)return{state:"accepted",stale:!1};const i=new Map(t.states.map(e=>[e.tc_id,e]));let s=0,o=0,l=0,c=0;for(const e of a){const t=i.get(e);t&&(s+=Number(t.leaves)||0,o+=Number(t.passed)||0,l+=Number(t.failed)||0,c+=Number(t.blocked)||0)}const d=l+c>0?"failing":0===o?"not-run":o===s?"verified":"incomplete",u=new Set(t.rerunOf.get(e)??[]),p=("verified"===d||"incomplete"===d)&&a.some(e=>u.has(e));return"verified"!==d||p?{state:d,stale:p}:{state:"accepted",stale:!1}}function mg(e,t){const n=[];return"accepted"===e?["accepted"]:("verified"!==e||t||n.push("verified"),"failing"===e&&n.push("failing"),"incomplete"!==e||t||n.push("incomplete"),"not-run"===e&&n.push("not_run"),t&&n.push("stale"),n)}function fg(e,t,n,r=new Set){if(!n)return e;const a={verified:0,failing:0,incomplete:0,not_run:0,stale:0,accepted:0};for(const e of t){if(r.has(e.requirement_id))continue;const t=pg(e.requirement_id,n);if(t){for(const t of mg(e.state,!0===e.stale))a[t]-=1;for(const e of mg(t.state,t.stale))a[e]+=1}}const i={...e};for(const[t,n]of Object.entries(a))"accepted"!==t&&0!==n&&(i[t]=(Number(e[t]??0)||0)+n);return i.accepted=a.accepted,i}var _g,hg,gg,yg,wg,vg=P({"src/core/accepted-failures.ts"(){}}),bg=P({"src/core/requirement-tree.ts"(){_g=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}});function kg(e){const t=e.source_item_id??"";switch(e.kind){case"parent_changed":return t?`Parent ${t} changed`:"Parent changed";case"hazard_changed":return t?`Hazard ${t} changed`:"Hazard changed";case"interface_changed":return t?`Interface ${t} changed`:"Interface changed";case"asil_raised":return t?`Hazard ${t} ASIL raised`:"ASIL raised";case"reparented":return"Parent link changed"}}function jg(e,t){const n=t?` in Release ${t}`:"";if(e.failed>0)return t?{id:e.id,action:"failed",reason:`Failed in Release ${e.failedFrom??t}`}:{id:e.id,action:"failed",reason:"Latest run failed"};const r=[];if(e.rerunFor.length>0&&r.push(`${function(e){const t=[...e].sort(),n=t.slice(0,3).join(", ");return t.length>3?`${n} +${t.length-3} more`:n}(e.rerunFor)} changed after its counted pass`),e.changedAfterPass&&r.push("The test changed after its counted pass"),r.length>0&&e.passed>0)return{id:e.id,action:"rerun",reason:r.join("; ")};if(e.leaves>0&&e.passed===e.leaves)return null;if(e.blocked>0)return{id:e.id,action:"not_run",reason:t?`Blocked${n}`:"Latest run blocked"};if(e.passed>0){const t=e.leaves-e.passed;return{id:e.id,action:"not_run",reason:`${t} of ${e.leaves} points not run${n}`}}return{id:e.id,action:"not_run",reason:t?`No counted run${n}`:"No run recorded"}}async function xg(e,t){try{const{data:n,error:r}=await e.rpc("rollout_state",{p_project_id:t});return!r&&!0===n?.[hg]}catch{return!1}}async function Sg(e,t){const n=await Sn(()=>e.from("items").select("id, req_type:data->req_type, verified_by:data->relationships->verified_by, children:data->relationships->children, parents:data->relationships->parents").eq("project_id",t).eq("type","requirement").is("deleted_at",null),pn),r=await Sn(()=>e.from("items").select("id, verifies:data->relationships->verifies").eq("project_id",t).eq("type","test-case").is("deleted_at",null),pn),a=new Set(r.map(e=>e.id)),i=new Map,s=(e,t)=>{if(!a.has(t))return;let n=i.get(e);n||i.set(e,n=new Set),n.add(t)},o=new Set(n.map(e=>e.id));for(const e of n)for(const t of yg(e.verified_by))s(e.id,t);for(const e of r)for(const t of yg(e.verifies))o.has(t)&&s(t,e.id);return{requirements:n,testsOf:i}}async function $g(e,t,n){const{requirements:r,testsOf:a}=await Sg(e,t),i=new Set(r.map(e=>e.id)),s=[...new Set([...a.values()].flatMap(e=>[...e]))].sort(),o=await On(s,r=>e.rpc("needs_attention_test_states",{p_project_id:t,p_release_id:n.releaseId,p_test_case_ids:r})),l=i.size>0?await Nf(e,t,i,n.releaseId):[],c=new Map;for(const e of l)for(const t of e.test_case_ids??[]){const n=c.get(t);n?n.push(e.requirement_id):c.set(t,[e.requirement_id])}const d=await Sn(()=>e.from("change_review_flags").select("id, item_id, kind, source_item_id").eq("project_id",t).is("cleared_at",null),["id"]),u=n.releaseId?await ug(e,t,n.releaseId):null,p=await gf(e,t),m=function(e){const t=new Set(e.map(e=>e.id)),n=new Map;for(const t of e)for(const e of _g(t.parents)){const r=n.get(e);r?r.push(t.id):n.set(e,[t.id])}const r=new Map;for(const a of e){const e=_g(a.children).filter(e=>t.has(e));r.set(a.id,[...new Set([...e,...n.get(a.id)??[]])])}return r}(r);return function(e){const t=new Map;for(const n of e.flags){const e=t.get(n.item_id);e?e.push(n):t.set(n.item_id,[n])}const n=new Map(e.tests.map(e=>[e.id,e])),r=new Set;for(const t of e.requirements)for(const e of t.testIds)n.has(e)&&r.add(e);const a=new Set(e.acceptedTestIds??[]),i=new Set(e.closedRequirementIds??[]),s=new Map;for(const t of e.requirements)if(t.plain)for(const e of t.testIds){const n=s.get(e);n?n.push(t.id):s.set(e,[t.id])}const o=e=>{const t=s.get(e)??[];return t.length>0&&t.every(e=>i.has(e))},l=[],c=new Set,d=new Set;for(const t of[...r].sort()){if(a.has(t))continue;const r=jg(n.get(t),e.releaseVersion);r&&(d.add(t),o(t)||(l.push(r),c.add(t)))}const u=new Map(e.requirements.map(e=>[e.id,e.childIds??[]])),p=new Map(e.requirements.map(e=>[e.id,e.testIds.filter(e=>n.has(e))])),m=new Set(e.requirements.filter(e=>e.plain).map(e=>e.id)),f=function(e,t,n,r){const a=t=>{const r=[],a=[],i=new Set([t]),s=[...e.get(t)??[]];for(;s.length>0;){const t=s.pop();if(!i.has(t))if(i.add(t),n(t))a.push(t);else{r.push(t);for(const n of e.get(t)??[])i.has(n)||s.push(n)}}return{reached:r,closed:a}},i=new Map,s=e=>{let n=i.get(e);if(void 0===n){const r=a(e);n=t(e).length>0||r.closed.length>0||r.reached.some(e=>t(e).length>0),i.set(e,n)}return n};return e=>{const{reached:n,closed:i}=a(e),o=new Set,l=[];for(const e of n){for(const n of t(e))o.add(n);r(e)&&0===t(e).length&&!s(e)&&l.push(e)}return{testIds:[...o].sort(),closed:i.sort(),untested:l.sort(),open:[...n].sort()}}}(u,e=>p.get(e)??[],e=>i.has(e),e=>m.has(e));let _=0,h=0;for(const r of e.requirements){const e=(t.get(r.id)??[]).slice().sort((e,t)=>(e.kind+(e.source_item_id??"")).localeCompare(t.kind+(t.source_item_id??""))),a=r.testIds.filter(e=>n.has(e)),s=[...new Set(e.map(kg))],o=i.has(r.id),u=0===a.length&&!o&&(r.childIds?.length??0)>0?f(r.id):null,p=u?.testIds??[],m=p.length>0||(u?.closed.length??0)>0,g=r.plain&&0===a.length&&!o&&!m;if(e.length>0?l.push({id:r.id,action:"review",reason:[...s,...g?["No linked test case"]:[]].join("; ")}):g&&l.push({id:r.id,action:"no_test",reason:"No linked test case"}),!r.plain)continue;_+=1;const y=m&&null!==u&&0===u.untested.length&&!r.rerunOverSubtree&&p.every(e=>!d.has(e));0===e.length&&(o||a.length>0&&a.every(e=>!c.has(e))||y)&&(h+=1)}return{items:l.sort(gg),requirementsTotal:_,requirementsDone:h}}({releaseVersion:n.releaseVersion,...u?{acceptedTestIds:u.map(e=>e.test_case_id)}:{},...p?{closedRequirementIds:p.map(e=>e.requirement_id)}:{},requirements:r.map(e=>({id:e.id,plain:!("string"==typeof e.req_type&&Sp.includes(e.req_type)),testIds:[...a.get(e.id)??[]].sort(),childIds:m.get(e.id)??[]})),tests:o.map(e=>({id:e.tc_id,leaves:Number(e.leaves)||0,passed:Number(e.passed)||0,failed:Number(e.failed)||0,blocked:Number(e.blocked)||0,rerunFor:c.get(e.tc_id)??[],changedAfterPass:!0===e.changed_after_pass,failedFrom:e.failed_from??null})),flags:d.filter(e=>i.has(e.item_id)).map(e=>({item_id:e.item_id,kind:e.kind,source_item_id:e.source_item_id??null}))})}async function Ag(e,t){try{const{data:n,error:r}=await e.from("baselines").select("id, release_version, release_status, snapshot_at").eq("project_id",t).is("deleted_at",null);if(r)return null;const a=Pf(n);return a?{id:a.id,release_version:a.release_version??null,release_status:a.release_status??null}:null}catch{return null}}async function Ig(e,t,n){if(!await xg(e,t))return{};const r=n?{releaseId:n.id,releaseVersion:n.release_version}:await async function(e,t){const n=await Ag(e,t);return n?{releaseId:n.id,releaseVersion:String(n.release_version??"")}:{releaseId:null,releaseVersion:null}}(e,t);return{needs_attention:(a=await $g(e,t,r),a.items.map(e=>({id:e.id,action:e.action,reason:e.reason})))};var a}var qg,Mg,Og,Eg,zg,Rg,Tg,Cg,Pg,Dg,Ng,Hg,Fg,Lg,Ug,Wg,Vg,Bg,Gg,Jg=P({"src/core/needs-attention.ts"(){kr(),Rp(),Vf(),vg(),kf(),bg(),hg="needs_attention",gg=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,yg=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):"string"==typeof e?[e]:[],wg="needs_attention (only where the project's Needs attention worklist is switched on; absent otherwise): the app's Needs attention list, one entry per item that is not done in the scope read (the current Release, or every recorded run when the project has none, as the Matrix reads it; release_id picks another Release): {id, action, reason}. action is review (a requirement flagged because its parent, its hazard, its interface or its parent link changed, or its ASIL rose), rerun (a test case whose counted pass a change made out of date), failed (its counted run failed), not_run (no counted run, or not every point run) or no_test (a requirement with no linked test case and no descendant requirement with one or with a document closure: a parent is read over its children, as the Matrix rolls it up, and is not done while a child has no test). Its length is the count the app's sidebar shows beside Needs attention."}});function Qg(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return String(e);const n=new Date(t).toISOString();return`${n.slice(0,10)} ${n.slice(11,16)} UTC`}function Yg(e){if(!e)return"";const t=Date.parse(e);return Number.isNaN(t)?String(e):new Date(t).toISOString().slice(0,10)}function Kg(e){return String(e??"").replace(/\s+/g," ").trim()}function Zg(e,t){return`Tested in ${e}: ${t.map(e=>`${e.id} passed${e.build?`, Build ${Kg(e.build)}`:""}`).join("; ")}`}function Xg(e){return`Unchanged since run ${e.test_case_id?`${e.test_case_id} (${Yg(e.run_at)})`:`of ${Yg(e.run_at)}`} on ${e.version}, Build ${e.build?Kg(e.build):"(none)"}`}function ey(e){return`Closed by document "${Kg(e.document_name)}" (${e.link?`link ${Kg(e.link)}, `:""}closed by ${Kg(e.closed_by)} on ${Qg(e.closed_at)})`}function ty(e){const t=Kg(e.reason),n=e.link?`${t.replace(/\.$/,"")}. Bug: ${Kg(e.link)}`:t;return`${e.label}. Reason: ${n} (accepted by ${Kg(e.accepted_by)} on ${Qg(e.accepted_at)})`}function ny(e,t){const n=function(e){return{verified:e.verified.tested.length+e.verified.earlier.length+e.verified.documents.length,anomalies:e.known_anomalies.tests.length,notDone:e.not_done.requirements.length+e.not_done.tests.length}}(e),r=e.release_version,a=[`# Release ${r} report: ${Kg(e.project_name)}`,""];a.push(`- **Release:** ${r} (snapshot "${Kg(e.release_name)}")`),a.push(`- **Project:** ${Kg(e.project_name)}`),a.push(`- **Generated:** ${Qg(e.generated_at)}`),a.push(`- **Status:** ${function(e){return`Final, stored ${Qg(e.stored_at)} (server time). SHA-256 of the stored report: ${e.sha256}`}(t)}`);for(const t of e.notes)a.push("",`_Note: ${Kg(t)}_`);a.push("",`## ${Og[0]} (${n.verified})`),a.push("",`### Tested in this Release (${e.verified.tested.length})`,""),0===e.verified.tested.length&&a.push(Tg);for(const t of e.verified.tested)a.push(Rg(t.id,t.title,Zg(r,t.tests)));a.push("",`### Verified in an earlier Release (${e.verified.earlier.length})`,""),0===e.verified.earlier.length&&a.push(Tg);for(const t of e.verified.earlier)a.push(Rg(t.id,t.title,Xg(t)));a.push("",`### Closed by document (${e.verified.documents.length})`,""),0===e.verified.documents.length&&a.push(Tg);for(const t of e.verified.documents)a.push(Rg(t.id,t.title,ey(t)));a.push("",`## ${Og[1]} (${n.anomalies})`,""),0===e.known_anomalies.tests.length&&a.push(Tg);for(const t of e.known_anomalies.tests)a.push(Rg(t.test_case_id,t.title,ty(t)));if(e.known_anomalies.requirements.length>0){a.push("",`Requirements accepted for ${r} (${e.known_anomalies.requirements.length}):`,"");for(const t of e.known_anomalies.requirements)a.push(Rg(t.id,t.title,t.label))}a.push("",`## ${Og[2]} (${n.notDone})`),a.push("",`### Requirements (${e.not_done.requirements.length})`,""),0===e.not_done.requirements.length&&a.push(Tg);for(const t of e.not_done.requirements)a.push(Rg(t.id,t.title,`${t.mark}. ${Kg(t.reason)}`));a.push("",`### Tests (${e.not_done.tests.length})`,""),0===e.not_done.tests.length&&a.push(Tg);for(const t of e.not_done.tests)a.push(Rg(t.id,t.title,`${t.mark}. ${Kg(t.reason)}`));return a.push("",`## ${Og[3]}`,""),a.push(e.regression_note&&e.regression_note.trim()?e.regression_note.trim().split(/\r\n|[\r\n\u0085\u2028\u2029]/).map(e=>e.trim()?`> ${e}`:">").join("\n"):zg),a.push("","---","",Eg),a.join("\n")}async function ry(e,t,n,r){if(!r)return{};if(!n){const{data:n,error:r}=await e.rpc("rollout_state",{p_project_id:t});if(r)throw r;return!0===n?.[qg]?{release_report:null}:{}}const a=await async function(e,t,n){const{data:r,error:a}=await e.rpc("release_report_stored",{p_project_id:t,p_release_id:n});if(a)throw a;const i=r??{};return!0!==i.enabled?{enabled:!1}:{enabled:!0,release_id:String(i.release_id??n),release_version:Cg(i.release_version)?i.release_version:null,release_status:Cg(i.release_status)?i.release_status:null,regression_note:Cg(i.regression_note)?i.regression_note:null,final_report:i.final_report??null,final_report_sha256:Cg(i.final_report_sha256)?i.final_report_sha256:null,final_report_at:Cg(i.final_report_at)?i.final_report_at:null}}(e,t,n.id);if(!a.enabled)return{};const i={release_id:n.id,release_version:a.release_version??null};if(null!=a.final_report){const e=function(e){if(!Ng(e)||e.format!==Mg)return null;const{verified:t,known_anomalies:n,not_done:r}=e;return Cg(e.release_id)&&Cg(e.release_version)&&Cg(e.release_name)&&Cg(e.project_name)&&Cg(e.generated_at)&&Ng(t)&&Dg(t.tested,Fg)&&Dg(t.earlier,Lg)&&Dg(t.documents,Ug)&&Ng(n)&&Dg(n.tests,Wg)&&Dg(n.requirements,Vg)&&Ng(r)&&Dg(r.requirements,Bg)&&Dg(r.tests,Bg)&&Pg(e.regression_note)&&Dg(e.notes,Cg)?e:null}(a.final_report);if(!e||!a.final_report_sha256||!a.final_report_at)throw new Error(`release_report: the stored report of Release ${n.id} could not be read`);return{release_report:{...i,status:"final",stored_at:a.final_report_at,sha256:a.final_report_sha256,report_text:ny(e,{stored_at:a.final_report_at,sha256:a.final_report_sha256})}}}return{release_report:{...i,status:"released"===a.release_status?"draft":"not_stored",stored_at:null,sha256:null,report_text:null}}}var ay,iy,sy=P({"src/core/release-report.ts"(){qg="release_report",Mg=1,Og=["1. Verified","2. Known anomalies","3. Not done","4. Regression note"],Eg="ATOMS records names and server times. This is not a Part 11 signature.",zg="No Regression note was written when this Release was promoted.",Rg=(e,t,n)=>`- ${Kg(`${e} ${t}`)}: ${n}`,Tg="_None._",Cg=e=>"string"==typeof e,Pg=e=>null===e||"string"==typeof e,Dg=(e,t)=>Array.isArray(e)&&e.every(t),Ng=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Hg=e=>Ng(e)&&Cg(e.id)&&Pg(e.build)&&Pg(e.run_at),Fg=e=>Ng(e)&&Cg(e.id)&&Cg(e.title)&&Dg(e.tests,Hg),Lg=e=>Ng(e)&&Cg(e.id)&&Cg(e.title)&&Pg(e.test_case_id)&&Cg(e.version)&&Pg(e.build)&&Cg(e.run_at)&&Pg(e.tester),Ug=e=>Ng(e)&&Cg(e.id)&&Cg(e.title)&&Cg(e.document_name)&&Pg(e.link)&&Cg(e.closed_by)&&Cg(e.closed_at),Wg=e=>Ng(e)&&Cg(e.test_case_id)&&Cg(e.title)&&Cg(e.label)&&Cg(e.reason)&&Pg(e.link)&&Cg(e.accepted_by)&&Cg(e.accepted_at),Vg=e=>Ng(e)&&Cg(e.id)&&Cg(e.title)&&Cg(e.label),Bg=e=>Ng(e)&&Cg(e.id)&&Cg(e.title)&&Cg(e.mark)&&Cg(e.reason),Gg="include_report (only where the project's Release report is switched on; release_report is absent otherwise): release_report is the Release report of the Release read, {release_id, release_version, status, stored_at, sha256, report_text}. status final: the report was stored when the next Release was promoted, and report_text is that stored report as the Markdown the app downloads (sections 1. Verified, 2. Known anomalies, 3. Not done, 4. Regression note), with the server's stored_at and the database's SHA-256 of it. status draft: the current Release, whose report the app builds when a member downloads it and stores at the next promotion, so report_text is null. status not_stored: a replaced Release whose report was never stored, report_text null. release_report is null when there is no Release to read."}});function oy(e,t,n=ay){return(r,a)=>{if("unrecognized_keys"!==r.code)return{message:a.defaultError};const i=(r.keys??[]).join(", ");return{message:`${e} takes no ${i} on an entry of ${t}. Nothing was written. ${n}`}}}var ly,cy=P({"src/core/list-entry-fields.ts"(){ay="Send the entry again with only the fields this tool's schema lists.",iy="Create the items first, then set other fields with atoms_update_item and record each run with atoms_record_test_results (a run is stamped with server time; past run dates come in through an import in the ATOMS app)."}});var dy,uy,py,my=P({"src/apps/register.ts"(){ly={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});async function fy(e,t,n){if(!e||"function"!=typeof e.rpc)return null;if((uy.get(t)??0)>Date.now())return null;const r=await e.rpc(t,n);if(a=r?.error,a&&("PGRST202"===a.code||"42883"===a.code||/Could not find the function public\.mcp_/i.test(String(a.message??""))))return uy.set(t,Date.now()+dy),null;var a;if(r?.error)throw new Error(r.error.message??`${t} failed`);return r}function _y(e){return e.replace(/\*/g,"%")}async function hy(e,t,n){const r=await fy(e,"mcp_count_items",{p_project_id:t,p_type:n.type??null,p_domain_pattern:void 0!==n.domainPattern?_y(n.domainPattern):null,p_level_pattern:void 0!==n.levelPattern?_y(n.levelPattern):null,p_search_pattern:void 0!==n.search?(a=n.search,_y(`*${on(a)}*`)):null});var a;return r?py(r.data):null}var gy=P({"src/core/project-read-counts.ts"(){xn(),dy=6e5,uy=new Map,py=e=>{const t="string"==typeof e?Number(e):e;return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null}}});function yy(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString().replace(/Z$/,"999Z")}var wy=P({"src/core/as-of.ts"(){}});async function vy(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}))}async function by(e,t,n){const r=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||3===t.length&&kn(t[2]))&&"string"==typeof t[0]&&t[0].length>0&&"string"==typeof t[1]&&t[1].length>0)return 3===t.length?{created_at:t[0],id:t[1],total:t[2]}:{created_at:t[0],id:t[1]}}catch{}return null}(n.after):null;if(void 0!==n.after&&null===r)throw new jn;const a=void 0===r?.total,i=null!==r&&a,s=a=>{let i=e.from("items").select("*",a).eq("project_id",t).is("deleted_at",null);return r&&(i=i.or(function(e){return An(bn,e)}(r))),n.type&&(i=i.eq("type",n.type)),n.domain&&(i=i.filter("data->tags->>domains","ilike",dn(n.domain))),n.level&&(i=i.filter("data->tags->>level","ilike",cn(n.level))),i};let o=s(i?{count:"exact"}:void 0).order("created_at",{ascending:!0}).order("id",{ascending:!0});o=r?o.range(0,n.limit):o.range(n.offset,n.offset+n.limit);const[{data:l,error:c,count:d},u]=await Promise.all([un(o),r?Promise.resolve(null):hy(e,t,{type:n.type,domainPattern:n.domain?dn(n.domain):void 0,levelPattern:n.level?cn(n.level):void 0})]);if(c)throw new Error(c.message);let p=i?d:u;if(!r&&null===p){const e=await s({count:"exact",head:!0});if(e.error)throw new Error(e.error.message);p=e.count??null}const m=l??[],f=m.slice(0,n.limit),_=m.length>n.limit,h=r?.total??p??0,g=r&&a?void 0:h;return{items:f,totalCount:h,hasMore:_,nextCursor:_?En(f[f.length-1],g):void 0,cursorTotal:g}}async function ky(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 jy(e,t){if(t.baseline_id&&t.as_of)throw new Wt("baseline_id and as_of are mutually exclusive");if(t.as_of)return gn(yy(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 Wt("Baseline not found");if(n.project_id!==t.project_id)throw new Wt("Baseline does not belong to this project");return yn(t.baseline_id)}return null}async function xy(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 Sy(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 $y(e,t,n){return qn(e,t,n).catch(e=>{throw new Error(`projectStateAt: ${e.message}`)})}async function Ay(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 Sn(()=>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=n=>{let i=e.from("items").select("*",n).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${ln(a)},data->>body.ilike.${ln(a)},data->>summary.ilike.${ln(a)}`);return n?.head||(i=void 0===r.offset?i.limit(r.limit):i.order("id",{ascending:!0}).range(r.offset,r.offset+r.limit-1)),r.type&&(i=i.eq("type",r.type)),r.domain&&(i=i.filter("data->tags->>domains","ilike",dn(r.domain))),r.level&&(i=i.filter("data->tags->>level","ilike",cn(r.level))),i};if(i)return async function(e,t,n){const r=[];let a=0;for(let t=0;t<e.length;t+=wn){const{data:i,error:s,count:o}=await n(e.slice(t,t+wn));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({count:"exact"}).in("id",e));const[{data:o,error:l},c]=await Promise.all([un(s()),hy(e,t,{type:r.type,domainPattern:r.domain?dn(r.domain):void 0,levelPattern:r.level?cn(r.level):void 0,search:a})]);if(l)throw new Error(l.message);let d=c;if(null===d){const e=await s({count:"exact",head:!0});if(e.error)throw new Error(e.error.message);d=e.count??null}return{items:o??[],totalCount:d??0}}function Iy(e,t,n){return async function(){Bm>=Vm?await new Promise(e=>Gm.push(e)):Bm+=1;try{return await async function(e,t,n){let r,a,i;if(n.moment){const s=(await $y(e,t,n.moment)).map(Sy);r=s.filter(e=>"requirement"===e.type),a=s.map(e=>({id:e.id,type:e.type,data:e.data})),i=[]}else a=(await Sn(()=>e.from("items").select(Wm).eq("project_id",t).is("deleted_at",null),pn)).map(rf),r=a.filter(e=>"requirement"===e.type),i=await Sn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t),mn);const s=r.filter(e=>!(n.domain&&!(e.data?.tags?.domains??[]).some(e=>uc(e)===uc(n.domain))||n.level&&Vl(e.data?.tags?.level)!==Vl(n.level))),o=qf(a,i),l=ef(a,o),c=s.filter(e=>l.has(e.id)),d=s.filter(e=>!l.has(e.id)),u=nf(a,o);return{covered:c,uncovered:d,total:s.length,mitigators:u}}(e,t,n)}finally{const e=Gm.shift();e?e():Bm-=1}}()}var qy=P({"src/db/queries.ts"(){xn(),gy(),Wc(),hf(),kr(),Tf(),wy(),an()}}),My={};async function Oy(e={}){try{const{projects:t,viewerOrgs:n}=await Qu(async()=>{const e=await Bu(),t=se(await ae(e,Yu()));return{projects:await vy(e),viewerOrgs:t}}),r=$e(),a=Ae(),i=function(e,t){const n=(e,t)=>null===e||e.includes(t);if(0===e.orgs.length||1===e.orgs.length&&""===e.orgs[0].orgId){const r=(e.orgs[0]?.effective??H).project_scope;return t.filter(e=>n(r,e.id))}return t.filter(t=>{const r="string"==typeof t.org_id?ge(e,t.org_id):ye(e);return n(r.project_scope,t.id)})}(Fe(),function(e,t){return 0===t.size?e:e.filter(e=>!("string"==typeof e.org_id&&t.has(e.org_id)))}(t,n)).filter(e=>!a||e.org_id===a).filter(e=>!r||e.id===r).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})),s=od(i,e.offset,e.limit);return Iu(Xd(s.rows,s.meta),{paging:{}})}catch(e){return qu(vu(e,{read:!0}))}}D(My,{listProjectsHandler:()=>Oy});var Ey=P({"src/tools/list-projects.ts"(){sp(),fe(),qy(),Ie(),We(),Se(),vd(),zu()}}),zy={};async function Ry(e){try{const t=await Bu();let n,r,a=null;try{a=await jy(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return qu(vu(e,{read:!0}))}let i=null;if(a){const i=(await $y(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=>uc(t)===uc(e.domain)))return!1}return!e.level||Vl(n?.tags?.level)===Vl(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 by(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=i?await Hf(t,e.project_id,n):null,o=s?.flags??new Map,l=n.map(e=>({id:e.id,title:e.title,type:e.type,status:Cm(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type,...o.has(e.id)?{needs_rerun:o.get(e.id)}:{}})),c=eu(r,e.limit,void 0!==e.after?0:e.offset);i&&"boolean"==typeof i.hasMore&&(c.has_more=i.hasMore,i.nextCursor&&(c.next_cursor=i.nextCursor),i.hasMore&&void 0===e.after&&(c.next_offset=e.offset+n.length)),s?.scope&&(c.rerun_scope=s.scope.label);const d=i?{resume:t=>({meta:{next_cursor:En(n[t-1],i?.cursorTotal),...void 0===e.after?{next_offset:e.offset+t}:{}},next:"after=meta.next_cursor"})}:{};return Iu(Xd(l,c),{paging:d})}catch(e){return e instanceof jn?qu(su(e.message)):e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(zy,{listItemsHandler:()=>Ry});var Ty=P({"src/tools/list-items.ts"(){sp(),qy(),zu(),kr(),Wc(),Zm(),Vf()}});var Cy=P({"src/core/get-item-links.ts"(){Tf(),kr()}});function Py(e,t){return Ra(e,t)}function Dy(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 Ny(e,t){if(t&&Ca(e,t))throw Dy(t)}async function Hy(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 Zu(e)}catch{t=null}return function(e){const t=Da(e.clientName);return{kind:"agent",user_id:e.userId,session_id:e.sessionId,label:Na(t,e.name,e.email),client:t}}({userId:Yu(),sessionId:q$(),name:t,email:Ku(),clientName:O$()})}(e),l=async n=>{const a=function(e,t){return function(e,t,n,r){const a={surface:"mcp",delivery:"npm",package_version:c$,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 Dy(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??Ea,n=function(e,t=mr,n=fr){return Ma(Aa(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=Aa(u);if(t(e)&&a.length>1){const e=Math.ceil(a.length/2),t=[Ma(a.slice(0,e),1/0,1/0)[0],Ma(a.slice(e),1/0,1/0)[0]];n.splice(d,1,...t),r+=1;continue}if(t(e)&&u.length>1){const e=Math.ceil(u.length/2);n.splice(d,1,u.slice(0,e),u.slice(e)),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&&Ny("ops",c.error),c}function Fy(e){return{...e.chunks?{chunks:e.chunks}:{},...void 0!==e.error?{error:vu(e.error).message}:{}}}function Ly(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 Uy(e){const t=e.relooked?[...e.answers]:await Ga(e.client,e.projectId,e.answers,e.ops),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 Qr(e.client,e.projectId,n)),ia({answers:t,ops:e.ops,skippedItems:Ly(e.results??[]),openRevisions:r,labels:e.labels})}function Wy(e){const t=e.suggestion;return"number"==typeof t?.sg_number?t.sg_number:null}function Vy(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!==Wy(e)?{change:{sg_number:Wy(e)}}:{}})),r={...e,applied:[...e.applied,...n]},{isError:a,result:i}=_a(r,t);return a?qu(i):Iu(i)}async function By(e,t,n,r,a,i={}){const s=[...new Set(r.filter(e=>["applied","noop","replaced","captured"].includes(e.status)&&!e.replayed&&e.item_id).map(e=>e.item_id))].filter(e=>n.some(t=>t.item_id===e));if(0===s.length)return;const o=s.map(e=>({item_id:e,project_id:t,changed_by:Yu(),event_type:a,old_data:null,new_data:Ja(n,r,e),actor:M$(),session_id:q$(),...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 Gy(e){return e&&0!==e.length?"tags"===e[0]?"level"===e[1]?"level":"domains"===e[1]?"domains":"tags":e[0]:null}function Jy(e){return"set"===e.kind?e.path:[...e.path,e.kind,String(e.row_id??Tr(e.value??null))]}function Qy(e){return null==e?[]:"string"==typeof e?[e]:[...e]}var Yy,Ky=P({"src/tools/_agent-ops.ts"(){sp(),E$(),ai(),zu()}}),Zy={};function Xy(e,t){if(!t)return e;const n={...e};for(const e of Yy){const r=t[e];null!=r&&("evidence_url"===e&&"string"==typeof r&&""===r.trim()||(n[e]=r))}return n}async function ew(e){try{const r=await Bu();let a=null;try{a=await jy(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return qu(vu(e,{read:!0}))}let i=null;if(!a&&!0===await Py(r,e.project_id)){i={head:await Kr(r,e.project_id),revision:(await Qr(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?Sy(e):null):await ky(r,e.project_id,e.item_id);if(!s)return qu(nu("Item",e.item_id));const o=Object.fromEntries(Sf.map(e=>[e.lane,[]]));if(a){const t=s.data?.relationships??{};for(const e of Object.keys(o)){const n=t[e];Array.isArray(n)&&(o[e]=n.slice())}const n=await async function(e,t,n,r){return function(e,t){const n={};for(const r of t){if(!r||r.id===e)continue;const t=r.data?.relationships;if(t&&"object"==typeof t)for(const a of Sf){const i=t[a.lane];if(!Array.isArray(i)||!i.includes(e))continue;const s=n[a.incoming]??=[];s.includes(r.id)||s.push(r.id)}}return n}(n,await qn(e,t,r))}(r,e.project_id,e.item_id,a);for(const[e,t]of Object.entries(n))if(e in o)for(const n of t)o[e].includes(n)||o[e].push(n)}else{const t=await async function(e,t,n){const r=r=>Sn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq(r,n),mn),[a,i]=await Promise.all([r("from_id"),r("to_id")]);return[...a,...i.filter(e=>e.from_id!==n)]}(r,e.project_id,e.item_id),n=(e,t)=>{if(!e||!(e in o))return;const n=o[e];n.includes(t)||n.push(t)},a=new Set([e.item_id]);for(const e of t)a.add(e.from_id),a.add(e.to_id);const i=s.data?.relationships??{};for(const e of Object.keys(o)){const t=i[e];if(Array.isArray(t))for(const e of t)"string"==typeof e&&a.add(e)}const l=await async function(e,t,n,r){const a=[...new Set(n)].filter(e=>e!==r),i=await On(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 s.add(r),s}(r,e.project_id,a,e.item_id),c=e=>l.has(e);for(const r of t)if(r.from_id===e.item_id){if(!c(r.to_id))continue;n(Af(r.type,!0),r.to_id)}else{if(!c(r.from_id))continue;n(Af(r.type,!1),r.from_id)}for(const t of Object.keys(o)){const r=i[t];if(Array.isArray(r))for(const a of r)"string"==typeof a&&a!==e.item_id&&c(a)&&n(t,a)}}const l=s.data?.relationships??{},c={};for(const e of Q_){const t=Array.isArray(l[e])?l[e].filter(e=>"string"==typeof e):[];t.length>0&&(c[e]=t)}let d=[];if("test-case"===s.type)if(a)d=(Lm(s.data)??[]).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)=>jm(String(e.base.run_at),String(t.base.run_at))).slice(0,20).map(e=>Xy(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)throw n;if(t){const e=new Map;for(const t of s.data?.runs??[])"string"==typeof t?.date&&e.set(t.date,t);d=t.map(t=>Xy(t,e.get(String(t.run_at))))}}const u=i&&function(e){return"requirement"===e.type&&null!==bp(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,p=a?void 0:await Hf(r,e.project_id,[s]),m={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:{...If(o),...c},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:Cm(s),...Ff(p,s.id),...kp(s,{live:null!==i,since:u}),..."test-case"===s.type?{...Em(s.data),latest_result:d[0]?.result??"not-run",test_results:d}:{},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}};let f;if(!a&&ih(s.type)){const t=await Ih(r,e.project_id),n=Ah(t);f="hazard"===s.type?function(e,t){const{level:n,count:r}=e.hazardAsil(t);return{highest_asil:n,event_count:r,events:[...e.rowsOfHazard(t)],functions:[...e.hazardFunctions(t)],goals:[...e.hazardGoals(t)]}}(n,s.id):function(e,t,n){const r=e.goalVerification(t),a=new Map(n.map(e=>[e.id,e])),i=[...e.rowsOfGoal(t)],s=i.filter(e=>mc((a.get(e)?.data??{}).analysis_props??null)!==Bo),o=[...e.satisfiers(t)],l=e.goalCoverage(t);return{asil:e.goalAsil(t),source_rows:s,events:i,functions:[...e.goalFunctions(t)],satisfied_by:o,verified_satisfiers:o.filter(t=>e.requirementVerified(t)).length,row_mitigators:[...l.rowMitigators],uncovered_rows:[...l.uncoveredRows],untested_rows:[...l.untestedRows],verification:{verified:r.verified,total:r.total,requirements:r.requirements.map(e=>({id:e.id,verified:e.verified,via_rows:[...e.viaRows],text:C_(e,bh)}))}}}(n,s.id,t)}f&&Object.assign(m,{safety:f}),a||Object.assign(m,await async function(t){if(!jh(t))return{};const n=Co(t.data);return xh(t,n?await(a=n,ky(r,e.project_id,a)):null)?kh(t.id):{};var a}(s));const _=function(e){const t={};if(e&&"object"==typeof e)for(const[n,r]of Object.entries(e))Array.isArray(r)&&r.length>0&&(t[n]=r.length);return{relationship_counts:t}}(m.relationships);if(i){const n=s.data?.steps,a=Array.isArray(n)?n:[],o=(await Zr(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 Iu(Xd({...m,...i.revision?{base_token:await Wr(i.revision,"item")}:{},seq:i.head,editing_now:o,...l?{presence:l}:{}},_))}return Iu(Xd(m,_))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}var t,n}D(Zy,{getItemHandler:()=>ew});var tw,nw,rw=P({"src/tools/get-item.ts"(){Ap(),sp(),Zm(),Vf(),qy(),Tf(),Cy(),zu(),ai(),Ky(),Nh(),Yy=["point","release_id","build","environment","tooling","evidence_url","step_results"]}}),aw={};function iw(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:Xr(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 sw(e){try{const t=await Bu(),n=await Py(t,e.project_id);if(null===n)return qu(Ta());if(!n)return qu(su(nw));if(void 0===e.since_seq){const n=await Kr(t,e.project_id);return Iu(Xd({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??tw});if(a)throw a;const i=r??{},s=(i.changes??[]).map(iw);return Iu(Xd({project_id:e.project_id,changes:s,last_seq:Number(i.last_seq??e.since_seq),has_more:!0===i.more}),{paging:{list:"changes",resume:e=>({data:{last_seq:s[e-1].seq,has_more:!0},next:`since_seq=${s[e-1].seq}`})}})}catch(e){return qu(vu(e,{read:!0}))}}D(aw,{LIST_CHANGES_DEFAULT_LIMIT:()=>tw,LIST_CHANGES_NOT_NUMBERED:()=>nw,listChangesHandler:()=>sw,listedChange:()=>iw});var ow=P({"src/tools/list-changes.ts"(){sp(),ai(),zu(),Ky(),tw=100,nw="This project does not number its changes yet. Use atoms_get_history for one item."}}),lw=P({"src/core/snapshot-search.ts"(){}}),cw={};async function dw(e){try{const t=await Bu();let n,r,a=null;try{a=await jy(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return qu(vu(e,{read:!0}))}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 $y(t,e.project_id,a),e.query,{type:e.type,limit:e.limit});r=i.totalCount,n=i.items}else{const a=await Ay(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});n=a.items,r=a.totalCount}return Iu(Xd(n.map(e=>({id:e.id,title:e.title,type:e.type,status:Cm(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),eu(r,e.limit,0)),{paging:{resume:"none"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(cw,{searchHandler:()=>dw});var uw=P({"src/tools/search.ts"(){sp(),qy(),lw(),zu(),Zm()}}),pw={};async function mw(e){try{const t=await Bu(),{access_token:n}=await Ct(),{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(()=>(It(),bt)),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 Iu(Xd(r.map(e=>({id:e.id,title:e.title,type:e.type,status:Cm(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),eu(a,e.limit,0)),{paging:{resume:"none"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(pw,{semanticSearchHandler:()=>mw});var fw=P({"src/tools/semantic-search.ts"(){sp(),Ht(),qy(),zu(),Zm()}}),_w={};async function hw(e){try{if(e.baseline_id&&e.as_of)return qu(su("baseline_id and as_of are mutually exclusive"));const t=await Bu();let n;if(e.baseline_id){const r=await xy(t,e.baseline_id);if(!r)return qu(su("Baseline not found"));if(r.project_id!==e.project_id)return qu(su("Baseline does not belong to this project"));n=yn(e.baseline_id)}else e.as_of&&(n=gn(yy(e.as_of)));const r=await Iy(t,e.project_id,{domain:e.domain,level:e.level,moment:n}),{total:a,mitigators:i}=r,s=n?null:await gf(t,e.project_id),{covered:o,uncovered:l,coveredByDocument:c}=wf(r.covered,r.uncovered,s),d=od(l,e.offset,e.limit),u=d.rows.map(e=>{const t=function(e,t){if(Xm(e))return[...t?.get(e.id)??[]]}(e,i);return{id:e.id,title:e.title,type:e.type,status:Cm(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,...t?{mitigated_by:t}:{}}});return Iu(Xd({covered:o.length,uncovered:l.length,total:a,coverage_percent:jf(o.length,a),covered_via_mitigation:pf(l,i),...c?{covered_by_document:c}:{},uncovered_items:u},d.meta),{paging:{list:"uncovered_items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(_w,{getCoverageHandler:()=>hw});var gw,yw,ww=P({"src/tools/get-coverage.ts"(){sp(),qy(),wy(),kr(),zu(),Zm(),vd(),$f(),hf(),kf()}}),vw=P({"src/core/accepted-readiness.ts"(){kr(),Vf(),Jg()}}),bw={};async function kw(e,t,n){const r=await Sn(()=>e.from("items").select("id").eq("project_id",t).eq("type","requirement").is("deleted_at",null),pn);return(await On(r.map(e=>e.id),r=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:n,p_requirement_ids:r}))).sort(yw)}async function jw(e){try{const t=await Bu();let n=null;if(e.release_id){const r=await xy(t,e.release_id);if(!r)return qu(su(`Release ${e.release_id} not found`));if(r.project_id!==e.project_id)return qu(su("Release does not belong to this project"));if(null===r.release_version)return qu(tu(`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 qu(vu(a,{read:!0}));n=r,n||(n=await async function(e,t){return await xg(e,t)?Ag(e,t):null}(t,e.project_id))}const r=await gf(t,e.project_id);if(!n)return Iu(Xd({release:null,rerun:await kw(t,e.project_id,null),...r?{document_closures:r}:{},hint:gw,...await Ig(t,e.project_id,null),...await ry(t,e.project_id,null,e.include_report)}),{complete:!0});const{data:a,error:i}=await t.rpc("verification_readiness",{p_project_id:e.project_id,p_release_id:n.id});if(i)return qu(vu(i,{read:!0}));const s=n.id,o=await Sn(()=>t.from("verification_status").select("requirement_id, state, stale, points_total, points_run, verified_in").eq("project_id",e.project_id).eq("release_id",s),["requirement_id"]),l=function(e,t){if(!t)return e.slice();const n=new Set(t.map(e=>e.requirement_id));return e.map(e=>({...e,closed_by_document:n.has(e.requirement_id)}))}(o.slice().sort(yw),r),c=await ug(t,e.project_id,s),d=await async function(e,t,n,r){if(!r)return null;const a=[...new Set(r.map(e=>e.test_case_id))],i={acceptedTestIds:a,testsOf:new Map,states:[],rerunOf:new Map};if(0===a.length)return i;const{testsOf:s}=await Sg(e,t),o=new Set(a),l=new Map;for(const[e,t]of s)[...t].some(e=>o.has(e))&&l.set(e,[...t].sort());if(0===l.size)return i;const c=[...new Set([...l.values()].flat().filter(e=>!o.has(e)))].sort(),d=c.length>0?await On(c,r=>e.rpc("needs_attention_test_states",{p_project_id:t,p_release_id:n,p_test_case_ids:r})):[],u=c.length>0?await Nf(e,t,l.keys(),n):[],p=new Map;for(const e of u)p.set(e.requirement_id,[...p.get(e.requirement_id)??[],...e.test_case_ids??[]]);return{acceptedTestIds:a,testsOf:l,states:d,rerunOf:p}}(t,e.project_id,s,c),u={release:{id:n.id,version:n.release_version,status:n.release_status},readiness:fg(yf(a??{},o,r),o,d,new Set((r??[]).map(e=>e.requirement_id))),requirements:l,rerun:await kw(t,e.project_id,s),...await Ig(t,e.project_id,n),...c?{accepted_failures:c}:{},...r?{document_closures:r}:{},...await ry(t,e.project_id,n,e.include_report),...0===l.length?{hint:"projection empty; an admin may need to run rebuild_verification_from_runs for this project"}:{}};return e.include_gaps&&(u.gaps=await Sn(()=>t.rpc("verification_notrun_points",{p_project_id:e.project_id,p_release_id:s}),["tc_id","asset","point_key"])),Iu(Xd(u),{complete:!0})}catch(e){return qu(vu(e,{read:!0}))}}D(bw,{verificationStatusHandler:()=>jw});var xw,Sw,$w,Aw,Iw=P({"src/tools/verification-status.ts"(){sp(),qy(),kr(),Jg(),vg(),vw(),kf(),sy(),zu(),gw="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).",yw=(e,t)=>e.requirement_id<t.requirement_id?-1:e.requirement_id>t.requirement_id?1:0}});function qw(e,t,n){const r=e?.count??0,a=(e?.items??[]).slice(0,xw).map(e=>""===String(e).trim()?`an unnamed ${t}`:String(e));if(0===a.length)return $w(r,`a ${t}`,n);const i=r-a.length;return i>0?`${a.join(", ")} and ${i} more`:1===a.length?a[0]:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`}function Mw(e,t,n,r){if(!e||e.count<=0)return[];const a=e=>""===String(e??"").trim()?`an unnamed ${t}`:String(e),i=(e.items??[]).slice(0,xw);if(0===i.length)return[`${r} ${$w(e.count,`a ${t}`,n)}`];const s=i.map(e=>"arrow"===t?`${r} an arrow to ${a(e.to)}`:`${r} ${"group"===t?"group ":""}${a(e.from)} to ${a(e.to)}`),o=e.count-i.length;return o>0&&s.push(`${r} ${$w(o,`1 more ${t}`,`more ${n}`)}`),s}function Ow(e){const t=e.summary??{};if("trashed"===e.event_type)return"Moved to Trash";if("restored"===e.event_type)return"Restored";const n=[];if("editors"===e.event_type){for(const r of t.editors_added??[])n.push(r.user_id===e.changed_by?"added themselves as editor":`added ${r.name} as editor`);for(const r of t.editors_removed??[])n.push(r.user_id===e.changed_by?"removed themselves as editor":`removed ${r.name} as editor`)}else if("created"===e.event_type){const e=[t.boxes_added?.count?$w(t.boxes_added.count,"1 box","boxes"):null,t.arrows_added?.count?$w(t.arrows_added.count,"1 arrow","arrows"):null,t.groups_added?.count?$w(t.groups_added.count,"1 group","groups"):null].filter(e=>null!==e);n.push(0===e.length?"created":`created with ${1===e.length?e[0]:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}`),t.links_added?.count&&n.push(`linked ${qw(t.links_added,"item","items")}`)}else{void 0!==t.name?.from&&n.push(`renamed the design to ${t.name.to}`),t.description_changed&&n.push("changed the description"),t.boxes_added?.count&&n.push(`added ${qw(t.boxes_added,"box","boxes")}`),t.boxes_removed?.count&&n.push(`removed ${qw(t.boxes_removed,"box","boxes")}`),n.push(...Mw(t.boxes_renamed,"box","boxes","renamed")),t.boxes_moved?.count&&n.push(`moved or resized ${$w(t.boxes_moved.count,"a box","boxes")}`),t.arrows_added?.count&&n.push(`added ${$w(t.arrows_added.count,"an arrow","arrows")}`),t.arrows_removed?.count&&n.push(`removed ${$w(t.arrows_removed.count,"an arrow","arrows")}`),n.push(...Mw(t.arrows_relabelled,"arrow","arrows","relabelled"));const e=e=>`${(e.items??[]).length>0?"group ":""}${qw(e,"group","groups")}`;t.groups_added?.count&&n.push(`added ${e(t.groups_added)}`),t.groups_removed?.count&&n.push(`removed ${e(t.groups_removed)}`),n.push(...Mw(t.groups_renamed,"group","groups","renamed")),t.groups_moved?.count&&n.push(`moved or resized ${$w(t.groups_moved.count,"a group","groups")}`),t.links_added?.count&&n.push(`linked ${qw(t.links_added,"item","items")}`),t.links_removed?.count&&n.push(`unlinked ${qw(t.links_removed,"item","items")}`),0===n.length&&t.canvas_changed&&n.push("changed the drawing"),0===n.length&&n.push("saved with no change")}const r=n.join(", ");return r.charAt(0).toUpperCase()+r.slice(1)}function Ew(e){if("mcp"!==e.source)return"user";const t=String(e.agent_label??"Claude").split(" ")[0].toLowerCase();return`mcp_${["claude","cursor","copilot"].includes(t)?t:"claude"}`}function zw(e){return{id:String(e.id),event_type:e.event_type,changed_by:e.changed_by,changed_by_name:e.changed_by_name,changed_at:e.changed_at,actor:Ew(e),source:e.source,agent_label:e.agent_label,version:e.version,fields_changed:Object.keys(e.summary??{}).filter(e=>"truncated"!==e),summary_line:Ow(e),summary:e.summary??{}}}var Rw=P({"src/core/model-design-history.ts"(){Js(),Se(),xn(),xw=3,Sw="id, design_id, version, changed_by, changed_by_name, changed_at, event_type, source, agent_label, summary",$w=(e,t,n)=>1===e?`${t}`:`${e} ${n}`,Aw=e=>ps.test(e)}}),Tw={};async function Cw(e){const t=e.offset??0;try{const n=await Bu();if(Aw(e.item_id)){const r=function(e,t){return ve(e,"atoms_get_model_design",t)}(ke(Fe(),e.project_id),e);if(r)return qu(r);const a=await async function(e,t,n,r,a=0){const i=await e.from("model_designs").select("id, display_id").eq("project_id",t).eq("display_id",n.trim().toUpperCase()).maybeSingle();if(i.error)throw i.error;const s=i.data;if(!s)return{design:null};const o=await un(e.from("model_design_history").select(Sw,{count:"exact"}).eq("design_id",s.id).order("id",{ascending:!1}).range(a,a+r));if(o.error)throw o.error;return{design:s,rows:o.data??[],total:"number"==typeof o.count?o.count:(o.data??[]).length}}(n,e.project_id,e.item_id,e.limit,t);return null===a.design?qu({status:"error",code:"not_found",retryable:!1,message:`${e.item_id} is not a model design of this project.`,next_steps:["Use atoms_list_model_designs to see this project's model designs and their MD ids"]}):Iu(Xd(a.rows.slice(0,e.limit).map(zw),ig(a.total,e.limit,a.rows.length,t)))}const{rows:r,total:a}=await async function(e,t,n,r,a=0){const{data:i,error:s,count:o}=await un(e.from("item_revisions").select("id, revision_number, fields_snapshot, valid_from, valid_to, changed_by, event_source, event_session_id, diff_summary",{count:"exact"}).eq("item_id",n).eq("project_id",t).order("revision_number",{ascending:!1}).range(a,a+r));if(s)throw new Error(s.message);const l=i??[];return{rows:l,total:o??a+l.length}}(n,e.project_id,e.item_id,e.limit,t);if(r.length>0||t>0&&a>0){const i=r,s=function(e,t,n,r,a){const i=e.slice(0,n),s=new Map(i.map((e,t)=>[String(e.id),t])),o=i.map(()=>[]);for(const e of t){const t=s.get(String(e.id).split(":")[0]);void 0!==t&&o[t].push(e)}const l=[],c=[];for(const e of o){if(c.length>0&&l.length+e.length>n)break;l.push(...e),c.push(l.length)}const d=c.length,u=e.length>d;return{entries:l,meta:{total_count:d>0?Math.max(a,r+d):a,limit:n,offset:r,has_more:u,...u?{next_offset:r+d}:{}},resume:e=>{const t=r+Math.max(1,c.filter(t=>t<=e).length);return{meta:{next_offset:t},next:`offset=${t}`}}}}(i,ag(i,await async function(e,t,n,r){const a=new Map,i=function(e){const t=new Set;for(const n of e){const e=ng(n).author;e&&"object"==typeof e||!n.event_session_id||"mcp"!==n.event_source&&"restore"!==n.event_source||t.add(n.event_session_id)}return[...t].sort()}(r);if(0===i.length)return a;try{const{data:r,error:s}=await e.from("change_history").select("session_id, actor").eq("project_id",t).eq("item_id",n).in("session_id",i).like("actor","mcp_%").limit(1e3);if(s)return a;for(const e of r??[])"string"!=typeof e.session_id||"string"!=typeof e.actor||a.has(e.session_id)||a.set(e.session_id,e.actor)}catch{}return a}(n,e.project_id,e.item_id,i),await async function(e,t,n,r){const a=r.filter(e=>null===Xh(e.diff_summary)&&"user"!==rg(e));if(0===a.length)return new Map;try{const i=a[a.length-1].valid_from,{data:s,error:o}=await e.from("change_history").select("changed_at, changed_by, actor, reason").eq("project_id",t).eq("item_id",n).like("actor","mcp_%").not("reason","is",null).gte("changed_at",i).order("changed_at",{ascending:!1}).limit(1e3);return o?new Map:function(e,t){const n=new Map,r=t.filter(e=>"string"==typeof e.actor&&e.actor.startsWith("mcp_")&&null!==Zh(e.reason)).map(e=>({at:Date.parse(e.changed_at),by:e.changed_by,reason:e.reason})).sort((e,t)=>t.at-e.at);return e.forEach((t,a)=>{if(null!==Xh(t.diff_summary)||"user"===rg(t))return;const i=Date.parse(t.valid_from),s=a>0?Date.parse(e[a-1].valid_from):1/0,o=r.find(e=>e.by===t.changed_by&&e.at>=i&&e.at<s);o&&n.set(t.id,o.reason)}),n}(r,s??[])}catch{return new Map}}(n,e.project_id,e.item_id,i)),e.limit,t,a);return Iu(Xd(s.entries,s.meta),{paging:{resume:s.resume}})}const{rows:i,total:s}=await async function(e,t,n,r,a=0){const{data:i,error:s,count:o}=await un(e.from("change_history").select("*",{count:"exact"}).eq("item_id",n).eq("project_id",t).order("changed_at",{ascending:!1}).range(a,a+r));if(s)throw new Error(s.message);const l=i??[];return{rows:l,total:o??a+l.length}}(n,e.project_id,e.item_id,e.limit,t);return Iu(Xd(i.slice(0,e.limit).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)");const a=Zh(e.reason);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,...null!==a?{reason:a}:{}}}),ig(s,e.limit,i.length,t)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(Tw,{getHistoryHandler:()=>Cw});var Pw,Dw,Nw=P({"src/tools/get-history.ts"(){sp(),qy(),lg(),zu(),Rw(),Se(),We()}}),Hw=P({"src/core/link-kinds.ts"(){Pw={parent:{word:"parent of",required:!0},verifies:{word:"verified by",required:!0},related:{word:"related to",required:!1},mitigates:{word:"mitigates",required:!0,turnedWord:"mitigated by"},allocated_to:{word:"allocated to",required:!1,turnedWord:"allocated from"},event_hazard:{word:"cites hazard",required:!0,turnedWord:"cited by"},event_goal:{word:"cites goal",required:!0},affects:{word:"affects",required:!1},traces_to:{word:"traces to",required:!1,turnedWord:"traced by"},decomposes_to:{word:"decomposes to",required:!0}},Dw={child:"parent",verified_by:"verifies",mitigated_by:"mitigates",allocated_from:"allocated_to",hazard_events:"event_hazard",goal_events:"event_goal",affected_by:"affects",traced_by:"traces_to",decomposed_from:"decomposes_to"}}});function Fw(e){return"parent"===e.type?{from_id:e.to_id,to_id:e.from_id,type:"child"}:"verifies"===e.type?{from_id:e.to_id,to_id:e.from_id,type:"verified_by"}:e}function Lw(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function Uw(e){const t=Gw(`${e.id}: ${e.title}`);return"test-case"===e.type?`(["${t}"])`:"note"===e.type?`("${t}")`:"function"===e.type?`{{"${t}"}}`:"hazard"===e.type?`>"${t}"]`:"goal"===e.type?`[/"${t}"/]`:`["${t}"]`}function Ww(e){const t="child"===e.type?"parent":"verified_by"===e.type?"verifies":Dw[e.type];return t&&"child"!==e.type&&"verified_by"!==e.type?{kind:t,from:e.to_id,to:e.from_id}:t?{kind:t,from:e.from_id,to:e.to_id}:Pw[e.type]?{kind:e.type,from:e.from_id,to:e.to_id}:null}function Vw(e){const t=Ww(e);if(!t)return null;const{word:n,required:r}=Pw[t.kind],a=Lw(t.from),i=Lw(t.to);return"related"===t.kind?`${a} -.-|${n}| ${i}`:`${a} ${r?"--\x3e":"-.->"}|${n}| ${i}`}function Bw(e){const t=Ww(e);return t?`${t.from}:${t.kind}:${t.to}`:`${e.from_id}:${e.type}:${e.to_id}`}function Gw(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var Jw=P({"src/core/mermaid.ts"(){Hw()}}),Qw={};async function Yw(e){try{if(e.baseline_id&&e.as_of)return qu(su("baseline_id and as_of are mutually exclusive"));const t=await Bu();let n,r,a;if(e.baseline_id){const r=await xy(t,e.baseline_id);if(!r)return qu(su("Baseline not found"));if(r.project_id!==e.project_id)return qu(su("Baseline does not belong to this project"));n=yn(e.baseline_id)}else e.as_of&&(n=gn(yy(e.as_of)));if(n){r=(await $y(t,e.project_id,n)).map(Sy).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),a=qf(r,[])}else r=await Sn(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn),a=qf(r,await Sn(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn));return Iu(Xd(function(e){const t=e.items,n=(e.relationships??[]).map(Fw),r=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${Gw(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(` ${Lw(t)}${Uw(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=Vw(c);if(!u)continue;const p=Bw(c);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")?qu(ou()):qu(vu(e,{read:!0}))}}D(Qw,{exportMermaidHandler:()=>Yw});var Kw,Zw,Xw=P({"src/tools/export-mermaid.ts"(){sp(),qy(),zu(),Jw(),wy(),kr()}}),ev=P({"src/core/item-types.ts"(){Kw={requirement:{idPrefix:"REQ",label:"Requirement"},"test-case":{idPrefix:"TC",label:"Test Case"},note:{idPrefix:"NOTE",label:"Note"},table:{idPrefix:"TABLE",label:"Table"},analysis:{idPrefix:null,label:"Analysis"},function:{idPrefix:"FN",label:"Function"},hazard:{idPrefix:"HAZ",label:"Hazard"},goal:{idPrefix:"SG",label:"Safety goal"}}}});function tv(e){const t=function(e){return Object.prototype.hasOwnProperty.call(Kw,e)?Kw[e]:void 0}(e);if(!t)throw new Error(`Unknown item type "${e}": it has no id prefix`);if(null===t.idPrefix)throw new Error(`Item type "${e}" has no single id prefix (its ids come from its scheme)`);return t.idPrefix}function nv(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 rv(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>Zw)throw new Error(`ID generation failed: at most ${Zw} 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 av=P({"src/core/item-id-reservation.ts"(){ev(),Zw=1e3}});async function iv(e,t){const n=await Ra(e,t);return null===n?"unreadable":n?"ops":"main"}function sv(){return qu(Ta())}async function ov(e){const t=[...e.ops];let n=e.preFound??new Map;!e.preFound&&e.deterministic&&t.length>0&&(n=await Ba(e.client,e.projectId,t));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 Hy(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 Ga(e.client,e.projectId,a.answers,t),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,...za(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 Qr(e.client,e.projectId,l)),{outcome:await ia({answers:s,ops:t,skippedItems:o,...c?{openRevisions:c}:{},...e.labels?{labels:e.labels}:{}}),answers:s,results:a.results,chunks:a.chunks,...void 0!==a.error?{error:a.error}:{},found:n}}function lv(e,t,n,r){if(0===e.not_applied.length)return Iu(Xd({...t,...r??{},...ha(e),...n?.chunks?{chunks:n.chunks}:{}}));const{isError:a,result:i}=_a(e,{...r??{},...Fy(n??{})});return a?qu(i):Iu(i)}function cv(e,t,n){return e&&!t?Ca(e,n):null}function dv(e){return null==e?[]:(Array.isArray(e)?[...e]:[e]).filter(e=>"string"==typeof e&&e.length>0)}function uv(e){return e.some(e=>void 0!==e.acceptance_revoked&&null!==e.acceptance_revoked&&!1!==e.acceptance_revoked)}async function pv(e){const t=await ta({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(ea(t.path));a&&r.push(ra({op_id:ya(),kind:"set",item_id:e.itemId,path:[...t.path],value:t.value},a))}return{ops:r,refusals:t.refusals}}async function mv(e){const t=Yu(),n=q$(),r=xa(e.contents),a=[],i=[],s=e.key?await Promise.all(e.contents.map(e=>La(e))):e.contents.map(()=>{});for(let s=0;s<e.contents.length;s+=1)a.push(await ga(e.key?va({userId:t,projectId:e.projectId,family:ja(e.tool),key:e.key,itemIdOrK:s}):wa({userId:t,projectId:e.projectId,content:e.contents[s],k:r[s],sessionId:n}))),i.push(await ga(e.key?va({userId:t,projectId:e.projectId,family:ja(e.tool),key:e.key,itemIdOrK:`link:${s}`,path:["relationships","children"]}):[t,e.projectId,"create_link",a[s]]));return{create:a,link:i,hash:s,createRefs:a.map((e,t)=>({op_id:e,content_hash:s[t]}))}}function fv(e,t){for(const n of e){const e=t.create.indexOf(n.op_id);e>=0&&t.hash[e]&&(n.content_hash=t.hash[e])}return e}async function _v(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{tokens:a,unread:!1};let i;try{i=await Yr(e,t,r.map(e=>e.revision_id))}catch{return{tokens:a,unread:!0}}for(const e of r){const t=i.get(e.revision_id);t&&a.set(e.item_id,await Wr(t,"all"))}return{tokens:a,unread:!1}}async function hv(e){let t=0,n=0;for(;;){let r;try{r=await ov({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 gv(e,t,n){return e.answers.find(e=>e.status===t&&(void 0===n||e.reason===n))}var yv,wv,vv=P({"src/tools/_ops.ts"(){sp(),E$(),ai(),zu(),Ky()}});function bv(e,t){const n=process.env.ATOMS_MCP_REQUIRE_CONFIRMATION?.trim();if(n){const t=n.toLowerCase();if("1"===t||"true"===t||"all"===t)return!0;if(n.split(",").map(e=>e.trim()).filter(Boolean).includes(e))return!0}return!!ke(Fe(),t).require_confirmation_for.includes(e)}function kv(e,t=yv){const n=Date.now()+t,r={...e,exp:n},a=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${a}.${R.default.createHmac("sha256",wv).update(a).digest("base64url")}`,expires_at:new Date(n).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function jv(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=R.default.createHmac("sha256",wv).update(n).digest("base64url"),i=Buffer.from(r,"utf8"),s=Buffer.from(a,"utf8");if(i.length!==s.length||!R.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 xv(e){if(Array.isArray(e))return e.map(xv);if(null!==e&&"object"==typeof e){const t={};for(const n of Object.keys(e).sort())t[n]=xv(e[n]);return t}return e}function Sv(e){const t=JSON.stringify(xv(e));return R.default.createHash("sha256").update(t).digest("base64url").slice(0,16)}var $v,Av=P({"src/middleware/confirmation.ts"(){We(),Se(),yv=6e4,wv=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:R.default.randomBytes(32).toString("base64url")})()}});function Iv(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=>Vl(e)===Vl(i))??s.find(e=>r(e)===a)??t}function qv(e,t){return"locked"===t?`Level "${e}" is not in the project's level list, and the MCP policy of this project's organization does not let you 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 Mv=P({"src/core/levels.ts"(){Wc(),ed(),$v="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."}}),Ov={};function Ev(e){const t=Zd(e??"");return"sub-system"===t?"subsystem":t}async function zv(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 Rv(e,t){return{levels:await zv(e,t)}}async function Tv(e,t){return(await Sn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn)).map(e=>e.data?.tags?.level)}async function Cv(e,t,n){const r=Zd(n);return r?Iv(n,r,await zv(e,t),Ev):r}async function Pv(e,t,n){const r=Zd(n??""),a=Ev(r);if(!r)return"none";try{const{levels:n}=await Rv(e,t);if(n.some(e=>Ev(e)===a))return"present";if(!J(ke(Fe(),t),"atoms_create_level").allowed)return"locked";if(!0===await Ra(e,t)){const n={op_id:ya(),kind:"add",item_id:null,path:["taxonomy","levels"],value:r},{run:a}=await hv({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 Dv(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 Nv(e){try{const t=await Bu(),{levels:n}=await Rv(t,e.project_id),r=function(e,t,n){const r=new Set(e.map(e=>Vl(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(Vl(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 Tv(t,e.project_id),Ev),a=r.some(e=>void 0!==e.items_not_shown);return Iu(Xd({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?` ${$v}`:"")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}async function Hv(e,t){let n;try{const r=await Bu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const a=t??await iv(r,e.project_id);if("unreadable"===a)return sv();n=a;const{levels:i}=await Rv(r,e.project_id),s=Zd(e.name),o=Ev(s);if(!s)return qu(su("Level name cannot be empty."));if(i.some(e=>Ev(e)===o))return qu(su(`Level "${s}" already exists in this project.`));if("ops"===a){const t={op_id:ya(),kind:"add",item_id:null,path:["taxonomy","levels"],value:s},{run:n}=await hv({client:r,projectId:e.project_id,op:t});if(n.answers.some(e=>"noop"===e.status))return qu(su(`Level "${s}" already exists in this project.`));if(n.outcome.not_applied.length>0)return lv(n.outcome,{},n);const a=(await zv(r,e.project_id)).findIndex(e=>Ev(e)===o),l=`L${a>=0?a:i.length}`;return lv(n.outcome,{level:{name:s,prefix:l},message:`Level "${s}" registered as ${l}. Tag items with level="${s}".`},n)}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=>Ev(e)===o);if(void 0!==l){const e=`L${a.indexOf(l)}`;return Iu(Xd({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 Iu(Xd({level:{name:s,prefix:d},message:`Level "${s}" registered as ${d}. Tag items with level="${s}".`}))};return await l()}catch(r){const a=cv(n,t,r);return a?Hv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}async function Fv(e,t){let n;try{const r=await Bu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const a=t??await iv(r,e.project_id);if("unreadable"===a)return sv();n=a;const i=Ev(Su(e.name));if(!i)return qu(su("Level name cannot be empty."));const{levels:s}=await Rv(r,e.project_id),o=s.filter(e=>Ev(e)===i),l="ops"===a?0:(await Tv(r,e.project_id)).filter(e=>Ev(e)===i).length;if(0===o.length&&0===l&&"ops"!==a)return qu(nu("Level",e.name));const c=o[0]??e.name;if(l>0)return qu(su(`Level "${c}" is used by ${l} item${l>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`));if(bv("atoms_delete_level",e.project_id)){const t={tool:"atoms_delete_level",project_id:e.project_id,target:i};if(!e.confirmation_token){const e=kv(t);return Iu(Xd({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=jv(e.confirmation_token,t);if(!n.valid)return qu(su(`confirmation_token rejected: ${n.reason}`))}if("ops"===a){const t={op_id:ya(),kind:"remove",item_id:null,path:["taxonomy","levels"],value:c},{run:n}=await hv({client:r,projectId:e.project_id,op:t}),a=gv(n,"invalid","level_in_use");if(a){const e="number"==typeof a.count?a.count:1;return qu(su(`Level "${c}" is used by ${e} item${e>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`))}if(gv(n,"deleted"))return qu(nu("Level",e.name));if(n.outcome.not_applied.length>0)return lv(n.outcome,{},n);const i=await zv(r,e.project_id),o=Bl(s,i);return lv(n.outcome,{level:{name:c},remaining_levels:i,message:`Level "${c}" deleted. Every later level's L# shifts down by one.`+(o?" "+o:"")},n)}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=Bl(s,a);return Iu(Xd({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=cv(n,t,r);return a?Fv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}async function Lv(e,t){let n;try{const r=await Bu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const a=t??await iv(r,e.project_id);if("unreadable"===a)return sv();n=a;const i=Array.isArray(e.names)?e.names.map(e=>Su(String(e??"")).trim()).filter(e=>e.length>0):[];if(0===i.length)return qu(su("names must be a non-empty array of the project's existing levels, in the order you want them."));const{levels:s}=await Rv(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=>Vl(t)===Vl(e))??a(t=>""!==n(t)&&n(t)===n(e));if(null===t)return null;i.push(t)}return i}(s,i,Ev);if(!o)return qu(su(`names must list every existing level exactly once. Levels: ${s.length>0?s.join(", "):"(none)"}`));if("ops"===a){const t=Dv(s,o);if(t.length>0){const n=t.map(e=>({op_id:ya(),kind:"move_row",item_id:null,path:["taxonomy","levels"],row_id:e.level,value:{after:e.after}})),a=await ov({client:r,projectId:e.project_id,ops:n});if(gv(a,"deleted"))return qu(nu("Level",e.names.join(", ")));if(a.outcome.not_applied.length>0)return lv(a.outcome,{},a)}const n=await zv(r,e.project_id),a=Bl(s,n);return Iu(Xd({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=Bl(s,a);return Iu(Xd({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=cv(n,t,r);return a?Lv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}D(Ov,{createLevelHandler:()=>Hv,deleteLevelHandler:()=>Fv,ensureLevelRegistered:()=>Pv,getProjectLevels:()=>zv,levelKey:()=>Ev,levelMoves:()=>Dv,listLevelsHandler:()=>Nv,reorderLevelsHandler:()=>Lv,storedLevelSpelling:()=>Cv});var Uv,Wv,Vv,Bv,Gv,Jv,Qv,Yv,Kv=P({"src/tools/levels.ts"(){sp(),ai(),vv(),Av(),zu(),Wc(),re(),Se(),We(),kr(),Mv()}});function Zv(e,t,n){const[r,a]="affects"===n?[e,t]:[t,e];return r.startsWith(Bv)&&a.startsWith(Gv)?null:`affects/affected_by links a security risk analysis row (${Bv}n) to an ISO 14971 risk row (${Gv}n) only: "${e}" -> "${t}" is not that pair.`}function Xv(e,t,n){const r=[t,n].filter(Jv);if(0===r.length)return null;const a=`"${t.id}" -> "${n.id}"`;if(Qv(e)){const r=Jv(t)?n:t;return Jv(r)?`${e} links a requirement and a Function: ${a} joins two Functions. Decompose a Function with parent and child links between Functions instead.`:"requirement"!==r.type?`${e} links a requirement and a Function: "${r.id}" is a ${r.type}, not a requirement. Only requirements are allocated to a Function.`:r.isAnalysisRow?`${e} links a requirement and a Function: "${r.id}" is an analysis row. An analysis row names its Function in analysis_props.source_function_id, not by an allocation link.`:null}if("parent"===e||"child"===e){if(Jv(t)&&Jv(n))return null;const r=Jv(t)?n:t;return`${e} links between Functions only: ${a} joins a Function to "${r.id}", a ${r.type}. To tie a requirement to a Function, use atoms_link_items with type allocated_to.`}return Yv(e)?`${e} links never have a Function at either end: "${r[0].id}" is a Function (${a}). A Function is not verified, mitigated or affected directly: link its allocated requirements instead.`:null}function eb(e,t,n,r){return Xv("parent",{id:e,type:t},{id:n,type:r})}async function tb(e,t,n,r){const a=[...new Set(n)],i=await r(a,n=>e.from("items").select("id, type, data").eq("project_id",t).is("deleted_at",null).in("id",n)),s=e=>{const t=e.data?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]},o=i.filter(e=>"requirement"===e.type).flatMap(s),l=new Map;if(o.length>0){const n=await r([...new Set(o)],n=>e.from("items").select("id, type").eq("project_id",t).in("id",n));for(const e of n)l.set(e.id,e.type)}const c=new Map;for(const e of i)c.set(e.id,{id:e.id,type:e.type,isAnalysisRow:"requirement"===e.type&&s(e).some(e=>"analysis"===l.get(e))});return c}async function nb(e,t,n,r){const a=n.filter(e=>"add"===e.action),i=a.filter(e=>Qv(e.type)||Yv(e.type)||"parent"===e.type||"child"===e.type);if(0===i.length)return null;const s=e=>e.startsWith(Uv),o=a.some(e=>Qv(e.type));if(!o&&!i.some(e=>s(e.from_id)||s(e.to_id)))return null;if(o){const n=Jf(await Bf(e,t));if(n)return{toolError:n}}const l=await async function(e,t,n,r){const a=n.filter(e=>"add"===e.action&&(Qv(e.type)||Yv(e.type)||"parent"===e.type||"child"===e.type));if(0===a.length)return null;const i=await tb(e,t,a.flatMap(e=>[e.from_id,e.to_id]),r);for(const e of a){const t=i.get(e.from_id),n=i.get(e.to_id);if(!t||!n)continue;const r=Xv(e.type,t,n);if(r)return r}return null}(e,t,n,r);return l?{validation:l}:null}var rb=P({"src/core/link-pairs.ts"(){s_(),Wc(),Uv="FN-",Wv=["allocated_to","allocated_from"],Vv=["verifies","verified_by","mitigated_by","mitigates","affects","affected_by"],Bv=`${pl.security_tir57}-`,Gv=`${pl.hazard_iso14971}-`,Jv=e=>"function"===e.type,Qv=e=>Wv.includes(e),Yv=e=>Vv.includes(e)}});async function ab(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 async function(e,t){const n=await fy(e,"mcp_field_value_counts",{p_project_id:t});if(!n)return null;const r=n.data;if(null===r||"object"!=typeof r||Array.isArray(r))return null;const a=[];for(const[e,t]of Object.entries(r)){const n=py(t);if(null===n)return null;a.push({key:e,items:n})}return a}(e,t);if(i){for(const{key:e,items:t}of i){const n=a.get(e.toLowerCase());n&&(r[n]+=t)}return r}const s=await Sn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn);for(const e of s){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}var ib,sb,ob,lb,cb=P({"src/core/project-field-counts.ts"(){kr(),gy()}});function db(e){if(!Array.isArray(e))return;const t=new Set(e.filter(e=>"string"==typeof e&&ob.has(e)));return 0!==t.size?ib.filter(e=>t.has(e)):void 0}var ub,pb,mb,fb=P({"src/core/field-scope.ts"(){ib=["requirement","test-case","note","table","function"],sb=["requirement","test-case","note","table"],ob=new Set(ib),lb=e=>JSON.stringify({type:e.type,options:e.options??[],appliesTo:e.appliesTo??null})}}),_b={};async function hb(e,t){const{data:n,error:r}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(r)throw r;return gb(n?.fields)}function gb(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&&pb.has(e.type)?e.type:"text",o=Array.isArray(e.options)?Ib(e.options):[],l=db(e.appliesTo??e.applies_to);t.push({name:a,type:s,..."select"===s?{options:o}:{},...l?{appliesTo:l}:{}})}return t}function yb(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(!pb.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=Ib(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 wb(e,t){const n=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!n.has(e.toLowerCase()))}function vb(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 bb(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 kb(e,t,n=new Set,r){const a=wb(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(bb(r,e,a)){a.trim()&&(i[t.name]=a);continue}const o=Sb(t,a,n);if(o.error)return{error:o.error};o.value&&(i[t.name]=o.value)}return{fields:i}}function jb(e){return/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function xb(e,t){const n=t??{};let r=`Field "${e}" defined. Set values with atoms_update_item fields={"${e}": "<value>"}.`;if("number"==typeof n.values_outside_options&&n.values_outside_options>0){const t=n.values_outside_options;r+=` Note: ${t} ${1===t?"item holds a":"items hold"} ${e} ${1===t?"value":"values"} that ${1===t?"is":"are"} not one of its options; ${1===t?"it is":"they are"} kept.`}const a=(Array.isArray(n.skipped_projects)?n.skipped_projects:[]).filter(e=>!!e&&"object"==typeof e&&"number"==typeof e.incompatible_items);return a.length>0&&(r+=` Not added to ${a.map(e=>`${String(e.name)} (${e.incompatible_items} items)`).join(", ")}: items there hold ${e} values this type cannot take.`),r}function Sb(e,t,n){const r=t.trim();if(!r)return{value:""};if(r.length>mb)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 Ab(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 jb(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);if(!function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(t.url))return{error:`${e.name} must be an http(s) URL.`};const n=function(e,t){const n=t.trim();return n?JSON.stringify({label:e.trim(),url:n}):""}(t.label,t.url);return n.length>mb?{error:`${e.name} is too long.`}:{value:n}}}}async function $b(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(bb(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(!Ab(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:Yu()});if(i)return{error:i.message};!0===a&&o.add(n)}return kb(n,r,o,a)}function Ab(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 Ib(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 qb(e){try{const t=await Bu(),n=await hb(t,e.project_id),r=await ab(t,e.project_id,n),a=od(n,e.offset,e.limit);return Iu(Xd({fields:a.rows.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},a.meta),{paging:{list:"fields"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}async function Mb(e,t){let n;try{const r=await Bu();try{await np(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return qu(tn("project"));throw e}const a=t??await iv(r,e.project_id);if("unreadable"===a)return sv();n=a;const{data:i}=await r.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),s=gb(i?.fields),o=db(e.appliesTo),l={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:Ib(e.options??[])}:{},...o?{appliesTo:o}:{}},c=yb(l,function(e,t,n){if(!n)return e;const r=t.name.toLowerCase();return e.some(e=>e.name.toLowerCase()===r&&lb(e)===lb(t))?e.filter(e=>e.name.toLowerCase()!==r):e}(s,l,"ops"===a));if(c)return qu(su(c));const d=function(e,t){return"organization"!==e?null:t&&0!==t.length?sb.every(e=>t.includes(e))?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 qu(su(d));if(o?.includes("function")){const t=Jf(await Bf(r,e.project_id));if(t)return qu(t)}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:Yu()}):await r.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"create",p_field:"ops"===a?{...l,op_id:ya()}:l,p_field_name:null,p_actor_user_id:Yu()});if(p)throw p;return Iu(Xd({field:u?.field??l,..."organization"===e.scope?{created_projects:u?.created_projects??[],skipped_projects:u?.skipped_projects??[]}:{},..."number"==typeof u?.values_outside_options?{values_outside_options:u.values_outside_options}:{},message:xb(l.name,u)}))}catch(r){const a=cv(n,t,r);return a?Mb(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(vu(r))}}async function Ob(e,t){let n;try{const r=await Bu();try{await np(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return qu(tn("project"));throw e}const a=t??await iv(r,e.project_id);if("unreadable"===a)return sv();n=a;const i=e.name.trim();if(bv("atoms_delete_field",e.project_id)){const t={tool:"atoms_delete_field",project_id:e.project_id,target:i};if(!e.confirmation_token){const n=await ab(r,e.project_id,[{name:i}]),a=kv(t);return Iu(Xd({status:"confirmation_required",preview:{field_name:i,items_with_values:n[i]??0},confirmation_token:a.token,expires_at:a.expires_at,expires_in_seconds:a.expires_in_seconds,message:`Re-call atoms_delete_field with the same project_id, name, and confirmation_token within ${a.expires_in_seconds}s to execute.`}))}const n=jv(e.confirmation_token,t);if(!n.valid)return qu(su(`confirmation_token rejected: ${n.reason}`))}const{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:ya()}:null,p_field_name:i,p_actor_user_id:Yu()});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),Iu(Xd({deleted:s?.deleted??i}))}catch(r){const a=cv(n,t,r);return a?Ob(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(vu(r))}}async function Eb(e){try{const t=await Bu();try{await np(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return qu(tn("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 qu(su("names must be a non-empty array of existing field names, in the order you want them"));const r=await hb(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 qu(su(`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:Yu()});if(o)throw o;return Iu(Xd({fields:gb(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e))}}D(_b,{PROJECT_FIELD_TYPES:()=>ub,PROJECT_FIELD_VALUE_MAX:()=>mb,canonicalizeFieldKeys:()=>vb,createFieldHandler:()=>Mb,createdFieldMessage:()=>xb,deleteFieldHandler:()=>Ob,findUnknownFieldNames:()=>wb,getProjectFields:()=>hb,isProjectFieldNumber:()=>jb,isStoredFieldValue:()=>bb,listFieldsHandler:()=>qb,normalizeProjectFields:()=>gb,reorderFieldsHandler:()=>Eb,validateAndCanonicalizeFieldValues:()=>kb,validateProjectFieldDefinition:()=>yb,validateProjectFieldValuesForWrite:()=>$b});var zb=P({"src/tools/fields.ts"(){sp(),zu(),vd(),cb(),an(),ai(),Av(),vv(),s_(),fb(),ub=["text","long","bool","date","person","select","number","link"],pb=new Set(ub),mb=2e3}}),Rb={};async function Tb(e){try{const t=await Bu();try{await tp(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const n=await Py(t,e.project_id);if(null===n)return qu(Ta());if(e.type=ah(e.type),ih(e.type)){const n=await lh(t,e.project_id);if(n)return qu(n);const r="goal"===e.type?gh(Object.keys(e.fields??{})):[];if(r.length>0)return qu(su(yh("A Safety goal",r),Ud))}e.title=Su(e.title),void 0!==e.body&&(e.body=Su(e.body)),void 0!==e.summary&&(e.summary=Su(e.summary)),void 0!==e.level&&(e.level=Su(e.level)),e.domains&&(e.domains=e.domains.map(e=>Su(e)));const r=(e.domains??[]).map(Zd).filter(e=>e.length>0),a=void 0!==e.level?await Cv(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=Nc(r,Dc(n?.function_tags),Zd);if(s.length>0)return qu(su(Hc(s),Ud));if(i.length>0){const e=new Set(i.map(Zd).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return qu(su(`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(()=>(zb(),_b)),a=await n(t,e.project_id),s=await r(t,e.project_id,a,e.fields);if(s.error)return qu(su(s.error));i=s.fields}if(void 0!==e.req_type){const t=qp(e.req_type,e.type);if(t)return qu(su(t,Ud))}if("function"===e.type){const n=Jf(await Bf(t,e.project_id));if(n)return qu(n);const r=await async function(e,t,n,r,a){if(0===r.length)return null;const i=await tb(e,t,r,a);for(const e of r){const t=i.get(e);if(!t)continue;const r=eb("the new item",n,t.id,t.type);if(r)return r}return null}(t,e.project_id,e.type,e.parent_ids??[],On);if(r)return qu(su(r))}const s={sanitizedDomains:r,sanitizedLevel:a,canonicalFields:i};return await Pa(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=Yu(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n,o=[...new Set(t.parent_ids??[])],l=$a({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=ja("atoms_create_item"),u=await ga(c?va({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:[]}):wa({userId:r,projectId:t.project_id,content:l,k:0,sessionId:q$()})),p=c?await La(l):void 0,m=(await Ba(e,t.project_id,[{op_id:u,content_hash:p}])).get(u);if(m&&("applied"===m.status||"noop"===m.status)&&m.item_id)return Iu(Xd({id:m.item_id,type:t.type,title:t.title,project_id:t.project_id,replayed:!0,message:yr,seq:m.seq??null}));const f=(await rv(e,t.project_id,{[tv(t.type)]:1}))[tv(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}:{}},h=[{op_id:u,kind:"create_item",item_id:f,path:[],value:{type:t.type,title:t.title,data:_},...p?{content_hash:p}:{}}];for(const e of o)h.push({op_id:c?await ga(va({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:["relationships","parents","add",e]})):ya(),kind:"add",item_id:f,path:["relationships","parents"],value:e});const g=await Hy(e,t.project_id,h,{mode:"single"});if(void 0!==g.error&&0===g.results.length)throw g.error;const y=await Ga(e,t.project_id,g.answers,h),w=await Uy({client:e,projectId:t.project_id,answers:y,ops:h,results:g.results,relooked:!0});await By(e,t.project_id,h,y,"created");const v=y.find(e=>e.op_id===u);if("invalid"===v?.status&&"op_id_reused"===v.reason)return qu(tu(hr,["Send the call again with a new idempotency_key, or without one"],{code:"op_id_reused",retryable:!1}));if(w.not_applied.length>0)return Vy(w,{id:f,type:t.type});const b=v?.item_id??f,k=!0===v?.replayed,j=v?.revision_id??null;let x,S;if(j){const n=await Yr(e,t.project_id,[j]).then(e=>e.get(j),()=>null);null===n?S=gr:n&&(x=await Wr(n,"all"))}const $={id:b,type:t.type},A={...x?{base_token:x}:{},...ha(w),...k?{replayed:!0,message:yr}:{},...S?{warning:S}:{}};return!1===t.echo?Iu(Xd({...$,...A})):Iu(Xd({...$,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=Yu(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n;{const n=tv(t.type),l=async()=>(await rv(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=>Sd(()=>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:q$()??null,p_diff_summary:null}),{scope:t.project_id});let p=await l(),m=d(p),{error:f}=await u(m);if(f&&(o=f)&&/^item_exists\b/.test(String(o.message??"").trim())&&(p=await l(),m=d(p),({error:f}=await u(m))),Ny("main",f),f)throw new Error(f.message);const _=i?qv(i,await Pv(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 Sd(()=>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"}),{scope:t.project_id,afterWrite:!0});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 g=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:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===t.echo?Iu(Xd({id:p,type:t.type,..._?{level_note:_}:{},...g})):Iu(Xd({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,..._?{level_note:_}:{},...g}))}var o}(t,e,s))}catch(e){const t=bu(e);return qu(t||vu(e))}}D(Rb,{createItemHandler:()=>Tb});var Cb=P({"src/tools/create-item.ts"(){sp(),av(),E$(),zu(),Kv(),Mv(),Wc(),Rp(),s_(),Nh(),rb(),kr(),Rd(),ai(),Ky(),zu()}});function Pb(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 Db(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 Nb,Hb=P({"src/core/change-control.ts"(){}});var Fb,Lb,Ub=P({"src/core/content-ids.ts"(){Nb={row:"r",column:"c",step:"st",param:"p"}}});function Wb(e,t){const n=Fb[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)+Wb(e.slice(r),t.slice(r))}const r=e?Fb.indexOf(e[0]):0,a=null!==t?Fb.indexOf(t[0]):Fb.length;return a-r>1?Fb[Math.round(.5*(r+a))]:t&&t.length>1?t.slice(0,1):Fb[r]+Wb(e.slice(1),null)}function Vb(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 Bb(e){if(e.length!==Vb(e[0]))throw new Error(`invalid integer part of order key: ${e}`)}function Gb(e){const t=Vb(e[0]);if(t>e.length)throw new Error(`invalid order key: ${e}`);return e.slice(0,t)}function Jb(e){if(e===Lb)throw new Error(`invalid order key: ${e}`);const t=Gb(e);if(e.slice(t.length).slice(-1)===Fb[0])throw new Error(`invalid order key: ${e}`)}function Qb(e){Bb(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=Fb.indexOf(n[e])+1;t===Fb.length?n[e]=Fb[0]:(n[e]=Fb[t],r=!1)}if(r){if("Z"===t)return`a${Fb[0]}`;if("z"===t)return null;const e=String.fromCharCode(t.charCodeAt(0)+1);return e>"a"?n.push(Fb[0]):n.pop(),e+n.join("")}return t+n.join("")}function Yb(e,t){if(null!==e&&Jb(e),null!==t&&Jb(t),null!==e&&null!==t&&e>=t)throw new Error(`${e} >= ${t}`);if(null===e){if(null===t)return`a${Fb[0]}`;const e=Gb(t),n=t.slice(e.length);if(e===Lb)return e+Wb("",n);if(e<t)return e;const r=function(e){Bb(e);const t=e[0],n=e.slice(1).split(""),r=Fb[Fb.length-1];let a=!0;for(let e=n.length-1;a&&e>=0;e-=1){const t=Fb.indexOf(n[e])-1;-1===t?n[e]=r:(n[e]=Fb[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=Gb(e),n=e.slice(t.length),r=Qb(t);return null===r?t+Wb(n,null):r}const n=Gb(e),r=e.slice(n.length),a=Gb(t),i=t.slice(a.length);if(n===a)return n+Wb(r,i);const s=Qb(n);if(null===s)throw new Error("cannot increment any more");return s<t?s:n+Wb(r,null)}function Kb(e,t,n){return Yb(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 Zb,Xb,ek=P({"src/core/order-key.ts"(){Ub(),Fb="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Lb=`A${"0".repeat(26)}`}});function tk(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nk(e,t){return e<t?-1:e>t?1:0}function rk(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)=>rk(e,t[n]));if(tk(e)&&tk(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=>rk(e[n],t[n]))}return!1}function ak(e){return tk(e)&&"string"==typeof e.id?`id:${e.id}`:`json:${ik(e)}`}function ik(e){return Array.isArray(e)?`[${e.map(ik).join(",")}]`:tk(e)?`{${Object.keys(e).filter(t=>void 0!==e[t]).sort(nk).map(t=>`${JSON.stringify(t)}:${ik(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function sk(e,t,n,r={}){if(r.skip?.(e))return[];if(1===e.length&&"relationships"===e[0]?(tk(t)||(t={}),tk(n)||(n={})):2===e.length&&"relationships"===e[0]&&(Array.isArray(t)||(t=[]),Array.isArray(n)||(n=[])),rk(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(ak)),s=new Set(a.map(ak)),o=[];for(const t of r)s.has(ak(t))||o.push({kind:"remove",path:[...e],value:t});for(const t of a)i.has(ak(t))||o.push({kind:"add",path:[...e],value:t});return o}(e,t,n);if(tk(t)&&tk(n)){const a=new Set([...Object.keys(t),...Object.keys(n)]),i=[];for(const s of[...a].sort(nk))0===e.length&&r.ignoreKeys?.has(s)||i.push(...sk([...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 ok(e){const t={};for(const n of Object.keys(e))Zb.has(n)||void 0===e[n]||(t[n]=e[n]);return t}function lk(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[Yb(null,t)];{let e=Yb(null,t);const r=[e];for(let a=0;a<n-1;a+=1)e=Yb(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`${Nb[e]}_${n}`}(Xb[e])),p.add(r),r}),f=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()}(_.map(e=>f[e])).map(e=>_[e])),g=[],y=new Set(m);t.forEach((t,n)=>{""===d[n]||u.get(d[n])!==n||y.has(d[n])||g.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[f[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=Kb(w,r,s);w.push(o),v[t]=o,f[t]<0?g.push({kind:a,path:[e],value:ok(n[t]),row_id:m[t],order_key:o}):g.push({kind:i,path:[e],base:l[f[t]],row_id:m[t],order_key:o})}for(let a=0;a<n.length;a+=1)f[a]<0||g.push(...sk([e,m[a]],ok(t[f[a]]),ok(n[a]),{skip:r.skip}));return g}var ck,dk=P({"src/core/content-ops.ts"(){Ub(),ek(),Zb=new Set(["id","order_key","created_seq"]),Xb={steps:"step",params:"param",rows:"row",columns:"column"}}});function uk(e){const t=e?.analysis_props;return t&&"object"==typeof t&&!Array.isArray(t)?t:null}function pk(e,t){if(!0!==uk(e)?.approved)return!1;const n=uk(t?.data);return null!==n&&!0!==n.approved}var mk=P({"src/core/human-check.ts"(){ck="approval cleared (a signature never covers content the approver did not see)"}}),fk={};async function _k(e){try{const n=await Bu();try{await tp(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const r=await Py(n,e.project_id);if(null===r)return qu(Ta());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?qu({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 Pa(r?"ops":"main",t=>"ops"===t?async function(e,t){const n=Yu(),r=Array.isArray(t.updates);if(!r&&!t.item_id)return qu(su("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(jp(n));const a=await hk(e,t.project_id,n,c,s),d=Qy(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:f}=a.refusal;if(!r)return qu(m?nu("Item",n):su(u,f?Ud:void 0));if(!i)return qu(su(`Batch stopped at "${n}": ${u.replace(/\.$/,"")}. Nothing was saved.`,f?Ud: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 ta({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(ea(n));if(a)for(const t of gk(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 ga(va({userId:n,projectId:t.project_id,family:ja("atoms_update_item"),key:t.idempotency_key,itemIdOrK:e.item_id??"",path:Jy(e)})):ya(),t.idempotency_key&&await Ua(e),t.reason&&(e.reason=t.reason);let f={answers:[],results:[],notSent:[]};if(m.length>0&&(f=await Hy(e,t.project_id,m,{mode:c}),void 0!==f.error&&0===f.results.length))throw f.error;const _=[...l,...p,...f.answers,...za(f.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 g=await Uy({client:e,projectId:t.project_id,answers:_,ops:m,results:f.results,labels:{stepNumber:e=>h.get(e)}}),y=r?crypto.randomUUID():void 0;if(await By(e,t.project_id,m,f.answers,"updated",{batch_id:y,reason:t.reason}),g.not_applied.length>0)return Vy(g,{...r?{batch_id:y}:{id:t.item_id},...Fy(f)});const w=new Map;for(const e of[...g.applied]){if(!e.item_id)continue;const t=Gy(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 g.captured)e.item_id&&v.set(e.item_id,Wy(e));const b=uv(f.answers)?{acceptance_revoked:!0}:{},k=new Set(f.answers.filter(e=>!0===e.approval_cleared&&e.item_id).map(e=>e.item_id)),j=e=>k.has(e)?{approval_cleared:!0}:{};if(r){const e=o.map(e=>v.has(e.itemId)?null!==v.get(e.itemId)?Pb(e.itemId,v.get(e.itemId)):Db(e.itemId):{id:e.itemId,updated_fields:w.get(e.itemId)??[],...j(e.itemId)});return Iu(Xd({batch_id:y,updated:e.length,results:!1===t.echo?void 0:e,errors:[],...b,...ha(g),...Fy(f)}))}const x=t.item_id;if(v.has(x)){const e=v.get(x);return Iu(Xd(null!=e?Pb(x,e):Db(x)))}const S=w.get(x)??[];if(!1===t.echo)return Iu(Xd({id:x,updated_fields:S,...j(x),...b,...ha(g)}));const $=await Qr(e,t.project_id,[x]).then(e=>e.get(x),()=>null);if(null===$)return Iu(Xd({id:x,updated_fields:S,...j(x),...b,...ha(g),warning:gr}));const A=$?.fields_snapshot??{},I=A.data??{};return Iu(Xd({id:x,type:A.type??o[0]?.type,title:A.title??I.title??"",summary:I.summary??"",body:I.body??"",domains:I.tags?.domains??[],level:I.tags?.level??"",...I.req_type?{req_type:I.req_type}:{},updated_fields:S,...$?{base_token:await Wr($,"core")}:{},...j(x),...b,...ha(g)}))}(n,e):async function(e,t){{const n=Yu(),r=async(r,a,i,s)=>{const o=await ky(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&&Pm(o))return{updated_fields:[],error:Dm(r)};if(void 0!==a.status&&Nm(o,a.status))return{updated_fields:[],error:Hm(r)};void 0!==a.title&&(a.title=Su(a.title)),void 0!==a.body&&(a.body=Su(a.body)),void 0!==a.summary&&(a.summary=Su(a.summary)),void 0!==a.level&&(a.level=Su(a.level)),void 0!==a.domains&&(a.domains=a.domains.map(e=>Su(e))),void 0!==a.steps&&(a.steps=zm(a.steps,e=>Su(e))),void 0!==a.params&&(a.params=Tm(zm(a.params,e=>Su(e)),o.data.params));const c=void 0!==a.domains?a.domains.map(Zd).filter(e=>e.length>0):void 0,d=void 0!==a.level?await Cv(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=Nc(c,Dc(n?.function_tags),Zd);if(i.length>0)return{updated_fields:[],error:Hc(i)};if(a.length>0){const e=new Set(a.map(Zd).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=[],f=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==a.title&&f(o.data.title,a.title)&&(p.title=a.title,m.push("title")),void 0!==a.body&&f(o.data.body,a.body)&&(p.body=a.body,m.push("body")),void 0!==a.summary&&f(o.data.summary,a.summary)&&(p.summary=a.summary,m.push("summary")),void 0!==c&&f(o.data.tags?.domains??[],c)&&(p.tags={...p.tags,domains:c},m.push("domains")),void 0!==d&&f(o.data.tags?.level,d)&&(p.tags={...p.tags,level:d},m.push("level")),void 0!==a.status&&f(o.data.status,a.status)&&(p.status=a.status,m.push("status")),void 0!==a.req_type){const e=qp(a.req_type,o.type);if(e)return{updated_fields:[],error:e};f(o.data.req_type,a.req_type)&&(p.req_type=a.req_type,m.push("req_type"))}if(void 0!==a.steps&&f(o.data.steps,a.steps)&&(p.steps=a.steps,m.push("steps")),void 0!==a.params&&f(o.data.params,a.params)&&(p.params=a.params,m.push("params")),void 0!==a.fields&&Object.keys(a.fields).length>0){const n="goal"===o.type?gh(Object.keys(a.fields)):[];if(n.length>0)return{updated_fields:[],error:yh(o.id,n)};const{getProjectFields:r,validateProjectFieldValuesForWrite:i,canonicalizeFieldKeys:s}=await Promise.resolve().then(()=>(zb(),_b)),l=await r(e,t.project_id),c=await i(e,t.project_id,l,a.fields,o.data.fields);if(c.error)return{updated_fields:[],error:c.error};const d=s(l,o.data.fields??{});for(const[e,t]of Object.entries({...s(l,a.fields),...c.fields??{}}))""===t?delete d[e]:d[e]=t;f(o.data.fields??{},d)&&(p.fields=d,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 _=a.title??o.title,{data:h,error:g}=await e.rpc("save_item_with_revision",{p_item_id:r,p_project_id:t.project_id,p_type:o.type,p_title:_,p_data:p,p_user_id:n,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:s?{reason:s}:null,p_expected_updated_at:a.expected_updated_at??o.updated_at});if(Ny("main",g),g)return{updated_fields:[],error:g};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 y=m.includes("level")&&d?qv(d,await Pv(e,t.project_id,d)):null,w=pk(o.data,h);var v;w&&(p.analysis_props=(v=h,uk(v?.data)));const b={item_id:r,project_id:t.project_id,changed_by:n,event_type:"updated",old_data:u,new_data:p,actor:M$(),session_id:q$()};i&&(b.batch_id=i);const k=function(e,t){return t?e?`${e}; ${ck}`:ck:e||void 0}(s,w);if(k&&(b.reason=k),await e.from("change_history").insert(b).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,...y?{levelNote:y}:{},...w?{approvalCleared:w}:{}}};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,approvalCleared:p}=await r(s.item_id,s,e,t.reason);if(d){if(ku(d))return qu(vu(d));if(!n){const e=d instanceof Error?d.message:String("object"==typeof d&&d&&"message"in d?d.message??"":d),t=Y(e);return qu(null!==t?{...t,message:`Batch stopped at "${s.item_id}": ${t.message} ${a.length} item(s) already updated.`}:su(`Batch stopped at "${s.item_id}": ${e.replace(/\.$/,"")}. ${a.length} item(s) already updated.`,e.includes("Function-flagged tag")||Ip(e)?Ud:void 0))}i.push({item_id:s.item_id,error:String(d)})}else void 0!==l?a.push(Pb(s.item_id,l)):c?a.push(Db(s.item_id)):a.push({id:s.item_id,updated_fields:o,...u?{level_note:u}:{},...p?{approval_cleared:!0}:{}})}const s=[...new Set(a.flatMap(e=>"level_note"in e&&e.level_note?[e.level_note]:[]))];return Iu(Xd({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 qu(su("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,approvalCleared:u}=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")?qu(nu("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(hm)||e.includes(gm)}(e)?qu(su(e,e.includes("Function-flagged tag")||Ip(e)?Ud:void 0)):fu(e)||ku(c)?qu(vu(c)):qu(ju(e))}if(void 0!==o)return Iu(Xd(Pb(t.item_id,o)));if(l)return Iu(Xd(Db(t.item_id)));if(!1===t.echo)return Iu(Xd({id:t.item_id,updated_fields:a,...d?{level_note:d}:{},...u?{approval_cleared:!0}:{}}));const p=i??{};return Iu(Xd({id:t.item_id,type:s,title:p.title??"",summary:p.summary??"",body:p.body??"",domains:p.tags?.domains??[],level:p.tags?.level??"",...p.req_type?{req_type:p.req_type}:{},updated_fields:a,...d?{level_note:d}:{},...u?{approval_cleared:!0}:{}}))}}(n,e))}catch(e){const t=bu(e);return qu(t||vu(e))}var t}async function hk(e,t,n,r,a){const i=await ky(e,t,n);if(!i)return{refusal:{message:`Item "${n}" not found`,path:null,notFound:!0}};if(void 0!==r.status&&Pm(i))return{refusal:{message:Dm(n),path:["status"]}};if(void 0!==r.status&&Nm(i,r.status))return{refusal:{message:Hm(n),path:["status"]}};const s=[],o=[],l=(e,t)=>{s.push(e),o.push(t)};if(void 0!==r.title&&l(["title"],Su(r.title)),void 0!==r.summary&&l(["summary"],Su(r.summary)),void 0!==r.body&&l(["body"],Su(r.body)),void 0!==r.req_type){const e=qp(r.req_type,i.type);if(e)return{refusal:{message:e,path:["req_type"],long:!0}};l(["req_type"],r.req_type)}if(void 0!==r.status&&l(["status"],r.status),void 0!==r.level&&l(["tags","level"],await Cv(e,t,Su(r.level))),void 0!==r.domains){const e=r.domains.map(e=>Zd(Su(e))).filter(e=>e.length>0);if(e.length>0){const t=await a.read(),n=Nc(e,Dc(t.function_tags),Zd);if(n.length>0)return{refusal:{message:Hc(n),path:["tags","domains"],long:!0}};if(t.domains.length>0){const n=new Set(t.domains.map(Zd).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 a="goal"===i.type?gh(Object.keys(r.fields)):[];if(a.length>0)return{refusal:{message:yh(n,a),path:["fields"],long:!0}};const{getProjectFields:s,validateProjectFieldValuesForWrite:o,canonicalizeFieldKeys:c}=await Promise.resolve().then(()=>(zb(),_b)),d=await s(e,t),u=await o(e,t,d,r.fields,i.data.fields);if(u.error)return{refusal:{message:u.error,path:["fields"]}};for(const[e,t]of Object.entries({...c(d,r.fields),...u.fields??{}}))l(["fields",e],""===t?null:t)}return void 0!==r.steps&&l(["steps"],zm(r.steps,e=>Su(e))),void 0!==r.params&&l(["params"],zm(r.params,e=>Su(e))),{entry:{paths:s,values:o,type:i.type,steps:i.data.steps}}}function gk(e,t,n){const r=e=>Array.isArray(e)?e:[];return 1===e.length&&"steps"===e[0]?function(e,t){return lk("steps",e??[],t??[])}(r(t),r(n)):1===e.length&&"params"===e[0]?function(e,t){return lk("params",e??[],t??[],{implicitIds:!0})}(r(t),r(Tm(n,t))):sk([...e],void 0===t?null:t,n)}D(fk,{updateItemHandler:()=>_k});var yk,wk=P({"src/tools/update-item.ts"(){Ap(),sp(),qy(),E$(),Rp(),re(),Zm(),zu(),Kv(),Mv(),Hb(),Wc(),ai(),dk(),Ky(),zu(),Nh(),vv(),mk()}}),vk={};async function bk(e){try{const t=await Bu();Yu();try{await tp(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const n=await Py(t,e.project_id);if(null===n)return qu(Ta());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 qu(nu("Item",e.item_id));if(r.deleted_at)return qu(su(`Item ${e.item_id} is already deleted`));if(bv(yk,e.project_id)){const t={tool:yk,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const n=kv(t);return Iu(Xd({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=jv(e.confirmation_token,t);if(!n.valid)return qu(su(`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 Pa(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:ya(),kind:"trash_item",item_id:t.item_id,path:[]}],a=await Hy(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await Uy({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await By(e,t.project_id,r,a.answers,"deleted"),i.not_applied.length>0?Vy(i,{id:t.item_id}):Iu(Xd({...n,...ha(i)}))}(t,e,a):async function(e,t,n,r){const a=Yu(),{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:M$(),p_session_id:q$()});if(Ny("main",i),i)throw new Error(i.message);return Iu(Xd(r))}(t,e,r,a))}catch(e){const t=bu(e);return qu(t||vu(e))}}D(vk,{deleteItemHandler:()=>bk});var kk=P({"src/tools/delete-item.ts"(){sp(),qy(),E$(),Av(),zu(),ai(),Ky(),zu(),yk="atoms_delete_item"}}),jk={};async function xk(e){try{const t=await Bu(),n=Yu();try{await tp(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const r=await Py(t,e.project_id);if(null===r)return qu(Ta());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 qu(nu("Item",e.item_id));if(!a.deleted_at){if(!r){const n=await Sk(t,e.project_id,e.item_id);if(n.error)return qu(Cd(e.item_id,$k(n)))}return qu({status:"error",message:`Item ${e.item_id} is not deleted and cannot be restored.`+(r?"":" Its links were checked and any missing ones rebuilt."),next_steps:["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 qu(Td());if(!0!==e.confirm)return Iu(function(e){const t=e.days_in_trash??0;return{status:"needs_confirmation",message:`${e.item_id} "${e.title??""}" is in Trash. ${Pd(e)} moved it there on ${Dd(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:[...Od],id:e.item_id,title:e.title??"",restored:!1,trashed_by:Pd(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:Nd(l,n)};return await Pa(r?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:ya(),kind:"restore_item",item_id:t.item_id,path:[]}],a=await Hy(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await Uy({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await By(e,t.project_id,r,a.answers,"restored"),i.not_applied.length>0?Vy(i,{id:t.item_id}):Iu(Xd({...n,...ha(i)}))}(t,e,c):async function(e,t,n,r){const a=Yu(),{error:i}=await async function(e,t){const n=e=>"PGRST202"===e?.code||"42883"===e?.code,r={p_project_id:t.projectId,p_item_ids:[t.itemId],p_user_id:t.userId};let{error:a}=await e.rpc("restore_items_with_revision",t.sessionId?{...r,p_event_session_id:t.sessionId}:r);if(t.sessionId&&n(a)&&({error:a}=await e.rpc("restore_items_with_revision",r)),!n(a))return{error:a??null};const{error:i}=await e.rpc("save_item_with_revision",{p_item_id:t.itemId,p_project_id:t.projectId,p_type:t.item.type,p_title:t.item.title,p_data:t.item.data,p_user_id:t.userId,p_event_source:"restore",p_event_session_id:t.sessionId,p_diff_summary:{changed_fields:["deleted_at"],restored:!0},p_expected_updated_at:t.item.updated_at});return{error:i??null}}(e,{projectId:t.project_id,itemId:t.item_id,userId:a,item:n,sessionId:q$()??null});if(Ny("main",i),i)throw i;const s=await Sk(e,t.project_id,t.item_id);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:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),s.error?qu(Cd(t.item_id,$k(s))):Iu(Xd(r))}(t,e,a,c))}catch(e){const t=bu(e);return qu(t||vu(e))}}function Sk(e,t,n){return Ad(()=>e.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:t,p_item_id:n}))}function $k(e){return{message:e.error?.message??"",code:e.error?.code??null,status:e.status}}D(jk,{restoreItemHandler:()=>xk});var Ak,Ik,qk,Mk=P({"src/tools/restore-item.ts"(){sp(),E$(),Qd(),Rd(),zu(),ai(),Ky(),zu()}}),Ok=P({"src/core/batch-cycle.ts"(){kr()}});function Ek(e){return!!e&&("PGRST202"===e.code||"42883"===e.code||/Could not find the function public\.apply_link_changes|function public\.apply_link_changes\(.*\) does not exist/i.test(e.message??""))}function zk(e){const t={from_id:e.from_id,to_id:e.to_id,type:e.type,action:e.action};return e.role&&(t.role=e.role),e.expected_from_updated_at&&(t.expected_from_updated_at=e.expected_from_updated_at),e.expected_to_updated_at&&(t.expected_to_updated_at=e.expected_to_updated_at),t}async function Rk(e){try{return await e()}catch(e){return{error:{message:e instanceof Error?e.message:String(e)}}}}async function Tk(e,t){let n=1,r=await Rk(e);for(const a of t){if(!bd(r.error??null))break;await _d.sleep(Math.round(a*_d.jitter())),r=await Rk(e),n+=1}return{error:r.error??null,calls:n}}async function Ck(e){const t=e.delays??qk,n=Math.max(1,Math.min(e.chunk??Ak,500)),r=e.eventSource??"mcp",a=[];let i=0,s=!1;for(let o=0;o<e.ops.length;o+=n){const l=e.ops.slice(o,o+n),c=s?null:await Tk(()=>e.client.rpc("apply_link_changes",{p_project_id:e.projectId,p_ops:l.map(zk),p_user_id:e.userId,p_event_source:r,p_wait_ms:Ik}),t);if(c&&(i+=c.calls),!c||c.error&&Ek(c.error)){s=!0;for(let n=0;n<l.length;n+=1){const c=l[n],d=await Tk(()=>e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:c.from_id,p_to_id:c.to_id,p_type:c.type,p_action:c.action,p_user_id:e.userId,p_event_source:r,...c.expected_from_updated_at?{p_expected_from_updated_at:c.expected_from_updated_at}:{},...c.expected_to_updated_at?{p_expected_to_updated_at:c.expected_to_updated_at}:{},...c.role?{p_role:c.role}:{}}),t);if(i+=d.calls,d.error)return{applied:a,error:d.error,failed:[c],notSent:e.ops.slice(o+n+1),calls:i,fallback:s};a.push(c)}}else{if(c.error)return{applied:a,error:c.error,failed:l,notSent:e.ops.slice(o+n),calls:i,fallback:s};a.push(...l)}}return{applied:a,error:null,failed:[],notSent:[],calls:i,fallback:s}}var Pk,Dk=P({"src/core/link-batch.ts"(){Rd(),Ak=100,Ik=3e3,qk=[250,500,1e3]}}),Nk={};async function Hk(e){try{const t=await Bu(),n=Yu();try{await tp(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}let r;const a=async()=>void 0===r?r=await Py(t,e.project_id):r,i=async(r,a,i)=>{const o=await Ck({client:t,projectId:e.project_id,ops:r,userId:n});return 0===o.applied.length&&Ny("main",o.error),o.applied.length>0&&await s(o.applied,a,i),o},s=async(r,a,i)=>{for(const a of r.filter(e=>"affects"===e.type||"affected_by"===e.type))for(const r of[a.from_id,a.to_id]){const a=await ky(t,e.project_id,r);if(!a)continue;const i=Co(a.data);if(!i)continue;const s=await ky(t,e.project_id,i);if(!s)continue;const{revoked:o,parentProps:l}=Po(s.data);if(!o)continue;const c={...s.data,analysis_props:l},{error:d}=await t.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:c,p_user_id:n,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});d&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${s.id}': ${d.message}\n`)}const s=r.map(t=>({item_id:t.from_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:null,new_data:{relationship_change:{action:t.action,type:t.type,from:t.from_id,to:t.to_id}},actor:M$(),session_id:q$(),...a?{batch_id:a}:{},...i?{reason:i}:{}}));await t.from("change_history").insert(s).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})},o=e=>Object.assign(new Error(e?.message??"unknown error"),{code:e?.code??void 0});if(e.operations&&Array.isArray(e.operations)){for(const t of e.operations){if(t.from_id===t.to_id)return qu(su(`Self-reference in batch: "${t.from_id}"`));if("affects"===t.type||"affected_by"===t.type){const e=Zv(t.from_id,t.to_id,t.type);if(e)return qu(su(e))}}const n=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],r=await On(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)),l=n.filter(e=>!s.has(e));if(l.length>0)return qu(nu("Items",l.join(", ")));const c=await nb(t,e.project_id,e.operations,On);if(c)return qu("toolError"in c?c.toolError:su(`${c.validation} No changes applied.`));const d=await async function(e,t,n){const r=e=>"parent"===e.type?[e.from_id,e.to_id]:[e.to_id,e.from_id],a=n.filter(e=>"parent"===e.type||"child"===e.type),i=a.filter(e=>"add"===e.action).map(r);if(0===i.length)return null;const s=new Set(a.filter(e=>"remove"===e.action).map(e=>r(e).join("\0"))),o=new Map;let l=[...new Set(i.flat())];const c=(n,r,a)=>Sn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type",n).in(r,a),mn);for(;l.length>0;){for(const e of l)o.set(e,new Set);for(let e=0;e<l.length;e+=wn){const t=l.slice(e,e+wn);for(const e of await c("parent","from_id",t))"parent"===e.type&&o.get(e.from_id)?.add(e.to_id);for(const e of await c("child","to_id",t))"child"===e.type&&o.get(e.to_id)?.add(e.from_id)}const e=new Set;for(const t of l)for(const n of o.get(t))o.has(n)||e.add(n);l=[...e]}const d=new Map;for(const[e,t]of o)d.set(e,new Set([...t].filter(t=>!s.has(`${e}\0${t}`))));for(const[e,t]of i)d.get(e).add(t);for(const[e,t]of i){if(o.get(e).has(t)&&!s.has(`${e}\0${t}`))continue;const n=new Map([[t,e]]),r=[t];for(;r.length>0;){const t=r.shift();if(t===e){const t=[e];for(let r=n.get(e);r!==e;r=n.get(r))t.push(r);return[e,...t.slice(1).reverse(),e].join(" -> ")}for(const e of d.get(t)??[])n.has(e)||(n.set(e,t),r.push(e))}}return null}(t,e.project_id,e.operations);if(d)return qu(su(`Batch would create a cycle: ${d}. No changes applied.`));const u=e.operations,p=await a();return null===p?qu(Ta()):await Pa(p?"ops":"main",async n=>{if("ops"===n)return Fk(t,e,u,!0);const r=crypto.randomUUID(),a=[...u.filter(e=>"remove"===e.action),...u.filter(e=>"add"===e.action)],s=e=>`${e.action} ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`,l=await i(a,r,e.reason);if(l.error){const e=l.applied,t=vu(o(l.error));return qu({...t,message:`${t.message}\n\nThis batch is not atomic: its operations are applied in calls of up to ${Ak}, each all or nothing. ${e.length} of ${a.length} operation(s) committed before this one failed and were NOT rolled back (batch ${r}). Committed: ${e.length?e.map(s).join("; "):"none"}. Failed (nothing of this call stored): ${l.failed.map(s).join("; ")}.`+(l.notSent.length?` Not sent: ${l.notSent.map(s).join("; ")}.`:""),next_steps:nn(e.length,t)})}return Iu(Xd({batch_id:r,processed:u.length,operations:!1===e.echo?void 0:u}))})}if(!(e.from_id&&e.to_id&&e.type&&e.action))return qu(su("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."));if(e.from_id===e.to_id)return qu(su("Cannot create a relationship between an item and itself"));if("affects"===e.type||"affected_by"===e.type){const t=Zv(e.from_id,e.to_id,e.type);if(t)return qu(su(t))}const l=await nb(t,e.project_id,[{action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type}],On);if(l)return qu("toolError"in l?l.toolError:su(l.validation));const c={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},d=await a();return null===d?qu(Ta()):await Pa(d?"ops":"main",async n=>{if("ops"===n)return Fk(t,e,[c],!1);const r=await On([c.from_id,c.to_id],n=>t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",n));for(const e of[c.from_id,c.to_id])if(!r.some(t=>t.id===e))throw new Error(`Item "${e}" not found`);const a=await i([c],void 0,e.reason);if(a.error)throw o(a.error);return!1===e.echo?Iu(Xd({action:c.action,from_id:c.from_id,to_id:c.to_id})):Iu(Xd({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}`}))})}catch(e){const t=bu(e);return qu(t||vu(e))}}async function Fk(e,t,n,r){const a=Yu(),i=[];for(const e of n){const n={op_id:"",kind:e.action,item_id:e.from_id,path:["relationships",Pk[e.type]],value:e.to_id};n.op_id=t.idempotency_key?await ga(va({userId:a,projectId:t.project_id,family:ja("atoms_link_items"),key:t.idempotency_key,itemIdOrK:e.from_id,path:Jy(n)})):ya(),t.reason&&(n.reason=t.reason),i.push(n)}const s=await Hy(e,t.project_id,i);if(void 0!==s.error&&0===s.results.length)throw s.error;const o=await Uy({client:e,projectId:t.project_id,answers:[...s.answers,...za(s.notSent)],ops:i,results:s.results}),l=r?crypto.randomUUID():void 0;if(await By(e,t.project_id,i,s.answers,"updated",{batch_id:l,reason:t.reason}),o.not_applied.length>0)return Vy(o,{...r?{batch_id:l}:{},...Fy(s)});if(r)return Iu(Xd({batch_id:l,processed:n.length,operations:!1===t.echo?void 0:n,...ha(o),...Fy(s)}));const c=n[0];return!1===t.echo?Iu(Xd({action:c.action,from_id:c.from_id,to_id:c.to_id,...ha(o)})):Iu(Xd({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}`,...ha(o)}))}D(Nk,{linkItemsHandler:()=>Hk});var Lk=P({"src/tools/link-items.ts"(){sp(),qy(),kr(),Ok(),E$(),Nl(),an(),zu(),ai(),Ky(),zu(),rb(),Dk(),Pk={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",affects:"affects",affected_by:"affected_by",allocated_to:"allocated_to",allocated_from:"allocated_from"}}});function Uk(e){if(0===e.length)return{};const t=e.map(e=>e.child_id);return{link_warnings:e.map(e=>({child_id:e.child_id,parent_id:e.parent_id,message:e.message})),warning:`${e.length} imported item${1===e.length?" was":"s were"} created but not yet listed under ${1===e.length?"its parent":"their parents"}: ${t.join(", ")}. Repair: call atoms_link_items with type 'parent', from_id=<child_id>, to_id=<parent_id> for each entry of link_warnings. Do not import them again.`}}var Wk,Vk,Bk=P({"src/core/bulk-parent-links.ts"(){Rd(),Dk()}}),Gk={};function Jk(e){return!!Qk(e)||new Set(["22023","23503","23505","23514"]).has(e.code??"")}function Qk(e){return!!e&&null!==zr(String(e.message??""))}function Yk(e,t){return e.items.length>t?qu(su(`Maximum ${t} items per call (received ${e.items.length}). Split into multiple calls.`)):null}async function Kk(e){try{if(!e.items||0===e.items.length)return qu(su("items array must contain at least 1 item"));const t=Yk(e,Wk);if(t)return t;const n=await Bu();try{await tp(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const r=await Py(n,e.project_id);if(null===r)return qu(Ta());if(!r){const t=Yk(e,Vk);if(t)return t}if(e.items.some(e=>"function"===e.type)){const t=Jf(await Bf(n,e.project_id));if(t)return qu(t);const r=await async function(e,t,n,r){const a=n.map((e,t)=>({item:e,index:t})).filter(({item:e})=>"function"===e.type&&"string"==typeof e.parent_id&&e.parent_id.length>0);if(0===a.length)return null;const i=await tb(e,t,a.map(({item:e})=>e.parent_id),r);for(const{item:e,index:t}of a){const n=i.get(e.parent_id);if(!n)continue;const r=eb("the new item",e.type,n.id,n.type);if(r)return{index:t,message:r}}return null}(n,e.project_id,e.items,On);if(r)return qu(su(`Nothing was imported. items[${r.index}]: ${r.message}`))}if(e.items=e.items.map(e=>({...e,type:ah(e.type)})),e.items.some(e=>ih(e.type))){const t=await lh(n,e.project_id);if(t)return qu(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=Dc(r?.function_tags),o=i.length>0?new Set(i.map(Zd).filter(e=>e.length>0)):null,l=Sv(i.map(Zd).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(Zd).filter(e=>e.length>0);if(0===r.length)continue;const a=Nc(r,s,Zd);if(a.length>0){d.add(e),c.push({index:e,title:t.title,error:Hc(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(bv("atoms_bulk_import",e.project_id)){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:Sv({items:e.items,registered_domain_hash:a.registeredDomainHash})};if(!e.confirmation_token){const n=kv(t);return Iu(Xd({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=jv(e.confirmation_token,t);if(!n.valid)return qu(su(`confirmation_token rejected: ${n.reason}`))}return await Pa(r?"ops":"main",t=>"ops"===t?async function(e,t,n){const r=Yu(),a=t.idempotency_key,i=ja("atoms_bulk_import"),s=t.items.some(e=>void 0!==e.level)?await zv(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(Zd).filter(e=>e.length>0),r=void 0!==e.level?Iv(e.level,Zd(e.level),s,Ev):void 0;return{input:e,index:t,domains:n,level:r,content:$a({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=xa(o.map(e=>e.content)),c=[];for(let e=0;e<o.length;e+=1)c.push(await ga(a?va({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:o[e].index,path:[]}):wa({userId:r,projectId:t.project_id,content:o[e].content,k:l[e],sessionId:q$()})));const d=a?await Promise.all(o.map(e=>La(e.content))):[],u=await Ba(e,t.project_id,c.map((e,t)=>({op_id:e,content_hash:d[t]}))),p=[],m=[],f=[];o.forEach((e,t)=>{const n=u.get(c[t]);n&&("applied"===n.status||"noop"===n.status)&&n.item_id?(p.push({id:n.item_id,title:e.input.title,type:e.input.type,replayed:!0}),m.push(n)):f.push({v:e,createId:c[t],contentHash:d[t]})});const _=[...n.errors],h=[],g=new Map;if(f.length>0){const n={};for(const{v:e}of f){const t=tv(e.input.type);n[t]=(n[t]??0)+1}const s=nv(await rv(e,t.project_id,n));for(const{v:e,createId:n,contentHash:o}of f){const l=s(tv(e.input.type));g.set(l,{title:e.input.title,type:e.input.type});const c={summary:e.input.summary,body:e.input.body,tags:{domains:e.domains,level:e.level??""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[]},links:[]};h.push({op_id:n,kind:"create_item",item_id:l,path:[],value:{type:e.input.type,title:e.input.title,data:c},...o?{content_hash:o}:{}}),e.input.parent_id&&h.push({op_id:a?await ga(va({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:e.index,path:["relationships","parents","add",e.input.parent_id]})):ya(),kind:"add",item_id:l,path:["relationships","parents"],value:e.input.parent_id})}}let y={answers:[],results:[],notSent:[]};if(h.length>0&&(y=await Hy(e,t.project_id,h,{mode:"bulk"}),void 0!==y.error&&0===y.results.length))throw y.error;const w=[...await Ga(e,t.project_id,y.answers,h),...za(y.notSent)],v=await Uy({client:e,projectId:t.project_id,answers:w,ops:h,results:y.results,relooked:!0});await By(e,t.project_id,h,w,"created");const b=[...p],k=[...m];for(const e of w){if(!e.item_id||!e.path||0!==e.path.length)continue;if("applied"!==e.status&&"noop"!==e.status)continue;const t=g.get(e.item_id);t&&(b.push({id:e.item_id,title:t.title,type:t.type,...e.replayed?{replayed:!0}:{}}),k.push(e))}const{tokens:j,unread:x}=await _v(e,t.project_id,k);for(const e of b){const t=j.get(e.id);t&&(e.base_token=t)}const S=b.length>0&&b.every(e=>e.replayed),$={created:b.length,items:b,errors:_,project_id:t.project_id,...y.chunks?{chunks:y.chunks}:{},...void 0!==y.error?{error:vu(y.error).message}:{},...S?{replayed:!0,message:yr}:{},...x?{warning:Yn}:{}};return v.not_applied.length>0?Vy(b.length>0&&0===v.applied.length?{...v,applied:b.map(e=>({item_id:e.id,path:[],status:"applied",seq:null,replayed:!0}))}:v,$):Iu(Xd({...$,...ha(v)}),{receipt:"items"})}(n,e,a):async function(e,t,n){const r=Yu();{const a=(new Date).toISOString(),i=q$(),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=tv(e.type);d[t]=(d[t]??0)+1}let u=null,p=null;try{u=nv(await rv(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(tv(e))},f=t.items.some(e=>void 0!==e.level)?await zv(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(Zd).filter(e=>e.length>0),i=void 0!==r.level?Iv(r.level,Zd(r.level),f,Ev):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 Iu(Xd({created:0,items:[],errors:o}));const _=[],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),_.push({id:e,project_id:t.project_id,type:n.type,title:n.title,data:o,created_by:r,updated_by:r})}const g=_.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:y}=await Sd(()=>e.rpc("bulk_save_items_with_revisions",{p_project_id:t.project_id,p_items:g,p_user_id:r,p_event_source:"mcp"}),{scope:t.project_id});Ny("main",y);const w=[];if(y&&Jk(y))for(const{itemId:n,input:a,index:c}of l){const l=_.find(e=>e.id===n);if(!l)continue;const{error:d}=await Sd(()=>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}),{scope:t.project_id});if(d){const e=zr(d.message??"");e&&w.push(d.message??""),o.push({index:c,title:a.title,error:e?.message??d.message})}else s.push({id:n,title:a.title,type:a.type})}else{if(y)throw y;for(const{itemId:e,input:t}of l)s.push({id:e,title:t.title,type:t.type})}const v=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})),b=await async function(e){const t=[],n=e=>({action:"add",from_id:e.from,to_id:e.to,type:"parent"});let r=[...e.links];for(;r.length>0;){const a=await Ck({client:e.client,projectId:e.projectId,userId:e.userId,ops:r.map(n),delays:e.delays});if(!a.error)break;const i=a.error.message??"unknown error",s=a.failed.map(e=>({from:e.from_id,to:e.to_id}));if(!a.fallback&&s.length>1&&!bd(a.error))for(const r of s){const a=await Ck({client:e.client,projectId:e.projectId,userId:e.userId,ops:[n(r)],delays:e.delays});a.error&&t.push({child_id:r.from,parent_id:r.to,message:a.error.message??"unknown error"})}else for(const e of s)t.push({child_id:e.from,parent_id:e.to,message:i});r=a.notSent.map(e=>({from:e.from_id,to:e.to_id}))}for(const n of t)e.warn(`bulk parent link sync failed for ${n.parent_id} (child ${n.child_id}): ${n.message}`);return t}({client:e,projectId:t.project_id,links:v.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 Ad(()=>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 k=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:M$(),session_id:i}));k.length>0&&await e.from("change_history").insert(k).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const j=new Set(s.map(e=>e.id)),x=new Set(l.filter(({itemId:e,sanitizedLevel:t})=>t&&j.has(e)).map(({sanitizedLevel:e})=>e)),S=[];for(const n of x){const r=qv(n,await Pv(e,t.project_id,n));r&&S.push(r)}const $=function(e,t,n){return e>0||0===t.length||0===n.length?null:n.length===t.length?n[0]:null}(s.length,o,w);return $?qu(vu(new Error($))):Iu(Xd({created:s.length,items:s,errors:o.length>0?o:[],project_id:t.project_id,...S.length>0?{level_notes:S}:{},...Uk(b)}),{receipt:"items"})}}(n,e,a))}catch(e){const t=bu(e);return qu(t||vu(e))}}D(Gk,{BULK_IMPORT_MAIN_MAX:()=>Vk,BULK_IMPORT_MAX:()=>Wk,bulkImportHandler:()=>Kk,canRetryBulkImportPerItem:()=>Jk,isItemLockedRefusal:()=>Qk});var Zk=P({"src/tools/bulk-import.ts"(){sp(),av(),E$(),Av(),zu(),Rd(),Bk(),Kv(),Mv(),Wc(),ai(),Ky(),zu(),vv(),s_(),Nh(),rb(),kr(),Wk=500,Vk=100}}),Xk={};async function ej(e){const t=Yu(),n=e.idempotencyKey||await async function(e){return null==e.requestId||""===e.requestId?ya():ga(["append_run_key",e.sessionId,String(e.requestId)])}({sessionId:q$(),requestId:e.requestId}),r=await Promise.all(e.entries.map(e=>async function(e){return Cr(Tr(Sa(e)))}(e))),a=xa(r),i=[];for(let s=0;s<e.entries.length;s+=1){const o=await ga(ba({userId:t,projectId:e.projectId,tool:e.tool,key:n,itemId:e.itemId,runHash:r[s],k:a[s]}));i.push({op_id:o,kind:"append_run",item_id:e.itemId,path:["runs"],value:e.entries[s]})}const s=await ov({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]));let c=null;if(!o)try{c=(await ky(e.client,e.projectId,e.itemId))?.data?.runs??null}catch{c=null}return{run:s,runs:i.map((t,n)=>{const r=l.get(t.op_id);return{result:qm(c,t.op_id,e.entries[n]),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 tj(e,t){let n;try{const r=await Bu(),a=Yu(),i=Ku();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const s=t??await iv(r,e.project_id);if("unreadable"===s)return sv();n=s;const o=await ky(r,e.project_id,e.item_id);if(!o)return qu(nu("Item",e.item_id));if("test-case"!==o.type)return qu(su(`Item '${e.item_id}' is a ${o.type}, not a test-case`));const l=(e.asset??"").trim(),c=Rm({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=>Su(e)),d=Am([e]).length>0?{release_note:rm}:{};if("ops"===s){const t=await ej({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 qu(su(t.refusal,Ud));const n=t.runs[0],s=l?` (asset: ${l})`:"",o=n.result;return lv(t.run.outcome,{item_id:e.item_id,result:o,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?wr:`Test result '${o??"recorded"}' recorded for ${e.item_id}${s}`,...null!==o&&o!==e.result?{verdict_note:Om([0],!0)}:{},...void 0!==e.date&&null!==e.date?{warning:am}:{},...d},t.run,{idempotency_key_used:t.keyUsed})}const u=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,u="string"==typeof s?.result?s.result:qm(null,"",c);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:u,run_at:o,note:c.note,asset:l||null},actor:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const p=l?` (asset: ${l})`:"";return Iu(Xd({item_id:e.item_id,result:u,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 '${u??"recorded"}' recorded for ${e.item_id}${p}`,...null!==u&&u!==e.result?{verdict_note:Om([0],!0)}:{},...void 0!==e.date&&null!==e.date?{warning:am}:{},...d}))};return await u()}catch(r){const a=cv(n,t,r);return a?tj(e,a):qu(vu(r))}}D(Xk,{recordRunsByOps:()=>ej,recordTestResultHandler:()=>tj});var nj=P({"src/tools/record-test-result.ts"(){sp(),qy(),E$(),zu(),Zm(),ai(),vv(),ai()}}),rj={};async function aj(e,t){let n;try{const r=await Bu(),a=Yu(),i=Ku();if(!Array.isArray(e.results)||0===e.results.length)return qu(su("results must be a non-empty array"));if(e.results.length>100)return qu(su(`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?km(e.date):NaN;Number.isNaN(a)||(a<n?t.push(r):n=a)}),t}(e.results);if(s.length>0)return qu(su(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),Ud));try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const o=t??await iv(r,e.project_id);if("unreadable"===o)return sv();n=o;const l=await ky(r,e.project_id,e.item_id);if(!l)return qu(nu("Item",e.item_id));if("test-case"!==l.type)return qu(su(`Item '${e.item_id}' is a ${l.type}, not a test-case`));if("ops"===o){const t=e.results.map(e=>{const t=Rm(e,e=>Su(e)),{date:n,...r}=t;return r}),n=await ej({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 qu(su(n.refusal,Ud));const a=Sm(e.results),i=Am(e.results),s=Mm(e.results,n.runs);return lv(n.run.outcome,{item_id:e.item_id,count:e.results.length,results:n.runs,...s.length>0?{verdict_note:Om(s),verdict_differs_entries:s}:{},message:n.run.outcome.replayed?wr:`Recorded ${e.results.length} test results for ${e.item_id}`,...a.length>0?{warning:$m(a),ignored_date_entries:a}:{},...i.length>0?{release_note:Im(i),no_release_entries:i}:{}},n.run,{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=>Rm(e,e=>Su(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:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const s=Sm(e.results),o=Am(e.results),l=Mm(e.results,t);return Iu(Xd({item_id:e.item_id,count:e.results.length,results:t,message:`Recorded ${e.results.length} test results for ${e.item_id}`,...l.length>0?{verdict_note:Om(l),verdict_differs_entries:l}:{},...s.length>0?{warning:$m(s),ignored_date_entries:s}:{},...o.length>0?{release_note:Im(o),no_release_entries:o}:{}}))};return await c()}catch(r){const a=cv(n,t,r);return a?aj(e,a):qu(vu(r))}}D(rj,{recordTestResultsBulkHandler:()=>aj});var ij=P({"src/tools/record-test-results-bulk.ts"(){sp(),qy(),E$(),zu(),nj(),ai(),vv(),Zm()}}),sj={};async function oj(e){try{const t=Uh(e.depth),n=await Bu(),r=await ky(n,e.project_id,e.item_id);if(!r)return qu(nu("Item",e.item_id));const a=await Sn(()=>n.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn),i=qf(a,await Sn(()=>n.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn)),s=function(e,t=0,n){const{rows:r,meta:a}=od(e.items,t,n),i=t=>{const n=new Set([e.root,...t.map(e=>e.id)]);return e.edges.filter(e=>n.has(e.from)&&n.has(e.to))},s={list:"items",resume:e=>({meta:{next_offset:t+e},data:{edges:i(r.slice(0,e))},next:`offset=${t+e}`})};return{data:{...e,items:r,edges:i(r)},meta:a,paging:s}}(function(e){const t=Uh(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})},s=e=>r.get(e)?.type;for(const t of e.relationships){const r=Fh(t,s),a=r.type;if(n||!Eh.includes(a)){if(("upstream"===e.direction||"both"===e.direction)&&(!Mh.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),Oh.has(a))){const e=zh[a]??a;n&&!n.has(e)||i(r.to_id,r.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!Oh.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),Mh.has(a))){const e=zh[a]??a;n&&!n.has(e)||i(r.to_id,r.from_id,e)}"related"!==a||n&&!n.has("related")||(i(r.from_id,r.to_id,"related"),i(r.to_id,r.from_id,"related"))}}const o=new Set([e.rootItemId]),l=[],c=[],d=[];for(const t of a.get(e.rootItemId)??[])d.push({id:t.neighbor,depth:1,relType:t.relType,from:e.rootItemId});for(let e=0;e<d.length;e++){const{id:n,depth:i,relType:s,from:u}=d[e];if(o.has(n)||i>t)continue;o.add(n);const p=r.get(n);if(p&&(l.push({id:n,title:Hh(p),type:p.type,relationship:s,depth:i,from:u,...Lh(p,r)}),c.push({from:u,to:n,type:s}),i<t))for(const e of a.get(n)??[])o.has(e.neighbor)||d.push({id:e.neighbor,depth:i+1,relType:e.relType,from:n})}const u={id:e.rootItemId,title:Hh(e.rootItem),type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId,...Lh(e.rootItem,r)};return{root:e.rootItemId,project_id:e.projectId,direction:e.direction,depth_limit:t,items:[u,...l],edges:c,total_count:l.length+1}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown",data:r.data},items:a,relationships:i??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types}),e.offset,e.limit);return Iu(Xd(s.data,s.meta),{paging:s.paging})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(sj,{traceHandler:()=>oj});var lj=P({"src/tools/trace.ts"(){sp(),qy(),kr(),Kh(),zu()}}),cj={};async function dj(e){try{const t=await Bu(),n=await Sn(()=>{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)},fn);return Iu(Xd({assets:n,total:n.length}),{complete:!0})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(cj,{listAssetsHandler:()=>dj});var uj=P({"src/tools/assets.ts"(){sp(),kr(),zu()}}),pj={};async function mj(e,t){try{const t=await Qu(e);return t.ok?Iu(Xd(t.data),{complete:!0}):qu(t.error)}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:t}))}}async function fj(e){return mj(async()=>async function(e,t){try{const n=await Zs(e,"model_designs_list",{p_project_id:t.project_id,p_trashed:!1});if(!0!==n?.enabled)return{ok:!1,error:Qs()};const r=(n.designs??[]).map(Vs);return{ok:!0,data:{model_designs:r,total:r.length}}}catch(e){const t=Ys(e);if(t)return{ok:!1,error:t};throw e}}(await Bu(),e),!0)}async function _j(e){return mj(async()=>async function(e,t){try{if(!ps.test(t.display_id))return Ls("validation_error","Validation error: display_id is an MD id such as MD-001",["Use atoms_list_model_designs to see the MD ids"]);const n=await eo(e,t.project_id,t.display_id);if(!n)return{ok:!1,error:Qs()};const r=n.canvas??ss,a=await Xs(e,t.project_id,zs(r).filter(e=>ls.test(e))),i=e=>a.get(e)?.title??null,s=e=>e.filter(e=>ls.test(e)).map(e=>({id:e,title:i(e),type:a.get(e)?.type??null}));return{ok:!0,data:{...Vs(n),model_mermaid:Fs(r,{displayId:n.display_id,name:n.name,description:n.description},i),boxes:r.boxes.filter(e=>e.links.length>0).map(e=>({box_label:e.label,linked_items:s(e.links)})),arrows:r.arrows.filter(e=>e.links.length>0).map(e=>({arrow_label:e.label,linked_items:s(e.links)}))}}}catch(e){const t=Ys(e);if(t)return{ok:!1,error:t};throw e}}(await Bu(),e),!0)}async function hj(e){return mj(async()=>async function(e,t,n={}){try{if(await Ks(e,t.project_id))return{ok:!1,error:$r()};const r=Os(t.name);if(r)return Ls("validation_error",`Validation error: ${r}`,["Give the design a name of 1 to 200 characters"]);const a=Es(t.description??"");if(a)return Ls("validation_error",`Validation error: ${a}`,["Shorten the description to 5000 characters"]);let i,s=ss;if(void 0!==t.mermaid&&""!==t.mermaid.trim()){const n=await to(e,t.project_id,t.mermaid,ss);if(!n.ok)return n.error;s=n.canvas;const r=ao(n.parsed,{name:t.name,description:t.description});if(r)return r;if(void 0===t.description&&null!==n.parsed.description){const e=Es(n.parsed.description);if(e)return Ls("validation_error",`Validation error: ${e}`,["Fix the %% description: line and call again"]);i=n.parsed.description}}const o=await Zs(e,"model_design_create",{p_project_id:t.project_id,p_name:t.name,p_description:t.description??i??"",p_canvas:s,p_source:"mcp",p_tool:"atoms_create_model_design",p_agent_client:n.agentClient??"Claude"});return{ok:!0,data:{...Vs(o),created:!0}}}catch(e){const t=Ys(e);if(t)return{ok:!1,error:t};throw e}}(await Bu(),e,{agentClient:Da(O$())}),!1)}async function gj(e){return mj(async()=>async function(e,t,n={}){try{if(!ps.test(t.display_id))return Ls("validation_error","Validation error: display_id is an MD id such as MD-001",["Use atoms_list_model_designs to see the MD ids"]);if(await Ks(e,t.project_id))return{ok:!1,error:$r()};if(void 0===t.name&&void 0===t.description&&void 0===t.mermaid)return Ls("validation_error","Validation error: send at least one of name, description or mermaid",["Name what to change and call again"]);if(void 0!==t.name){const e=Os(t.name);if(e)return Ls("validation_error",`Validation error: ${e}`,["Give the design a name of 1 to 200 characters"])}if(void 0!==t.description){const e=Es(t.description);if(e)return Ls("validation_error",`Validation error: ${e}`,["Shorten the description to 5000 characters"])}const r=await eo(e,t.project_id,t.display_id);if(!r)return{ok:!1,error:Qs()};if(r.version!==t.expected_version){const e=Number.isNaN(Date.parse(r.updated_at))?String(r.updated_at):new Date(r.updated_at).toISOString().slice(0,16).replace("T"," ");return Ls("stale_version",`Not saved: ${r.updated_by_name} saved version ${r.version} of ${r.display_id} at ${e} UTC.`,["Read the design again with atoms_get_model_design","Apply your change to that version's Mermaid, then call atoms_update_model_design with its version as expected_version"],!0,{current_version:r.version})}let a,i,s=null;if(void 0!==t.mermaid){const o=await to(e,t.project_id,t.mermaid,r.canvas??ss);if(!o.ok)return o.error;s=o.canvas;const l=ao(o.parsed,{name:t.name,description:t.description});if(l)return l;if(void 0===t.name&&null!==o.parsed.name&&Ms(o.parsed.name)!==r.name){const e=Os(o.parsed.name);if(e)return Ls("validation_error",`Validation error: ${e}`,["Fix the %% name: line and call again"]);a=o.parsed.name}if(void 0===t.description&&null!==o.parsed.description&&o.parsed.description!==r.description){const e=Es(o.parsed.description);if(e)return Ls("validation_error",`Validation error: ${e}`,["Fix the %% description: line and call again"]);i=o.parsed.description}if(n.blockDestructive){const e=function(e,t){const n=e=>new Set([...e.boxes,...e.arrows].flatMap(e=>e.links.map(t=>`${e.id}\0${t}`))),r=n(t);if([...n(e)].some(e=>!r.has(e)))return"removing a link";const a=e=>new Set([...e.boxes.map(e=>`b:${e.id}`),...e.arrows.map(e=>`a:${e.id}`),...e.groups.map(e=>`g:${e.id}`)]),i=a(t);return[...a(e)].some(e=>!i.has(e))?"removing a box, arrow or group from a model design":null}(r.canvas??ss,s);if(e)return{ok:!1,error:ro(e)}}}const o=await Zs(e,"model_design_save",{p_design_id:r.id,p_expected_version:t.expected_version,p_name:t.name??a??null,p_description:t.description??i??null,p_canvas:s,p_source:"mcp",p_tool:"atoms_update_model_design",p_agent_client:n.agentClient??"Claude"});return{ok:!0,data:{...Vs(o),updated:!0,...s?no(r.canvas??ss,s):{}}}}catch(e){const t=Ys(e);if(t)return{ok:!1,error:t};throw e}}(await Bu(),e,{agentClient:Da(O$()),blockDestructive:ke(Fe(),e.project_id).block_destructive}),!1)}D(pj,{createModelDesignHandler:()=>hj,getModelDesignHandler:()=>_j,listModelDesignsHandler:()=>fj,updateModelDesignHandler:()=>gj});var yj,wj=P({"src/tools/model-designs.ts"(){sp(),uo(),zu(),ai(),Se(),We(),E$()}}),vj=P({"src/core/bulk-variables.ts"(){kr()}});function bj(e){const t=e.data?.body;return"string"==typeof t?t.toLowerCase():""}function kj(e,t){return"string"==typeof e&&e.toLowerCase().includes(`{${t.toLowerCase()}}`)}async function jj(e,t,n){const r=[...new Set(n.map(e=>e.toLowerCase()))];return 0===r.length?new Map:await async function(e,t,n){const r=await fy(e,"mcp_variable_reference_counts",{p_project_id:t,p_names:[...n]});if(!r)return null;const a=r.data;if(null===a||"object"!=typeof a||Array.isArray(a))return null;const i=new Map;for(const e of n){const t=py(a[e]??0);if(null===t)return null;i.set(e,t)}return i}(e,t,r)??async function(e,t,n){const r=new Map,a=[...new Set(n.map(e=>e.toLowerCase()))];if(0===a.length)return r;if(a.length<=yj)return await Promise.all(a.map(async n=>{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->>body","ilike",function(e){return`%{${e.replace(/[\\%_]/g,e=>`\\${e}`)}}%`}(n));if(i)throw new Error(`items reference count: ${i.message}`);r.set(n,a??0)})),r;const i=await Sn(()=>e.from("items").select("id, body:data->>body").eq("project_id",t).is("deleted_at",null).filter("data->>body","ilike","%{%"),["id"]);for(const e of a)r.set(e,i.filter(t=>kj(t.body,e)).length);return r}(e,t,r)}function xj(e,t){const n=e.map(e=>({v:e,n:t.get(e.name.toLowerCase())??0})).filter(({n:e})=>e>0),r=n.reduce((e,{n:t})=>e+t,0);if(0===r)return{already_referenced_by_items:0};const a=n.slice(0,5).map(({v:e,n:t})=>`${t} item${1===t?"":"s"} already contain${1===t?"s":""} {${e.name}}; ${1===t?"it now reads":"they now read"} ${e.value}${e.unit?` ${e.unit}`:""}.`);return n.length>5&&a.push(`And ${n.length-5} more names.`),{already_referenced_by_items:r,warning:a.join(" ")}}var Sj,$j,Aj=P({"src/core/variable-refs.ts"(){kr(),gy(),yj=10}}),Ij={};async function qj(e,t,n,r){if(n&&r)throw new Wt("baseline_id and as_of are mutually exclusive");if(r)return gn(yy(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 Wt("Baseline not found for this project");return yn(n)}async function Mj(e,t,n){return n?Mn(e,t,n):Sn(()=>e.from("project_variables").select("*").eq("project_id",t),_n)}async function Oj(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 Ej(e,t,n){if(0===n.length||!0!==await Ra(e,t))return n;const r=await Qr(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 Wr(t,"variable","variable")}:e}))}async function zj(e,t,n,r){const a=Yu(),i=ja("atoms_create_variable");return n?{rowId:await ga(va({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables","row_id"]})),opId:await ga(va({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables"]}))}:{rowId:await ga(ka({userId:a,projectId:e,name:t,what:"variable"})),opId:await ga(ka({userId:a,projectId:e,name:t,what:"create_variable"}))}}async function Rj(e){try{const t=await Bu(),n=await qj(t,e.project_id,e.baseline_id,e.as_of),r=await Mj(t,e.project_id,n),a=e.limit??50,i=e.offset??0,s=r.slice(i,i+a);return Iu(Xd({variables:null===n?await Ej(t,e.project_id,s):s,total:r.length},ld(r.length,a,i)),{paging:{list:"variables"}})}catch(e){return qu(vu(e,{read:!0}))}}async function Tj(e){try{const t=await Bu(),n=await qj(t,e.project_id,e.baseline_id,e.as_of),r=(await Mj(t,e.project_id,n)).find(t=>t.name===e.variable_name)??null;if(!r)return qu(nu("Variable",e.variable_name));const a=(await Sn(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn)).filter(t=>kj(t.data?.body,e.variable_name)),[i]=null===n?await Ej(t,e.project_id,[r]):[r];return Iu(Xd({variable:i,referenced_by:a.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:a.length}))}catch(e){return qu(vu(e,{read:!0}))}}async function Cj(e,t){let n;try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();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 qu(nu("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 ta({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:t,tokens:dv(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(ea(a[t]));n&&l.push(ra({op_id:ya(),kind:"set",item_id:null,path:a[t],value:e},n))});const c=await ov({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 lv(c.outcome,!1===e.echo?{name:e.variable_name,updated:!0}:{variable:d},c)}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 Oj(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?Iu(Xd({name:e.variable_name,updated:!0})):Iu(Xd({variable:l}))}catch(r){const a=cv(n,t,r);return a?Cj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}async function Pj(e,t){let n;try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();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 qu(su(`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 qu(su(`Duplicate names in batch (case-insensitive): ${[...new Set(l)].join(", ")}`));const c=await Mj(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 qu(su(`Variable(s) already exist (case-insensitive): ${u.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const p=xj(e.variables,await jj(r,e.project_id,n));if("ops"===i){const t=e.variables,n=await Promise.all(t.map((t,n)=>zj(e.project_id,t.name,e.idempotency_key,n))),a=await Promise.all(t.map((t,r)=>Sj($j(n[r],t),e.idempotency_key))),i=crypto.randomUUID(),s=await ov({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 lv(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.`,...p},s)}const m=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})),f=await async function(e,t,n,r){const a=[...new Set(n)];if(r.length>=a.length)return[...r];const i=await Sn(()=>e.from("project_variables").select("*").eq("project_id",t),_n),s=new Map(i.map(e=>[String(e.name),e])),o=a.filter(e=>!s.has(e));if(o.length>0)throw new Error(`atoms_create_variable: ${o.length} saved variable(s) not found on read back: ${o.slice(0,5).join(", ")}`);return a.map(e=>s.get(e))}(r,e.project_id,m.map(e=>e.name),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,m,a));return Iu(Xd({batch_id:crypto.randomUUID(),created:(f??[]).length,variables:!1===e.echo?(f??[]).map(e=>({name:e.name})):f??[],message:`${(f??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`,...p}))}if(!e.name||!e.value)return qu(su("Provide either (name, value) for single variable or variables[] for batch."));if(!s.test(e.name))return qu(su(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const o=(await Mj(r,e.project_id,null)).find(t=>t.name.toLowerCase()===e.name.toLowerCase());if(o)return qu(su(`Variable "${o.name}" already exists in this project (names are unique regardless of case).`));const l=xj([e],await jj(r,e.project_id,[e.name]));if("ops"===i){const t=await zj(e.project_id,e.name,e.idempotency_key,0),n=await ov({client:r,projectId:e.project_id,ops:[await Sj($j(t,e),e.idempotency_key)],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 lv(n.outcome,!1===e.echo?{name:e.name,...l}:{variable:a,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`,...l},n)}const c=await Oj(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?Iu(Xd({name:e.name,...l})):Iu(Xd({variable:c,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`,...l}))}catch(r){const a=cv(n,t,r);return a?Pj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}async function Dj(e,t){let n;try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();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 qu(nu("Variable",e.name));const o=(await jj(r,e.project_id,[e.name])).get(e.name.toLowerCase())??0;if(o>0&&!e.force)return qu(su(`Variable "${e.name}" is referenced in ${o} item${o>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(bv("atoms_delete_variable",e.project_id)){const t={tool:"atoms_delete_variable",project_id:e.project_id,target:e.name};if(!e.confirmation_token){const n=kv(t);return Iu(Xd({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:o,would_orphan_references:o>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=jv(e.confirmation_token,t);if(!n.valid)return qu(su(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t=["variables",String(s.id)],n=await ta({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:String(s.id),tokens:dv(e.base_token),paths:[t],values:[null],name:e.name}]}),a=n.items.get(String(s.id))?.bases.get(ea(t)),i=a?[ra({op_id:ya(),kind:"remove",item_id:null,path:["variables"],row_id:String(s.id),value:null},a)]:[],l=await ov({client:r,projectId:e.project_id,ops:i,refusals:n.refusals});return lv(l.outcome,{deleted:!0,name:e.name,referenced_by_items:o,warning:o>0?`${o} item${o>1?"s":""} still contain {${e.name}}. Those references are now unresolved.`:void 0},l)}const l=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 l?Iu(Xd({deleted:!0,name:e.name,referenced_by_items:o,warning:o>0?`${o} item${o>1?"s":""} still contain {${e.name}}. Those references are now unresolved.`:void 0})):qu(nu("Variable",e.name))}catch(r){const a=cv(n,t,r);return a?Dj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}D(Ij,{createVariableHandler:()=>Pj,deleteVariableHandler:()=>Dj,getVariableHandler:()=>Tj,listVariablesHandler:()=>Rj,updateVariableHandler:()=>Cj});var Nj,Hj,Fj=P({"src/tools/variables.ts"(){vd(),vj(),sp(),ai(),vv(),kr(),wy(),Aj(),an(),Av(),zu(),Sj=async(e,t)=>t?Ua(e):e,$j=(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}})}}),Lj={};async function Uj(e,t,n,r,a){let i=0,s=Nj;for(;;){const{data:o,error:l}=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:s});if(l&&("57014"===l.code||/statement timeout/i.test(l.message??""))&&Math.floor(s/2)>=Hj){s=Math.floor(s/2);continue}if(l)throw new Error(i>0?`${l.message} (${i} items were already updated and the registry is unchanged: call again to finish)`:l.message);const c="number"==typeof o?o:0;if(i+=c,c<s)return i}}async function Wj(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 Vj(e){try{const t=await Bu(),{domains:n,functionTags:r}=await Wj(t,e.project_id),a=Nc(n,r),i=new Set(a.map(uc)),s=new Set(r.map(uc)),o=n.filter(e=>!i.has(uc(e))),{counts:l,orphans:c}=await async function(e,t,n){const r=await Sn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn),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(uc(e))).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),p=[...d,...u];return Iu(Xd({domains:p,total:p.length,registered_count:d.length,unregistered_count:u.length,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")?qu(ou()):qu(vu(e,{read:!0}))}}async function Bj(e,t){let n;try{const r=await Bu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const a=t??await iv(r,e.project_id);if("unreadable"===a)return sv();n=a;const i=Su(e.name).trim().toLowerCase();if(!i)return qu(su("Domain name cannot be empty."));const s=await Wj(r,e.project_id);if(null!==pc(i,s.functionTags))return qu(su(Jc(i,!0),Ud));const o=pc(i,s.domains);if(null!==o)return qu(su(Jc(o,!1),Ud));if("ops"===a){const t={op_id:ya(),kind:"add",item_id:null,path:["taxonomy","domains"],value:i},{run:n}=await hv({client:r,projectId:e.project_id,op:t});return n.answers.some(e=>"noop"===e.status)?qu(su(Jc(i,!1),Ud)):lv(n.outcome,{domain:{name:i},message:Gc(i)},n)}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 Wj(r,e.project_id),n=null!==pc(i,t);return qu(su(Jc(i,n),Ud))}return Iu(Xd({domain:{name:i},message:Gc(i)}))};return await l()}catch(r){const a=cv(n,t,r);return a?Bj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}async function Gj(e,t){let n;const r=m_("atoms_update_domain",e);if(r)return qu(r);try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();if(n=i,"string"!=typeof e.new_name)return qu(su("Pass new_name, the domain's new name."));const{domains:s,functionTags:o}=await Wj(r,e.project_id),l=Su(e.name).trim(),c=function(e,t){const n=e.trim();return"ops"===t?n:n.toLowerCase()}(Su(e.new_name),"ops"===i?"ops":"main");if(!c)return qu(su("new_name cannot be empty."));const{spelling:d,registered:u}=await Vc(r,e.project_id,l,s);if(null===d)return qu(nu("Domain",l.toLowerCase()));if(null!==pc(c,[d]))return qu(su(function(e,t){return`"${t}" is the same domain as "${e}" (only the case differs), so there is nothing to rename.`}(d,c)));const p=function(e,t,n,r){if(null!==pc(t,[e]))return null;const a=pc(t,r);if(null!==a)return{kind:"function",name:a};const i=pc(t,n);return null!==i?{kind:"domain",name:i}:null}(d,c,s,o);if("function"===p?.kind)return qu(function(e,t,n){return{status:"error",message:`Cannot rename "${e}" to "${t}": "${n}" is a function tag, and a tag is a domain or a function, never both, so a domain cannot take a function's name. Choose another name.`,next_steps:["Choose a new_name that is not already a domain or a function tag"],details:{code:Uc,functions:[n]}}}(d,c,p.name));if("domain"===p?.kind&&u)return qu(su(Qc(p.name)));const m="domain"===p?.kind&&!u,f=m&&p?p.name:c,_=await Bc(r,e.project_id,[d]);if(e.dry_run)return Iu(Xd({dry_run:!0,rename:{from:d,to:f},items_affected:_,message:m?`Dry run: "${d}" is not registered and "${f}" is, so the ${_} item${1!==_?"s":""} carrying "${d}" would be merged into the registered domain "${f}" (the registry is not changed). Call again with dry_run=false to apply.`:`Dry run: renaming "${d}" → "${c}" would update ${_} item${1!==_?"s":""}. Call again with dry_run=false to apply.`}));if("ops"===i){const t={op_id:ya(),kind:"rename",item_id:null,path:["taxonomy","domains"],value:f,base:d},{run:n,retagged:a}=await hv({client:r,projectId:e.project_id,op:t,repeat:!0});return gv(n,"deleted")?qu(nu("Domain",d.toLowerCase())):gv(n,"invalid","name_taken")?qu(su(Qc(f))):lv(n.outcome,{domain:{name:f},renamed_from:d,items_updated:a,message:m?`Domain "${d}" merged into the registered domain "${f}". ${a} item${1!==a?"s":""} updated.`:`Domain renamed "${d}" → "${c}". ${a} item${1!==a?"s":""} updated.`},n)}const h=async()=>{const t=await Uj(r,e.project_id,d,f,a);return m?Iu(Xd({domain:{name:f},renamed_from:d,items_updated:t,message:`Domain "${d}" 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,d,c),Iu(Xd({domain:{name:c},renamed_from:d,items_updated:t,message:`Domain renamed "${d}" → "${c}". ${t} item${1!==t?"s":""} updated.`})))};return await h()}catch(r){const a=cv(n,t,r);return a?Gj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}async function Jj(e,t){let n;try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();n=i;const{domains:s}=await Wj(r,e.project_id),o=Su(e.name).trim(),{spelling:l,registered:c}=await Vc(r,e.project_id,o,s),d=l??o.toLowerCase(),u=null===l?0:await Bc(r,e.project_id,[l]);if(!c&&0===u)return qu(nu("Domain",d));if(u>0&&!e.force)return qu(su(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(bv("atoms_delete_domain",e.project_id)){const t={tool:"atoms_delete_domain",project_id:e.project_id,target:d};if(!e.confirmation_token){const e=kv(t);return Iu(Xd({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=jv(e.confirmation_token,t);if(!n.valid)return qu(su(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t={op_id:ya(),kind:"remove",item_id:null,path:["taxonomy","domains"],value:d},{run:n,retagged:a}=await hv({client:r,projectId:e.project_id,op:t,repeat:!0});return gv(n,"deleted")?qu(nu("Domain",d)):lv(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)}const p=async()=>{const t=u>0?await Uj(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 Iu(Xd({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=cv(n,t,r);return a?Jj(e,a):r instanceof Error&&r.message.includes("Not authenticated")?qu(ou()):qu(ju(r instanceof Error?r.message:String(r)))}}D(Lj,{DOMAIN_CHANGE_BATCH:()=>Nj,DOMAIN_CHANGE_BATCH_FLOOR:()=>Hj,createDomainHandler:()=>Bj,deleteDomainHandler:()=>Jj,listDomainsHandler:()=>Vj,updateDomainHandler:()=>Gj});var Qj=P({"src/tools/domains.ts"(){sp(),kr(),Av(),zu(),Wc(),ai(),vv(),ed(),M_(),Nj=50,Hj=10}}),Yj={};async function Kj(e){try{const t=await Bu(),{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 Sn(()=>t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn);if(!a&&0===s.length){if(i)throw new Error(i);return qu(nu("Project",e.project_id))}const o={requirements:0,test_cases:0,notes:0};let l=0;const c=[];for(const e of s)if("requirement"===e.type){o.requirements++;const t=e.data?.tags?.domains??[];c.push({id:e.id,domains:t})}else"test-case"===e.type?o.test_cases++:"note"===e.type?o.notes++:"function"===e.type&&l++;"items"===await Bf(t,e.project_id)&&(o.functions=l);const d=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=Cm(n);"passed"===e?t.passed++:"failed"===e?t.failed++:"blocked"===e?t.blocked++:t.not_run++}return t}(s),u=qf(s,await Sn(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn)),p=ef(s,u),m=c.length,f=wf(c.filter(e=>p.has(e.id)),c.filter(e=>!p.has(e.id)),await gf(t,e.project_id)),_=new Set(f.covered.map(e=>e.id)),h={covered:f.covered.length,uncovered:f.uncovered.length,total:m,percent:jf(f.covered.length,m),via_mitigation:mf(c.map(e=>e.id),_,nf(s,u)),...f.coveredByDocument?{covered_by_document:f.coveredByDocument}:{}},g=await Df(t,e.project_id),y=function(e,t){const n=new Set(t.flatMap(e=>e.test_case_ids??[]));let r=0;for(const t of e)"test-case"===t.type&&n.has(t.id)&&"passed"===Cm(t)&&r++;return{requirements:new Set(t.map(e=>e.requirement_id)).size,test_cases:r}}(s,await Nf(t,e.project_id,p,g.releaseId)),w=new Map;for(const e of c){const t=e.domains.length>0?e.domains:["(untagged)"],n=_.has(e.id);for(const e of t){w.has(e)||w.set(e,{covered:0,total:0});const t=w.get(e);t.total++,n&&t.covered++}}const v=Array.from(w.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:jf(t.covered,t.total)})),b=new Date;b.setDate(b.getDate()-7);const k=!0===await Py(t,e.project_id),j=await async function(e,t,n,r){const a=await fy(e,"mcp_count_recent_changes",{p_project_id:t,p_since:n,p_project_changes:r});return a?py(a.data):null}(t,e.project_id,b.toISOString(),k),{count:x,error:S}=null!==j?{count:j,error:null}:k?await t.from("project_changes").select("seq",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("committed_at",b.toISOString()):await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",b.toISOString());if(S)throw new Error(S.message);return Iu(Xd({project_id:e.project_id,project_name:a??`Project ${e.project_id.slice(0,8)}`,counts:o,test_status:d,coverage:h,coverage_by_domain:v,rerun:y,rerun_scope:g.label,recent_changes:x??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(Yj,{projectSummaryHandler:()=>Kj});var Zj=P({"src/tools/project-summary.ts"(){sp(),qy(),$f(),Vf(),hf(),kf(),kr(),zu(),Ky(),s_(),gy()}}),Xj={};async function ex(e){try{const t=await Bu();let n,r;if(e.query&&e.query.trim().length>0){const a=await Ay(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:Cm(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),r=a.totalCount}else{const a=await by(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:Cm(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 Sn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),pn),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 Iu(Xd({items:n,filters:{domains:a.domains,levels:a.levels,types:Gf(await Bf(t,e.project_id))},project_id:e.project_id},ld(r,e.limit,e.offset)),{paging:{list:"items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(Xj,{browseHandler:()=>ex});var tx=P({"src/tools/browse.ts"(){vd(),sp(),qy(),zu(),Zm(),s_()}}),nx={};async function rx(e){try{const t=e.direction??"downstream",n=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await Bu(),a=await ky(r,e.project_id,e.item_id);if(!a)return qu(nu("Item",e.item_id));const i=await Sn(()=>r.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),pn),s=qf(i,await Sn(()=>r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),mn)),o=new Map;for(const e of i)o.set(e.id,{title:Hh(e),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=Fh(e,e=>o.get(e)?.type),r=n.type;"upstream"!==t&&"both"!==t||(Rh.includes(r)&&c(n.from_id,n.to_id,r),Th.includes(r)&&c(n.to_id,n.from_id,Ch[r]??r)),"downstream"!==t&&"both"!==t||(Th.includes(r)&&c(n.from_id,n.to_id,r),Rh.includes(r)&&c(n.to_id,n.from_id,Ch[r]??r)),"related"===r&&(c(n.from_id,n.to_id,"related"),c(n.to_id,n.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(let e=0;e<m.length;e++){const{id:t,depth:r,path:a}=m[e];if(d.has(t))continue;if(null!==n&&r>n)continue;d.add(t);const i=o.get(t);if(i&&(u.push({item_id:t,title:i.title,type:i.type,depth:r,relationship_path:a,shared_variables:[]}),r>p&&(p=r),null===n||r<n))for(const e of l.get(t)??[])d.has(e.neighbor)||m.push({id:e.neighbor,depth:r+1,path:[...a,{from_id:t,to_id:e.neighbor,relationship_type:e.relType}]})}let f=0;if(e.include_variable_refs){const t=await Sn(()=>r.from("project_variables").select("id, name").eq("project_id",e.project_id),_n),n=function(e,t,n){const r=new Map,a=t.find(t=>t.id===e);if(!a)return r;const i=bj(a),s=n.filter(e=>"string"==typeof e.name&&e.name&&i.includes(`{${e.name.toLowerCase()}}`));if(0===s.length)return r;for(const n of t){if(n.id===e)continue;const t=bj(n);if(t)for(const e of s)t.includes(`{${e.name.toLowerCase()}}`)&&(r.has(n.id)||r.set(n.id,new Set),r.get(n.id).add(e.name))}return r}(e.item_id,i,t),a=new Map(u.map(e=>[e.item_id,e]));for(const[t,r]of n){const n=[...r].sort(),i=a.get(t);if(i){i.shared_variables=n;continue}const s=o.get(t);s&&(u.push({item_id:t,title:s.title,type:s.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:t,relationship_type:`variable_ref:${n[0]}`}],shared_variables:n}),f++)}}const _={};for(const e of u)_[e.type]=(_[e.type]??0)+1;const h=o.get(e.item_id),g=od(u,e.offset,e.limit);return Iu(Xd({root:{item_id:e.item_id,title:h?.title??a.title,type:h?.type??a.type},impacted_items:g.rows,summary:{total_impacted:u.length,by_type:_,max_depth_reached:p,...f>0?{variable_impact_count:f}:{}}},g.meta),{paging:{list:"impacted_items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}D(nx,{impactAnalysisHandler:()=>rx});var ax,ix,sx,ox,lx,cx,dx,ux,px,mx,fx,_x,hx,gx=P({"src/tools/impact-analysis.ts"(){sp(),qy(),Kh(),kr(),Aj(),vd(),zu()}});function yx(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function wx(e){return null==e?"":String(e)}function vx(e){if(null==e||""===e)return"null";if(Array.isArray(e))return 0===e.length?"null":`[${e.map(vx).join(",")}]`;if("object"==typeof e){const t=e,n=Object.keys(t).filter(e=>"null"!==vx(t[e])).sort();return 0===n.length?"null":`{${n.map(e=>`${JSON.stringify(e)}:${vx(t[e])}`).join(",")}}`}return JSON.stringify(e)}function bx(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function kx(e){return null==e||""===e?null:e}function jx(e,t=!0){const n=kx(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=>jx(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)}:${jx(r[e],t)}`).join(",")}}`}function xx(e,t){return e.some(e=>!t.includes(e))||t.some(t=>!e.includes(t))}function Sx(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 $x(e){const t=Object.prototype.hasOwnProperty.call(e,"parent"),n=Object.prototype.hasOwnProperty.call(e,"child");if(!t&&!n)return e.relationships;const r=bx(e.relationships);return{...r,parent:[...Sx(r.parent),...Sx(e.parent)],child:[...Sx(r.child),...Sx(e.child)]}}function Ax(e,t){const n=bx(e),r="parents"===t?n.parent:"children"===t?n.child:void 0;return Array.from(new Set([...Sx(n[t]),...Sx(r)])).sort()}function Ix(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){const e=bx(n);if("string"!=typeof e.date||!e.date.trim())continue;const r={};for(const t of dx){const n=kx(e[t]);null!==n&&(r[t]=n)}t.set(e.date,r)}return t}function qx(e,t){const n=Ix(e),r=Ix(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&&dx.every(e=>jx(t[e])===jx(a[e])))});return[Object.fromEntries(a.map(e=>[e,n.get(e)??null])),Object.fromEntries(a.map(e=>[e,r.get(e)??null]))]}function Mx(e,t){const n=[];kx(e.title)!==kx(t.title)&&n.push({path:"title"}),kx(e.type)!==kx(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 lx)kx(r[e])!==kx(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)?xx(t,n):jx(t)!==jx(n))&&i("tags",e)}const l=bx(r.analysis_props),c=bx(a.analysis_props);for(const e of Array.from(new Set([...Object.keys(l),...Object.keys(c)])).sort())!ax.has(e)&&yx(l[e])&&yx(c[e])&&wx(l[e])!==wx(c[e])&&i("analysis_props",e);jx(r.ownership)!==jx(a.ownership)&&i("ownership");for(const e of cx)xx(Ax($x(r),e),Ax($x(a),e))&&i("relationships",e);Object.keys(qx(r.runs,a.runs)[0]).length>0&&i("runs");for(const e of Array.from(new Set([...Object.keys(r),...Object.keys(a)])).sort())ux.has(e)||jx(r[e],!1)!==jx(a[e],!1)&&i(e);return n}function Ox(e,t){const n=Mx(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"),(Ex(e)||Ex(t)?kx(Rx(e))!==kx(Rx(t)):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=bx(e),r=bx(t),a=[],i=bx(n.analysis_props),s=bx(r.analysis_props),o=Array.from(new Set([...Object.keys(i),...Object.keys(s)])).sort();for(const e of o){if(ax.has(e))continue;const t=i[e],n=s[e];yx(t)&&yx(n)?wx(t)!==wx(n)&&a.push(`analysis_props.${e}`):vx(t)!==vx(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(bx(n.fields)),d=l(bx(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 Ex(e){return"test-case"===e.type}function zx(e){const t=bx(e.data);return Ex(e)?Lm(t):t.runs}function Rx(e){const t=bx(e.data);return Ex(e)?Cm({type:"test-case",data:t})??null:t.status??null}function Tx(e,t){for(const[n,r]of Object.entries(e))if(n.toLowerCase()===t)return"string"==typeof r?r:null;return null}function Cx(e,t,n){const r=bx(e.data),a=bx(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:Rx(e),to:Rx(t)};else if("tags.level"===o)s[o]={from:bx(r.tags).level??null,to:bx(a.tags).level??null};else if("tags.domains"===o)s[o]={from:bx(r.tags).domains??null,to:bx(a.tags).domains??null};else if(o.startsWith("analysis_props.")){const e=o.slice(15);s[o]={from:bx(r.analysis_props)[e]??null,to:bx(a.analysis_props)[e]??null}}else if(o.startsWith("fields.")){const e=o.slice(7).toLowerCase();s[o]={from:Tx(bx(r.fields),e),to:Tx(bx(a.fields),e)}}else if("data"===o){const n=Mx(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={},p=Ex(e)||Ex(t);for(const n of c){if("status"===n&&p)continue;const[s,o]="runs"===n?Dx(n,zx(e),zx(t),i,l):"relationships"===n?Dx(n,$x(r),$x(a),i,l):Dx(n,r[n],a[n],i,l);vx(s)!==vx(o)&&(d[n]=s??null,u[n]=o??null)}s[o]={from:d,to:u}}else s[o]={from:null,to:null};return s}function Px(e,t){return null===e||"object"!=typeof e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).filter(([e])=>!t(e)))}function Dx(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[Px(t,e),Px(n,e)]}if("relationships"===e){const e=cx.filter(e=>a.has(`data.relationships.${e}`)),r=t=>Object.fromEntries(e.map(e=>[e,Ax(t,e)]));return[r(t),r(n)]}if("runs"===e)return qx(t,n);if("analysis_props"===e){const e=e=>r.has(`analysis_props.${e}`);return[Px(t,e),Px(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[Px(t,e),Px(n,e)]}return Array.isArray(t)&&Array.isArray(n)?function(e,t){const n={},r={},a=Nx(e),i=Nx(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;vx(t)!==vx(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++)vx(e[a])!==vx(t[a])&&(n[a]=e[a]??null,r[a]=t[a]??null);return[n,r]}(t,n):[t,n]}function Nx(e){const t=[];for(const n of e){const e=bx(n).id;if("string"!=typeof e||"order"===e)return null;t.push(e)}return new Set(t).size===t.length?t:null}function Hx(e){return"string"==typeof e?1:Array.isArray(e)?e.reduce((e,t)=>e+Hx(t),0):null!==e&&"object"==typeof e?Object.values(e).reduce((e,t)=>e+Hx(t),0):0}function Fx(e){const t=JSON.stringify(e,null,2),n=t.split("\n").length;return t.length+n*fx+mx*Hx(e.diff)+2}function Lx(e,t,n){if("string"==typeof e){if(e.length<=t+hx)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=>Lx(e,t,n)):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Lx(r,t,n)])):e}function Ux(e,t){const n=e.diff??{};for(const r of _x){const a={n:0},i=Lx(n,r,a),s={...e,diff:i,...a.n>0?{diff_clipped:!0}:{}};if(Fx(s)<=t)return s}const r={n:0},a=Lx(n,_x[_x.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(Fx(c)>t)break;o=r,l=c}return 0===l.diff_omitted&&delete l.diff_omitted,l}var Wx,Vx=P({"src/core/baseline-diff.ts"(){Zm(),ax=new Set(["field_source","approved","approved_at","approved_by","approved_note"]),ix=["approval_state","approver_user_id","rev_label","approved_at","requires_impacted_approval"],sx=["id","title","type","metadata",...ix],ox=["parent","child"],lx=["body","summary","status","level","isLocked","lockedBy","lockedAt"],cx=["parents","children","related","verifies","verified_by","mitigated_by","mitigates","traces_to","traced_by","allocated_to","allocated_from","decomposes_to","decomposed_from","affects","affected_by","event_hazard","hazard_events","event_goal","goal_events"],dx=["result","by","note","asset"],ux=new Set(["tags","ownership","relationships","runs",...lx,...sx,...ox]),px=2e4,mx=29,fx=6,_x=[1e3,400,160,60,20],hx=40}});function Bx(e,t){const n=e.filter(e=>"object"==typeof e&&null!==e);if(0===n.length)return"";const r=[];let a=n.length;for(const e of Wx){const i=n.filter(e.test).length;0!==i&&(a-=i,r.push(`${i} ${t}(s) ${"variable"===t&&e.variable||e.words}.`))}return a>0&&r.push(`${a} ${t}(s) were left alone for another reason (each entry's reason says which).`),r.push(`They are listed in ${"item"===t?"items_skipped":"variables_skipped"}.`),r.join(" ")}function Gx(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 Jx,Qx,Yx,Kx,Zx=P({"src/core/restore-preview.ts"(){Wx=[{test:e=>"changed_since_source"===e.reason||"clash"===e.reason,words:"were left alone because someone changed them after the preview"},{test:e=>"deleted"===e.reason,words:"were left alone because they are in the Trash or no longer exist",variable:"were left alone because someone removed them after the preview"},{test:e=>"refused"===e.reason&&!0!==e.partly_applied,words:"could not be restored: the server refused their version in the snapshot (refused_reason says why)"},{test:e=>"refused"===e.reason&&!0===e.partly_applied,words:"were partly restored: the server refused part of their version in the snapshot (refused_reason says why)"},{test:e=>"link_end_skipped"===e.reason,words:"were left alone because an item linked with them was not restored"},{test:e=>"asil_put_back"===e.reason,words:"were left alone because a row that gives them their ASIL was not restored"},{test:e=>"locked"===e.reason,words:"were left alone because they are locked"},{test:e=>"typing"===e.reason,words:"were left alone because someone was typing in them"},{test:e=>"forbidden"===e.reason,words:"were left alone because a change to them is waiting for approval or is not allowed"},{test:e=>"approved"===e.reason,words:"were left alone because they are approved under change control"}]}}),Xx={};function eS(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):null}async function tS(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 nS(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 rS(e,t,n){const{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a)return qu(ju(a.message));if(!r)return qu(nu("Project",t));if(r.deleted_at)return qu($r());const{data:i,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?qu(ju(s.message)):!0!==(i?.feature_flags??{})[n]?qu(tu(`Feature '${n}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function aS(e){try{const t=await Bu(),n=await async function(e,t){const n=[],r=new Set;for(let a=0;;){const{data:i,error:s}=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}).range(a,a+1e3-1);if(s)throw new Error(`listBaselines: ${s.message}`);const o=i??[];if(0===o.length)return n;let l=0;for(const e of o)r.has(e.id)||(r.add(e.id),n.push(e),l+=1);if(0===l)return n;a+=o.length}}(t,e.project_id),r=Math.max(e.offset??0,0),a=Math.min(Math.max(e.limit??50,1),100);return Iu(Xd({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},ld(n.length,a,r)),{paging:{list:"baselines"}})}catch(e){return eS(e)??qu(vu(e,{read:!0}))}}async function iS(e){try{const t=await Bu(),n=await rS(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?qu(tu(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):qu(vu(a)):Iu(Xd({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 eS(e)??qu(vu(e))}}async function sS(e){try{const t=await Bu(),n=await xy(t,e.baseline_id);if(!n)return qu(nu("Baseline",e.baseline_id));const r=await rS(t,n.project_id,"baselines_enabled");if(r)return r;if(null!==n.locked_at)return qu(tu("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 qu(nu("Project",n.project_id));const{data:i,error:s}=await t.auth.getUser();if(qt(s))return qu(Mt());const o=i?.user?.id;if(!o)return qu(ou());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 qu(tu("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?qu(vu(d)):Iu(Xd({id:c.id,locked_at:c.locked_at,locked_by:c.locked_by}))}catch(e){return eS(e)??qu(vu(e))}}async function oS(e){try{const t=await Bu(),[n,r]=await Promise.all([xy(t,e.baseline_a_id),xy(t,e.baseline_b_id)]);if(!n||!r)return qu(nu("Baseline","one of the baseline_ids"));if(n.project_id!==r.project_id)return qu(tu("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[a,i]=await Promise.all([$y(t,n.project_id,yn(n.id)),$y(t,r.project_id,yn(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=Ox(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),f=Math.min(Math.max(e.limit??50,1),200);let _=c.slice(m,m+f);const h={offset:m,limit:f,total:c.length};if(!0===e.detail){const e=function(e,t,n,r,a={}){const i=a.budget??px,s=a.diffOf??Cx,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=Fx(e);if(l+a>i){if(o.length>0)break;e=Ux(e,i),a=Fx(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}}(_,s,o,m);_=e.items,Object.assign(h,e.pageInfo)}return Iu(Xd({summary:{added:d,removed:u,modified:p,total_compared:l.length},items:_,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}}}),{paging:{list:"items",resume:e=>({data:{page_info:{...h,returned:e,next_offset:m+e,truncated:!0}},next:`offset=${m+e}`})}})}catch(e){return eS(e)??qu(vu(e,{read:!0}))}}async function lS(e,t){let n;try{const o=await Bu(),l=await xy(o,e.baseline_id);if(!l)return qu(nu("Baseline",e.baseline_id));const c=await rS(o,l.project_id,"baselines_enabled");if(c)return c;const{data:d}=await o.from("projects").select("org_id").eq("id",l.project_id).maybeSingle();if(!d)return qu(nu("Project",l.project_id));const{data:u,error:p}=await o.auth.getUser();if(qt(p))return qu(Mt());const m=u?.user?.id;if(!m)return qu(ou());const{data:f}=await o.from("org_members").select("role").eq("user_id",m).eq("org_id",d.org_id).maybeSingle();if(!f||"admin"!==f.role)return qu(tu("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const{data:_}=await o.rpc("cc_project_is_controlled",{p_project_id:l.project_id});if(!0===_)return qu(tu("Change control is on for this project. Release review before restoring a baseline.",["Release review on the project, then run the restore"]));const h=t??await iv(o,l.project_id);if("unreadable"===h)return sv();n=h;const g=await $y(o,l.project_id,yn(l.id)),y=await On(g.map(e=>e.id),e=>o.from("items").select("*").eq("project_id",l.project_id).in("id",e)),w=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}]})}(g,y),v=await Mn(o,l.project_id,yn(l.id)),b={tool:"atoms_restore_baseline",project_id:l.project_id,target:l.id},k=bv(b.tool,l.project_id);if(k&&!0===e.confirm&&e.confirmation_token){const t=jv(e.confirmation_token,b);if(!t.valid)return qu(su(`confirmation_token rejected: ${t.reason}`))}if(!0!==e.confirm||k&&!e.confirmation_token){const e="ops"===h?await Kr(o,l.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 o.rpc("restore_baseline_preview_counts",{p_baseline_id:l.id})),n=k?kv(b):null;return Iu(Xd({...n?{status:"confirmation_required",confirmation_token:n.token,expires_at:n.expires_at,expires_in_seconds:n.expires_in_seconds,message:(i=n.expires_in_seconds,s=null!==e,`Re-call atoms_restore_baseline with the same baseline_id, confirm true and this confirmation_token${s?", with the source_seq above,":""} within ${i}s to execute.`)}:{},preview:!0,...null!==e?{source_seq:e,items:w.slice(0,Jx).map(e=>({id:e.id,type:e.type,title:e.title,changed_fields:e.diff_summary?.changed_fields??[]})),...w.length>Jx?{items_truncated:!0}:{}}:{},items_to_restore:w.length,variables_to_restore:v.length,field_definitions_to_restore:l.field_definitions_snapshot?.length??null,items_to_trash:t.items_to_trash,variables_to_archive:t.variables_to_archive,summary:(r=w.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"===h)return"number"!=typeof e.source_seq||!Number.isInteger(e.source_seq)||e.source_seq<0?qu(su("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.",Qx)):await async function(e,t){const n=Date.now();let r=t.bulkId??ya(),a=t.afterId??null,i=!1,s=null;const o={restored:0,trashed:0,variables:0,archived:0,fields:0,total:0};let l=!1;const c=[],d=[],u=[],p=di(e),m=p&&t.bulkId?await async function(e,t,n,r=ti){try{if(!e.supabaseUrl||!e.accessToken||!n)return null;const a=e.fetch??fetch,i=await a(`${ci(e,t,n)}&seq=not.is.null&select=seq&order=seq.desc&limit=1`,{method:"GET",headers:si(e),signal:AbortSignal.timeout(r)});if(!i.ok)return console.error(`[embed-on-save] change mark read failed (${i.status})`),null;const s=await i.json(),o=Array.isArray(s)&&s.length>0?Number(s[0].seq):0;return Number.isFinite(o)?o:null}catch(e){return console.error("[embed-on-save] change mark read failed:",e instanceof Error?e.message:e),null}}(p,t.projectId,t.bulkId):null;try{do{const{data:n,error:p}=await Sd(()=>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:Kx}),{scope:t.projectId,delays:wd});if(p&&bd(p)){s="busy";break}if(p)throw Object.assign(new Error(p.message),{code:p.code});const m=n??{};r=m.bulk_id??r,a=m.next_after_id??null,o.restored+=m.items_restored??0,o.trashed+=m.items_trashed??0,o.variables+=m.variables_restored??0,o.archived+=m.variables_archived??0,o.fields+=m.field_definitions_restored??0,l=l||!0===m.field_definitions_skipped,o.total=Math.max(o.total,m.total??0),c.push(...m.items_skipped??[]),d.push(...m.variables_skipped??[]),u.push(...Array.isArray(m.not_restored)?m.not_restored:[]),i=!0===m.done}while(!i&&Date.now()-n<Yx)}finally{p&&ui(async function(e,t,n,r){try{if(!e.supabaseUrl||!e.accessToken||!n)return;const a=e.fetch??fetch,i=[];let s=r;for(;;){const r=`${ci(e,t,n)}&item_id=not.is.null`+(null!==s?`&seq=gt.${s}`:"")+`&select=seq,kind,item_id,path&order=seq.asc&limit=${ei}`,o=await a(r,{method:"GET",headers:si(e)});if(!o.ok){console.error(`[embed-on-save] change read failed (${o.status})`);break}const l=await o.json();if(!Array.isArray(l)||0===l.length)break;i.push(...l);const c=Number(l[l.length-1].seq);if(!Number.isFinite(c)||null!==s&&c<=s)break;s=c}const o=li(i);o.length>0&&await oi(e,t,o)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}(p,t.projectId,r,m))}const f=Gx({items_restored:o.restored,items_trashed:o.trashed,variables_archived:o.archived}),_=function(e,t=[],n=!1){return[Bx(e,"item"),Bx(t,"variable"),n?"The field definitions were left as someone changed them after the preview.":""].filter(Boolean).join(" ")}(c,d,l),h=_?` ${_}`:"",g=i?f+h:`Restore not finished. ${f}${h} Call atoms_restore_baseline again with confirm true, source_seq ${t.sourceSeq}, bulk_id ${r} and after_id ${a??""} to continue.`;return Iu(Xd({ok:!0,complete:i,bulk_id:r,...i?{}:{next_after_id:a},...s?{paused:s}:{},items_restored:o.restored,variables_restored:o.variables,field_definitions_restored:o.fields,field_definitions_skipped:l,items_trashed:o.trashed,variables_archived:o.archived,items_skipped:c,...d.length>0?{variables_skipped:d}:{},not_restored:u,progress:{items_restored:o.restored,items_total:o.total||null},summary:g}))}(o,{baselineId:l.id,projectId:l.project_id,userId:m,sourceSeq:e.source_seq,bulkId:e.bulk_id,afterId:e.after_id});const j=await tS(o,{baselineId:l.id,projectId:l.project_id,userId:m});return function(e,t,n){const r=di(e);r&&0!==n.length&&ui(oi(r,t,n))}(o,l.project_id,function(e,t){const n=new Map;for(const e of t)e&&"string"==typeof e.id&&n.set(e.id,e);const r=new Set;for(const t of e){if(!t||"string"!=typeof t.id||""===t.id)continue;const e=n.get(t.id);e&&ii(e.data)===ii(t.data)||r.add(t.id)}return[...r]}(g,y)),Iu(Xd({ok:!0,items_restored:j.items_restored,variables_restored:j.variables_restored,field_definitions_restored:j.field_definitions.length,items_trashed:j.items_trashed,variables_archived:j.variables_archived,summary:Gx(j)}))}catch(r){const a=cv(n,t,r);return a?lS(e,a):eS(r)??qu(vu(r))}var r,a,i,s}D(Xx,{RESTORE_CALL_BUDGET_MS:()=>Yx,createBaselineHandler:()=>iS,diffBaselinesHandler:()=>oS,listBaselinesHandler:()=>aS,lockBaselineHandler:()=>sS,restoreBaselineHandler:()=>lS,restoreBaselineStateAtomicallyViaMain:()=>tS,syncRestoredItemRelationships:()=>nS});var cS,dS=P({"src/tools/baselines.ts"(){vd(),sp(),ai(),Rd(),vv(),zt(),E$(),zu(),qy(),Tf(),Vx(),Zx(),Av(),kr(),hi(),Jx=200,Qx=400,Yx=2e4,Kx=200}});function uS(e){return!!e&&(bd(e)||Yt(String(e.message??""))||"PT409"===String(e.code??""))}async function pS(e,t=cS){const n=async()=>{try{return await e()}catch(e){return{message:e instanceof Error?e.message:String(e)}}};let r=await n();for(const e of t){if(!uS(r))return r;await _d.sleep(Math.round(e*_d.jitter())),r=await n()}return r}function mS(e){const t=[],n={};return e.controlType&&(n.control_type_not_written={row_id:e.rowId,req_id:e.reqId,control_type:e.controlType.value,reason:e.controlType.message},t.push(`the control type ${e.controlType.value} was not written onto ${e.rowId}`)),e.asil&&(n.asil_not_written={req_id:e.reqId,asil:e.asil.level,source_row:e.rowId,reason:e.asil.message},t.push(`ASIL ${e.asil.level} was not written onto ${e.reqId}`)),0===t.length?{}:(n.warning=`The link ${e.rowId} mitigated by ${e.reqId} is saved, but ${t.join(" and ")} because another write was on the item. Call atoms_link_mitigation again with the same arguments to finish; the link is not added twice.`,n)}var fS,_S,hS,gS,yS=P({"src/core/after-link-save.ts"(){Rd(),an(),cS=[100,250,500]}});function wS(e){return"string"==typeof e}function vS(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:wS(n.by)?n.by:null,on:wS(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:wS(e.by)?e.by:"",on:wS(e.on)?e.on:"",count:"number"==typeof e.count&&Number.isFinite(e.count)?e.count:0})):[]}}}function bS(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>hS)return{ok:!1,error:`scenario_catalogs accepts at most ${hS} 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(!wS(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),!wS(e.name)||!e.name.trim())return{ok:!1,error:`catalog "${e.id}" must carry a non-empty name`};if(e.name.length>_S)return{ok:!1,error:`catalog "${e.id}" name must be at most ${_S} characters`};if(!Array.isArray(e.entries))return{ok:!1,error:`catalog "${e.id}" entries must be an array`};if(e.entries.length>fS)return{ok:!1,error:`catalog "${e.id}" accepts at most ${fS} 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(!wS(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=wS(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>_S)return{ok:!1,error:`an entry of catalog "${e.id}" must be at most ${_S} characters`};const s=Array.isArray(n.function_tags)?n.function_tags.filter(wS).map(e=>e.trim()).filter(Boolean):[],o=Array.isArray(n.function_ids)?n.function_ids.filter(wS).map(e=>e.trim()).filter(Boolean):null;a.push(null===o?{id:n.id,text:r,function_tags:s}:{id:n.id,text:r,function_tags:s,function_ids:o})}const s=vS(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 kS,jS=P({"src/core/catalogs.ts"(){fS=50,_S=100,hS=200,gS=["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]}}),xS={};function SS(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}function $S(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function AS(e){const t=e?.relationships?.verified_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function IS(e){return JSON.parse(JSON.stringify(e??{}))}async function qS(e,t,n,r){const a=await x_(n,Object.keys(r),()=>Bf(e,t));if(a)return{ok:!1,result:qu(su(a,Ud))};if(!(Zf in r))return{ok:!0,rest:r,writes:{},answer:{}};const{[Zf]:i,...s}=r,o=await async function(e,t,n){if("string"!=typeof n)return{ok:!1,error:{status:"error",message:'Validation error: source_function_id must be a string, the id of a Function item ("" clears it on a project with Function items turned on). Nothing was written.',next_steps:["Find the project's Functions with atoms_list_items type 'function'"],code:"function_id_invalid",retryable:!1}};const r=n.trim(),a=await Bf(e,t);if(!r&&"tags"===a)return{ok:!1,error:{status:"error",message:r_,next_steps:[...a_],code:"function_items_off",retryable:!1}};const i=await w_(e,t,r?[r]:[],a);if(!i.ok)return i;const s=i.functions[0];return s?{ok:!0,writes:{source_function_id:s.id,source_function:s.title},answer:{source_function_id:s.id,source_function_title:s.title}}:{ok:!0,writes:{source_function_id:"",source_function:""},answer:{source_function_id:null,source_function_title:null}}}(e,t,i);return o.ok?{ok:!0,rest:s,writes:o.writes,answer:o.answer}:{ok:!1,result:qu(o.error)}}async function MS(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 Hl(n)}function OS(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function ES(e){return qu("tool"===e.kind?e.error:su(e.message,Ud))}function zS(e,t,n){return fh(t,n).map(t=>({op_id:ya(),kind:t.kind,item_id:e,path:[...t.path],value:t.value}))}async function RS(e,t,n,r){const a=OS(r);if(!a)return!1;const i=await ky(e,t,a);return vh(n,i?.data)}async function TS(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:Fl(n,a,a?null:await MS(e,t))}}async function CS(e,t,n,r){const a=OS(r),i=a?await ky(e,t,a):null;return TS(e,t,n,i?.data)}function PS(e,t,n,r={}){const a=r.where?`${r.where}: `:"",i=function(e,t){const n=rl[e];if(!n)return{ok:!0,fields:t};const r=Object.keys(t??{}),a=[];for(const e of r){const i=Object.prototype.hasOwnProperty.call(n.aliases,e)?n.aliases[e]:e;if(i!==e&&r.includes(i))return{ok:!1,message:`${e} and ${i} are the same field on a ${n.row} (${e} is its ${n.kind}); send one of them. Nothing was written.`};a.push([i,t[e]])}return{ok:!0,fields:Object.fromEntries(a)}}(e,n??{});if(!i.ok)return{ok:!1,message:`${a}${i.message}`};n=i.fields;const s=new Set([...nl[e],...r.extraKeys??[]]),o=Object.keys(n??{});if(0===o.length)return{ok:!1,message:`${a}fields must contain at least one key`};const l=o.filter(e=>Ml.includes(e));if(l.length>0)return{ok:!1,message:`${a}${jc(e,l)}`};const c=xc(e);if(c&&o.includes(c.field))return{ok:!1,message:`${a}${Sc(e)}`};const d=o.filter(e=>!s.has(e));if(d.length>0)return{ok:!1,message:`${a}Unknown field(s) for ${e}: ${d.join(", ")}. Allowed: ${[...s].sort().join(", ")}`};const u=tl[e],p={};for(const r of o){const i=n[r];if(u[r]){const t="number"==typeof i?String(i):i;if("string"!=typeof t||!u[r].includes(t))return{ok:!1,message:`${a}Invalid ${r} value ${JSON.stringify(i)} for ${e}. Allowed: ${u[r].join(", ")}`};p[r]=t}else{if("string"!=typeof i)return{ok:!1,message:`${a}Field '${r}' must be a string`};const e=Gl(t,r,i);if(e)return{ok:!1,message:`${a}${e}`};p[r]=i}}return{ok:!0,writes:p}}async function DS(e,t){let n;const r=m_("atoms_create_analysis",e);if(r)return qu(r);try{const r=await Bu(),i=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const s=t??await iv(r,e.project_id);if("unreadable"===s)return sv();n=s;const o="string"==typeof(a=e.subtype)&&Object.prototype.hasOwnProperty.call(gl,a)?gl[a]:null;if(!o)return qu(su(function(e){return`subtype must be one of: ${yl.join(", ")} (got ${JSON.stringify(e)})`}(e.subtype)));const l=e.source_req_ids??[],c=e.source_function_ids??[],d=(e.source_assets??[]).map(e=>Su(e));if("hara"===o&&l.length>0)return qu(su("A HARA is seeded from functions, never requirements (a requirement is an output of the analysis): pass source_function_ids (a security risk analysis: source_assets) and omit source_req_ids"));if("dfmea"===o&&(c.length>0||d.length>0))return qu(su("source_function_ids and source_assets apply to hara only; seed a DFMEA with source_req_ids"));if(l.length>50)return qu(su("source_req_ids supports at most 50 entries per call"));if(c.length>i_||d.length>i_)return qu(su(`source_function_ids and source_assets support at most ${i_} entries per call`));if(l.length>0){const{data:t,error:n}=await r.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 a=new Map((t??[]).map(e=>[e.id,e])),i=l.filter(e=>!a.has(e));if(i.length>0)return qu(nu("Source requirement(s)",i.join(", ")));const s=l.filter(e=>{const t=a.get(e);return"requirement"!==t.type||kS.has(t.data?.req_type)});if(s.length>0)return qu(su(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${s.join(", ")}`))}if(void 0!==e.variant&&!ic(e.subtype).includes(e.variant))return qu(su(function(e,t){const n=ic(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 u=await MS(r,e.project_id),p=e.variant??function(e,t){return"medical"===t?vl[e]:wl[e]}(e.subtype,u),m=await async function(e,t,n,r){const a=n??"automotive";return Si(a).includes(r)||"automotive"===a&&await $i(e,t,a)?null:function(e,t){const n=Si(e);return`Cannot create a ${wi[t]}: this project's industry is ${vi[e]}, which offers ${n.length?function(e){const t=e.map(e=>wi[e]);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}(n):"no analyses"}. Analyses already in the project keep working. `+(n.length?"Create one of the offered analyses instead, or change the ":"To create one, change the ")+"industry on the project settings page (allowed while no analysis in the project would end up outside the new industry)."}(a,r)}(r,e.project_id,u,p);if(m)return qu(su(m,Ud));const f=Fl(o,p),_=Ll(f),h=Ql(f),g={},y=[];for(const t of[...al,...cl]){const n=e[t];"string"==typeof n&&""!==n&&(y.push(t),h.includes(t)&&(g[t]=Su(n)))}const w=y.filter(e=>!h.includes(e));if(w.length>0)return qu(su(tc(f,w)));let v=[];if("hara"===o){const t=await async function(e,t,n,r){const a=r.functionIds.length>0,i=[];for(const e of r.assets){const t=(e??"").trim();t&&!i.some(e=>o_(e)===o_(t))&&i.push(t)}if("security_tir57"===n)return a?{ok:!1,error:S_("A security risk analysis names assets, never Functions: pass its asset names in source_assets and omit source_function_ids. Nothing was written.",["Pass source_assets with the asset names, one row each"])}:{ok:!0,seeds:i.map(e=>({text:e,functionId:null}))};if(!j_(n))return a||i.length>0?{ok:!1,error:S_(`source_function_ids and source_assets apply to a HARA, a risk analysis or a security risk analysis only; a ${n} analysis is seeded with source_req_ids. Nothing was written.`)}:{ok:!0,seeds:[]};if(i.length>0)return{ok:!1,error:S_(`source_assets applies to a security risk analysis only; a ${n} analysis is seeded with source_function_ids, the ids of Function items. Nothing was written.`,["Find the project's Functions with atoms_list_items type 'function'",`Or create one with ${Yf}`])};if(!a)return{ok:!0,seeds:[]};const s=await y_(e,t,r.functionIds);return s.ok?{ok:!0,seeds:s.functions.map(e=>({text:e.title,functionId:e.id}))}:s}(r,e.project_id,f,{functionIds:c,assets:d});if(!t.ok)return qu(t.error);v=t.seeds}const b="hara"===o?v:l.map(e=>({text:e,functionId:null})),k=ch({...void 0!==e.hazard_id?{hazard_id:e.hazard_id}:{},...void 0!==e.goal_id?{goal_id:e.goal_id}:{}});if(k.error)return qu(su(k.error));let j=!1;if("hara_iso26262"===f&&("ops"===s||dh(k.picks))){const t=await sh(r,e.project_id);if(null===t)return qu(oh(null));if(j=function(e,t){return"hara_iso26262"===e&&null!==t&&null===Ai(t)}(f,t),!j&&dh(k.picks))return qu(oh(t))}const x=await _h(r,e.project_id,"atoms_create_analysis",f,j,k.picks,null,t=>ky(r,e.project_id,t));if(x)return ES(x);if("ops"===s)return await async function(e){const{client:t,projectId:n,subtype:r,schemeId:a,seeds:i}=e,s=ul[r],o=ml[a],l=ac(a,e.stamp?"hazard_goal":"legacy"),c={analysis:{subtype:r,scheme:a,revision:e.revision,...e.schemeStandard?{standard:e.schemeStandard}:{}},analysis_props:{variant:e.variant,...e.scopeInput,...e.stamp?{event_model:"hazard_goal"}:{}}},d=e=>"hara"===r?b_(e):{source_req:e.text},u=hh(null,e.picks),p=[$a({type:"analysis",title:e.title,fields:{...c,...u}}),...i.map(e=>$a({type:"requirement",title:"",req_type:s,fields:{...d(e),...u}}))],m=await mv({projectId:n,tool:"atoms_create_analysis",key:e.key,contents:p}),f=await Ba(t,n,[...m.createRefs,...m.link.slice(1)]),_={};f.has(m.create[0])||(_[o]=1);const h=m.create.slice(1).filter(e=>!f.has(e)).length;h>0&&(_[l]=(_[l]??0)+h);const g=Object.keys(_).length>0?nv(await rv(t,n,_)):null,y=f.get(m.create[0])?.item_id??g(o),w=m.create.slice(1).map(e=>f.get(e)?.item_id??g(l)),v=[{op_id:m.create[0],kind:"create_item",item_id:y,path:[],value:{type:"analysis",title:e.title,data:{body:"",...c}}}];i.forEach((e,t)=>{v.push({op_id:m.create[t+1],kind:"create_item",item_id:w[t],path:[],value:{type:"requirement",title:"",data:{body:"",req_type:s,analysis_props:"hara"===r?{source_req:null,...b_(e),approved:!1,approved_at:null,field_source:{}}:{source_req:e.text,approved:!1,approved_at:null,field_source:{}}}}})}),w.forEach((e,t)=>{v.push({op_id:m.link[t+1],kind:"add",item_id:y,path:["relationships","children"],value:e})});for(const t of w)v.push(...zS(t,null,e.picks));const b=await ov({client:t,projectId:n,ops:fv(v,m),preFound:f,labels:HS(a)}),k=m.create.map(e=>b.answers.find(t=>t.op_id===e)),{tokens:j,unread:x}=await _v(t,n,k.filter(e=>!!e)),S=k[0]?.item_id??y,$=i.map((t,n)=>{const a=k[n+1]?.item_id??w[n];return{..."hara"===r?k_(a,t):{id:a,source_req:t.text},...dh(e.picks)?hh(null,e.picks):{},...j.get(a)?{base_token:j.get(a)}:{}}});return lv(b.outcome,{id:S,subtype:r,title:e.title,revision:e.revision,scheme:a,variant:e.variant,labels:wh(a,e.stamp?"hazard_goal":"legacy"),...e.stamp?{event_model:"hazard_goal"}:{},...e.schemeStandard?{standard:e.schemeStandard}:{},...j.get(S)?{base_token:j.get(S)}:{},rows:$,...b.outcome.replayed?{message:yr}:{},...x?{warning:Yn}:{}},b)}({client:r,projectId:e.project_id,userId:i,subtype:o,schemeId:f,variant:p,schemeStandard:_,scopeInput:g,seeds:b,title:e.title??`New ${$c(f).parent}`,revision:e.revision??"1.0",key:e.idempotency_key,stamp:j,picks:k.picks});const S=async()=>{const t=ml[f],n=ac(f,"legacy"),a={[t]:1};a[n]=(a[n]??0)+b.length;const s=nv(await rv(r,e.project_id,a)),l=s(t),c=`New ${$c(f).parent}`,d=e.title??c,u=e.revision??"1.0",m=ul[o],h=(new Date).toISOString(),y={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:f,revision:u,..._?{standard:_}:{}},analysis_props:{variant:p,...g},metadata:{created_at:h,created_by:i,updated_at:h,updated_by:i}},{error:w}=await r.rpc("save_item_with_revision",{p_item_id:l,p_project_id:e.project_id,p_type:"analysis",p_title:d,p_data:y,p_user_id:i,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null});if(w)throw new Error(w.message);const v=(e,t)=>"hara"===o?k_(e,t):{id:e,source_req:t.text},k=[],j=[];for(const t of b){const a=s(n),c={id:a,type:"requirement",title:"",body:"",req_type:m,tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[l],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis_props:"hara"===o?{source_req:null,...b_(t),approved:!1,approved_at:null,field_source:{}}:{source_req:t.text,approved:!1,approved_at:null,field_source:{}},metadata:{created_at:h,created_by:i,updated_at:h,updated_by:i}},{error:d}=await r.rpc("save_item_with_revision",{p_item_id:a,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:q$()??null,p_diff_summary:null});if(d)throw new Error(d.message);const{error:u}=await r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:a,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 ${a}: ${u.message}\n`),j.push({row_id:a,..."hara"===o?{source_function:t.text}:{source_req:t.text},message:u.message})),await r.from("change_history").insert({item_id:a,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:c,actor:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),k.push(v(a,t))}return await r.from("change_history").insert({item_id:l,project_id:e.project_id,changed_by:i,event_type:"created",old_data:null,new_data:y,actor:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Iu(Xd({id:l,subtype:o,title:d,revision:u,scheme:f,variant:p,labels:$c(f),..._?{standard:_}:{},rows:k,...j.length>0?{link_warnings:j,warning:`${j.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 S()}catch(r){const a=cv(n,t,r);return a?DS(e,a):qu(vu(r))}var a}function NS(e){for(const t of Object.keys(e)){const n=e[t];"string"==typeof n&&(e[t]=Su(n))}}function HS(e){const t=new Map(sc(e).map(e=>[e.key,e.label]));return{analysisLabel:e=>t.get(e)??null}}function FS(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 LS(e,t,n){const r=n.data,a=new Map;for(const n of $S(r)){const r=await ky(e,t,n);r&&a.set(n,r)}const i=await of(e,t,{id:n.id,type:n.type,data:r},[...a.values()]),s=[];for(const r of i){const a=await ky(e,t,r);a?.data?.asil_source===n.id&&s.push(r)}return s}async function US(e,t){let n;try{const s=await Bu(),o=Yu();try{await tp(s,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const l=t??await iv(s,e.project_id);if("unreadable"===l)return sv();n=l;const c=await ky(s,e.project_id,e.row_id);if(!c)return qu(nu("Analysis row",e.row_id));const d=c.data;if("goal"===c.type){const t=gh(Object.keys(e.fields??{}));if(t.length>0)return qu(su(yh(c.id,t),Ud))}if("analysis"===c.type)return async function(e,t,n,r,a,i,s){const{schemeId:o}=await TS(e,n,function(e){return"dfmea"===e?.analysis?.subtype?"dfmea":"hara"}(a),a),l=function(e,t){const n=Ql(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,qo.includes(t)||Mo.includes(t);var t});if(a.length>0)return{ok:!1,message:zo(a)};const i=r.filter(e=>!n.includes(e));if(i.length>0)return{ok:!1,message:tc(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=Yl(e);if("overall_residual_risk"===n&&""!==r&&!a.includes(r))return{ok:!1,message:nc(n,r,a)};if("software_safety_class"===n&&""!==r&&!ll.includes(r))return{ok:!1,message:nc(n,r,ll)};s[n]=r}return{ok:!0,writes:s}}(o,i);if(!l.ok)return qu(su(l.message));const c=l.writes;if(NS(c),s){const{ops:t,refusals:i}=await pv({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 ov({client:e,projectId:n,ops:t,refusals:i,labels:HS(o)}),d={...a.analysis_props??{},...c};return lv(l.outcome,{analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:Zl(d),overall:Xl(d,Yl(o))},l)}return await(async()=>{const i=IS(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:q$()??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:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Iu(Xd({analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:Zl(s),overall:Xl(s,Yl(o))}))):qu(tu(`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"]))})()}(s,o,e.project_id,c,d,e.fields??{},"ops"===l?{tokens:dv(e.base_token)}:void 0);const u=SS(d?.req_type);if(!u)return qu(su(Sh(e.row_id,c.type,"atoms_fill_row"),Ud));const{schemeId:p}=await CS(s,e.project_id,u,d),m=await x_(p,Object.keys(e.fields??{}),()=>Bf(s,e.project_id));if(m)return qu(su(m,Ud));const{[Zf]:f,..._}=e.fields??{},h=ch(_);if(h.error)return qu(su(h.error));const g=h.rest,y=void 0!==f,w=dh(h.picks),v=(y||w)&&0===Object.keys(g).length?{ok:!0,writes:{}}:PS(p,u,g,{extraKeys:"hara"===u?["effect","title"]:["effect"]});if(!v.ok)return qu(su(v.message));const b=v.writes;NS(b);const k=mh(c.id,d?.relationships,Object.keys(b),h.picks);if(k)return qu(su(k,Ud));if(w){const t=await _h(s,e.project_id,c.id,p,await RS(s,e.project_id,p,d),h.picks,d?.relationships,t=>ky(s,e.project_id,t));if(t)return ES(t)}let j={};if(y){const t=await qS(s,e.project_id,p,{[Zf]:f});if(!t.ok)return t.result;Object.assign(b,t.writes),j=t.answer}const x=d?.analysis_props??null;if("ops"===l){const{ops:t,refusals:n}=await pv({client:s,projectId:e.project_id,itemId:c.id,tokens:dv(e.base_token),cells:FS(u,b)}),o=zS(c.id,d?.relationships,h.picks),l=await ov({client:s,projectId:e.project_id,ops:[...t,...o],refusals:n,labels:HS(p)}),m={...x??{}};for(const[e,t]of Object.entries(b))"effect"!==e&&"title"!==e&&(m[e]=t);const f=Object.keys(b).length>0&&Cc({...m})||(r=x,a=d?.relationships,i=h.picks,!0===r?.approved&&fh(a,i).length>0),_=vc(p,m),g=E_(d?.relationships,"event_goal").length>0||void 0!==h.picks.event_goal,y=0===l.outcome.not_applied.length&&"hara_iso26262"===p?[...new Set([...await LS(s,e.project_id,c),...g?await qh(s,e.project_id,(await ky(s,e.project_id,c.id))?.data?.relationships,t=>ky(s,e.project_id,t)):[]])].sort():[];return lv(l.outcome,{row_id:c.id,subtype:u,written_fields:Object.keys(b),written_columns:oc(p,Object.keys(b)),computed_level:_,..."hara_iso26262"===p?{asil_propagated_to:y}:{},...f?{approval_cleared:!0}:{},acceptance_revoked:uv(l.answers),...j,...w?hh(d?.relationships,h.picks):{}},l)}const S=async()=>{const t=function(e,t){const n={};for(const r of["event_hazard","event_goal"])void 0!==t[r]&&fh(e,{[r]:t[r]}).length>0&&(n[r]=t[r]);return n}(d?.relationships,h.picks);if(0===Object.keys(b).length&&0===Object.keys(t).length)return Iu(Xd({row_id:c.id,subtype:u,written_fields:[],written_columns:[],computed_level:vc(p,x),..."hara_iso26262"===p?{asil_propagated_to:[]}:{},acceptance_revoked:!1,...j,...w?hh(d?.relationships,h.picks):{}}));const n=IS(d);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.field_source&&"object"==typeof r.field_source||(r.field_source={});let a=c.title;for(const[e,t]of Object.entries(b))"effect"===e?n.body=t:"title"===e?(n.title=t,a=t):(r[e]=t,"failure_mode"===e&&"dfmea"===u&&(n.title=t,a=t)),r.field_source[e]="mcp";if(w){n.relationships={...n.relationships??{}};for(const[e,r]of Object.entries(t))n.relationships[e]=r?[r]:[]}const i=Cc(r),l=(new Date).toISOString();n.metadata={...n.metadata??{},updated_at:l,updated_by:o};const m=vc(p,r),f=vc(p,x),_=[];if("hara_iso26262"===p&&function(e,t,n){return t!==Bo&&(t!==n||e.some(e=>Jm.includes(e)))}(Object.keys(b),m,f)){const t=new Map;for(const r of $S(n)){const n=await ky(s,e.project_id,r);n&&t.set(r,n)}const r=await of(s,e.project_id,{id:c.id,type:c.type,data:n},[...t.values()]);for(const n of r){const r=t.get(n)??await ky(s,e.project_id,n);r&&lf(r.data,c.id,m,m!==f)&&_.push(r)}}const{data:g,error:y}=await s.rpc("save_item_with_revision",{p_item_id:c.id,p_project_id:e.project_id,p_type:c.type,p_title:a,p_data:n,p_user_id:o,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null,p_expected_updated_at:c.updated_at});if(y)throw new Error(y.message);if(!g)return qu(tu(`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 s.from("change_history").insert({item_id:c.id,project_id:e.project_id,changed_by:o,event_type:"updated",old_data:d,new_data:n,actor:M$(),session_id:q$(),...i?{reason:`${Object.keys(b).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 v=OS(d),k=v?await Do(v,"The row was",{readParent:()=>ky(s,e.project_id,v),saveParent:(t,n)=>Sd(()=>s.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:o,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at}),{scope:e.project_id,afterWrite:!0}),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},S=k.revoked,$=[],A=[];for(const t of _){const n=t.data,r=n?.asil??null,a=n?.asil_source??null,i=IS(n);i.asil=m,i.asil_source=c.id,i.metadata={...i.metadata??{},updated_at:l,updated_by:o};let d=null;try{const{error:n}=await s.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:i,p_user_id:o,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});n&&(d=n.message??"unknown error")}catch(e){d=e instanceof Error?e.message:String(e)}null===d?(await s.from("change_history").insert({item_id:t.id,project_id:e.project_id,changed_by:o,event_type:"updated",old_data:{asil:r,asil_source:a},new_data:{asil:m,asil_source:c.id},actor:M$(),session_id:q$(),reason:`ASIL propagated from ${c.id} (rating change via atoms_fill_row)`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),$.push(t.id)):(process.stderr.write(`[atoms-mcp] Warning: ASIL push from ${c.id} to ${t.id} failed: ${d}\n`),A.push(t.id))}const I=[k.warning,A.length>0?(q=c.id,M=A,`${q} was saved, but its ASIL did not reach ${M.join(", ")} (asil_propagation_failed). Repeat the same atoms_fill_row call to push it again; the row's rating is already stored.`):null].filter(e=>"string"==typeof e&&e.length>0);var q,M;return Iu(Xd({row_id:c.id,subtype:u,written_fields:Object.keys(b),written_columns:oc(p,Object.keys(b)),computed_level:m,...$.length>0?{asil_propagated_to:$}:{},...A.length>0?{asil_propagation_failed:A}:{},...i?{approval_cleared:!0}:{},acceptance_revoked:S,...I.length>0?{warning:I.join(" ")}:{},...j,...w?hh(d?.relationships,h.picks):{}}))};return await S()}catch(r){const a=cv(n,t,r);return a?US(e,a):qu(vu(r))}var r,a,i}function WS(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 VS(e,t,n,r=!1){const a=await ky(e,t,n);if(!a)return{ok:!1,result:qu(nu("Analysis",n))};if("analysis"!==a.type)return{ok:!1,result:qu(su(`Item ${n} is not an analysis (type='${a.type}')`))};const i=a.data,s=SS("hara"===i?.analysis?.subtype?"safety-goal":"dfmea"===i?.analysis?.subtype?"failure-mode":null);if(!s)return{ok:!1,result:qu(su(`Analysis ${n} is missing a valid analysis.subtype`))};const o=ul[s],{variant:l,schemeId:c}=await TS(e,t,s,i),d=vh(c,i),u=Array.isArray(i?.relationships?.children)?i.relationships.children.filter(e=>"string"==typeof e):[],p=r?await Qr(e,t,[a.id,...u]):new Map;let m=[];if(u.length>0){const n=await On([...new Set(u)],n=>e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",n)),r=new Set(u),a=new Map(n.filter(e=>!e.deleted_at&&r.has(e.id)&&e.data?.req_type===o).map(e=>[e.id,e]));m=u.map(e=>a.get(e)).filter(e=>Boolean(e))}const f=new Set;for(const e of m){const t=e.data?.analysis_props??{};"string"==typeof t.source_req&&t.source_req&&f.add(t.source_req);for(const t of $S(e.data))f.add(t);for(const t of AS(e.data))f.add(t);for(const t of z_(e.data?.relationships))f.add(t)}const _=new Map,h=new Map;let g=[];if(f.size>0){g=await On([...f],n=>e.from("items").select(Um).eq("project_id",t).is("deleted_at",null).in("id",n))??[];for(const e of g)_.set(e.id,e.updated_at),h.set(e.id,e.content_changed_at??e.updated_at)}const y=m.length>0?sf(m,[...g,...await af(e,t)]):new Map,w=await v_(e,t,function(e){return __(e.map(e=>l_(e).source_function_id))}(m.map(e=>({analysis_props:e.data?.analysis_props??null})))),v=d?await Ih(e,t):null,b=v?Ah(v):null,k="security_tir57"===c?await async function(e,t,n){const r=e=>cf(e.data?.relationships?.affects),a=[...new Set(n.flatMap(r))];if(0===a.length)return new Set;const i=await On(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 new Set(n.filter(e=>r(e).some(e=>s.has(e))).map(e=>e.id))}(e,t,m):new Set,j=new Map,x=m.map(e=>{const t=e.data?.analysis_props??{},n=y.get(e.id)??[],r=$S(e.data).filter(e=>_.has(e)),a=AS(e.data).filter(e=>_.has(e)),i=n.length>0,s=vc(c,t),o=z_(e.data?.relationships),l=new Set(o),d=b?function(e,t){const n=e.goalOf(t);return n&&e.goalIds.includes(n)?{cited:!0,satisfied:e.satisfiers(n).length>0,id:n}:{cited:!1,satisfied:!1,id:null}}(b,e.id):void 0,u=function(e,t,n,r){if(n)return null;if("hara_iso26262"===e&&r?.cited&&r.satisfied)return null;if("hara_iso26262"===e){const e=mc(t);return"QM"===e||e===Bo?null:r?.cited?`asil ${e} unmitigated: no safety requirement is linked to the row or satisfies its goal${r.id?` ${r.id}`:""}`:`asil ${e} unmitigated`}if("hazard_iso14971"===e){const e=hc(t);return"Low"!==e&&e!==Bo?`${e.toLowerCase()} risk uncontrolled`:null}if("security_tir57"===e){const e=yc(t);return Io(e)?`${e.toLowerCase()} security risk uncontrolled`:null}const a=parseInt(vc(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,d);j.set(e.id,{props:t,affectsLinked:k.has(e.id)});const p={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:dc(c,s),is_gap:null!==u,gap_rule:u,is_critical:bc(c,t,i,d),is_stale:kc(t,r,e=>(l.has(e)?h.get(e):_.get(e))??null,u_({analysis_props:t},c,w),o),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?gc(t):"security_tir57"===c?wc(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 nl[c])p[e]=t[e]??null;return Object.assign(p,function(e,t){const n=c_(l_(e).source_function_id).trim();if(!n)return{};const r=d_(e,t.schemeId,t.itemsById,t.tagMap);return{source_function_id:n,source_function_title:"live"===r.state?r.title:null}}({analysis_props:t},{schemeId:c,itemsById:w})),b&&Object.assign(p,function(e,t){const n=e.goalOf(t);return{...kh(t),hazard_id:e.hazardOf(t),goal_id:n,goal_asil:n&&e.isLiveId(n)?e.goalAsil(n):null,goal_display:n?(r=n,`Goal ${r}`):null};var r}(b,e.id)),p});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:Ll(c)??null,variant:l,labels:wh(c,d?"hazard_goal":"legacy"),...d?{event_model:"hazard_goal"}:{},acceptability:cc(c),definitions:lc(c),control_types:Ic(c),field_labels:sc(c),scope:Ql(c).length>0?Zl(i?.analysis_props):null,overall:Ql(c).length>0?Xl(i?.analysis_props,Yl(c)):null,threat_model:"security_tir57"===c?WS(i?.analysis_props):null,acceptance:To(i?.analysis_props)},schemeId:c,parentProps:i?.analysis_props??null,revisions:p,rows:x,gapFacts:j,stamped:b&&v?{index:b,items:v,rows:m.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data}))}:null,counts:{rows:x.length,gaps:x.filter(e=>e.is_gap).length,critical:x.filter(e=>e.is_critical).length,stale:x.filter(e=>e.is_stale).length,approved:x.filter(e=>e.approved).length,linked:x.filter(e=>e.mitigated_by.length>0).length}}}async function BS(e){try{return await async function(e,t=Yc){let n;const r=new Promise((e,r)=>{n=setTimeout(()=>r(new Xc(t)),t)});try{return await Promise.race([e(),r])}finally{clearTimeout(n)}}(()=>async function(e){const t=await Bu(),n=!0===await Ra(t,e.project_id),r=await VS(t,e.project_id,e.analysis_id,n);if(!r.ok)return r.result;const a=od(r.rows,e.offset,e.limit),i={paging:{list:"rows"}};if(!n)return Iu(Xd({analysis:r.analysis,rows:a.rows,counts:r.counts},a.meta),i);const s=async e=>{const t=r.revisions.get(e);return t?Wr(t,"analysis"):void 0},o=new Map(sc(r.schemeId).map(e=>[e.key,e.label])),l=await Zr(t,e.project_id,[r.analysis.id,...a.rows.map(e=>e.id)],{analysisLabel:e=>o.get(e)??null}),c=await s(r.analysis.id),d=await Promise.all(a.rows.map(async e=>{const t=await s(e.id);return{...e,...t?{base_token:t}:{},editing_now:l.get(e.id)??[]}}));return Iu(Xd({analysis:{...r.analysis,...c?{base_token:c}:{},editing_now:l.get(r.analysis.id)??[]},rows:d,counts:r.counts},a.meta),i)}(e))}catch(e){return qu(vu(e,{read:!0}))}}async function GS(e,t,n,r){const a=OS(n);if(!a)return;const i=await ky(e,t,a);if(!i)return;const{revoked:s,parentProps:o}=Po(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:q$()??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 JS(e,t,n,r){return!0===r?.analysis_props?.approved&&pk(r,await ky(e,t,n))}async function QS(e,t){let n;try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();if(n=i,e.row_id===e.req_id)return qu(su("row_id and req_id must be different items"));const s=await ky(r,e.project_id,e.row_id);if(!s)return qu(nu("Analysis row",e.row_id));const o=s.data;if("goal"===s.type)return await YS(r,e,s,i,null);const l=SS(o?.req_type);if(!l)return qu(su(Sh(e.row_id,s.type,"atoms_link_mitigation"),Ud));if("remove"!==e.action&&E_(o?.relationships,"event_goal").length>0){const{schemeId:t}=await CS(r,e.project_id,l,o),n=await RS(r,e.project_id,t,o),a=n?await ky(r,e.project_id,E_(o?.relationships,"event_goal")[0]):null,c=function(e,t,n){if(!e)return null;const r=E_(t,"event_goal")[0];return r&&n&&n.id===r&&"goal"===n.type&&(null===n.deleted_at||void 0===n.deleted_at)?r:null}(n,o?.relationships,a?{id:a.id,type:a.type,deleted_at:a.deleted_at??null}:null);if(c&&a)return await YS(r,e,a,i,s.id)}const c=await ky(r,e.project_id,e.req_id);if(!c)return qu(nu("Requirement",e.req_id));const d=c.data;if("remove"===e.action){if(void 0!==e.role||void 0!==e.control_type||void 0!==e.override)return qu(su(Qm));if(!df(e.row_id,o,e.req_id,d))return qu(su(uf(e.row_id,e.req_id),Ud));const{schemeId:t}=await CS(r,e.project_id,l,o);if("ops"===i){const n={op_id:ya(),kind:"remove",item_id:e.row_id,path:["relationships","mitigated_by"],value:e.req_id},a=await ov({client:r,projectId:e.project_id,ops:[n],labels:HS(t)});return lv(a.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,...await JS(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},acceptance_revoked:uv(a.answers)},a)}const n=async()=>{const{error:n}=await r.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:a,p_event_source:"mcp",p_expected_from_updated_at:s.updated_at,p_expected_to_updated_at:c.updated_at,p_role:null});if(n)throw new Error(n.message);await r.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"remove",type:"mitigated_by",from:e.row_id,to:e.req_id}},actor:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await GS(r,e.project_id,o,a);const i=await ky(r,e.project_id,e.row_id),l=i?.data,d=l?.analysis_props?.mitigation_types;if(i&&l&&d&&"object"==typeof d&&Object.prototype.hasOwnProperty.call(d,e.req_id)){const t=IS(l);delete t.analysis_props.mitigation_types[e.req_id],t.metadata={...t.metadata??{},updated_at:(new Date).toISOString(),updated_by:a};const{error:n}=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:t,p_user_id:a,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});if(n)throw new Error(n.message)}return Iu(Xd({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,...await JS(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{}}))};return await n()}if("requirement"!==c.type||kS.has(d?.req_type))return qu(su(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));const{schemeId:u}=await CS(r,e.project_id,l,o);if(qc(u)&&d?.req_type!==Lo)return qu(su(Mc(e.req_id,u)));const p=Ac(u);if(0===p.length&&void 0!==e.control_type)return qu(su(Oc(u)));if(p.length>0&&!e.control_type)return qu(su(Ec(u)));if(!(void 0===e.control_type||Ul(e.control_type)&&function(e,t){return Ac(e).some(e=>e.id===t)}(u,e.control_type)))return qu(su(Ec(u)));if("dfmea"===l&&!e.role)return qu(su(`role is required for dfmea mitigation links. Choose one of: ${Go.join(", ")}`));if("hara"===l&&e.role)return qu(su("role is not applicable to hara mitigation links; omit it (roles are a dfmea concept)"));if("ops"===i){const t="dfmea"===l?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,a={op_id:ya(),kind:"add",item_id:e.row_id,path:["relationships","mitigated_by"],value:n},i=await ov({client:r,projectId:e.project_id,ops:[a],labels:HS(u)});return lv(i.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:t,scheme:u,...e.control_type?{control_type:e.control_type}:{},...await JS(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},acceptance_revoked:uv(i.answers)},i)}const m=async()=>{let t=Bo;if("hara_iso26262"===u){t=vc(u,o?.analysis_props);const r=d?.asil;if(t!==Bo&&"string"==typeof r&&r.length>0&&r!==t&&!0!==e.override)return qu((i=t,{...tu(`ASIL conflict: the target requirement already carries asil '${n=r}' but ${p=s.id} computes '${i}'.`,["Pass override=true to apply the HARA value; the override is history-logged like a dialog accept","Or align the row's S/E/C ratings with the existing ASIL before linking"]),details:{code:"asil_conflict",current_value:n,incoming_value:i,source_row:p,hint:"pass override=true to apply the HARA value; the override is history-logged like a dialog accept"}}))}var n,i,p;const m="dfmea"===l?e.role:null,{error:f}=await r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:e.row_id,p_to_id:e.req_id,p_type:"mitigated_by",p_action:"add",p_user_id:a,p_event_source:"mcp",p_expected_from_updated_at:s.updated_at,p_expected_to_updated_at:c.updated_at,p_role:m});if(f)throw new Error(f.message);let _;await r.from("change_history").insert({item_id:e.row_id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:null,new_data:{relationship_change:{action:"add",type:"mitigated_by",from:e.row_id,to:e.req_id,...m?{role:m}:{}}},actor:M$(),session_id:q$()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await GS(r,e.project_id,o,a);let h,g=null;if(e.control_type&&Ul(e.control_type)){const t=e.control_type,n=await pS(async()=>{const t=await ky(r,e.project_id,e.row_id)??s,n=IS(t.data);n.analysis_props&&"object"==typeof n.analysis_props||(n.analysis_props={source_req:null,approved:!1,approved_at:null,field_source:{}});const i=n.analysis_props;i.mitigation_types&&"object"==typeof i.mitigation_types||(i.mitigation_types={}),i.mitigation_types[e.req_id]=e.control_type;const o=(new Date).toISOString();n.metadata={...n.metadata??{},updated_at:o,updated_by:a};const{error:l}=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:q$()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});return l??null});n?(process.stderr.write(`[atoms-mcp] Warning: control type write after the link failed for '${e.row_id}': ${n.message}\n`),g={value:t,message:String(n.message??"unknown error")}):_=t}let y=null;if("hara_iso26262"===u&&t!==Bo){let n=null,i=null,o=null;const l=await pS(async()=>{const l=await ky(r,e.project_id,e.req_id);if(o=l?.id??null,!l)return null;const c=l.data;n=c?.asil??null,i=c?.asil_source??null;const d=IS(c);d.asil=t,d.asil_source=s.id;const u=(new Date).toISOString();d.metadata={...d.metadata??{},updated_at:u,updated_by:a};const{error:p}=await r.rpc("save_item_with_revision",{p_item_id:l.id,p_project_id:e.project_id,p_type:l.type,p_title:l.title,p_data:d,p_user_id:a,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null,p_expected_updated_at:l.updated_at});return p??null});l?(process.stderr.write(`[atoms-mcp] Warning: ASIL write after the link failed for '${e.req_id}': ${l.message}\n`),y={level:t,message:String(l.message??"unknown error")}):o&&(await r.from("change_history").insert({item_id:o,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{asil:n,asil_source:i},new_data:{asil:t,asil_source:s.id},actor:M$(),session_id:q$(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${n??"unset"}', now '${t}' 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`)}),h=t)}return Iu(Xd({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",role:m,scheme:u,..._?{control_type:_}:{},...h?{asil_written:h}:{},...await JS(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},...mS({rowId:e.row_id,reqId:e.req_id,asil:y,controlType:g})}))};return await m()}catch(r){const a=cv(n,t,r);return a?QS(e,a):qu(vu(r))}}async function YS(e,t,n,r,a){const i="hara_iso26262";if(void 0!==t.role)return qu(su("role is not applicable to a Safety goal's mitigation links; omit it (roles are a dfmea concept)"));if(void 0!==t.control_type)return qu(su(Oc(i)));if(t.req_id===n.id)return qu(su("row_id and req_id must be different items"));const s=await ky(e,t.project_id,t.req_id);if(!s)return qu(nu("Requirement",t.req_id));const o=s.data,l="remove"===t.action?"remove":"add";if("remove"===l){if(void 0!==t.override)return qu(su(Qm));if(!df(n.id,n.data,t.req_id,o))return qu(su(uf(n.id,t.req_id),Ud))}else{if("requirement"!==s.type||kS.has(o?.req_type))return qu(su(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${t.req_id}`));if(qc(i)&&o?.req_type!==Lo)return qu(su(Mc(t.req_id,i)))}if("ops"!==r)return qu(_o());const c={op_id:ya(),kind:l,item_id:n.id,path:["relationships","mitigated_by"],value:t.req_id},d=await ov({client:e,projectId:t.project_id,ops:[c],labels:HS(i)}),u=await ky(e,t.project_id,t.req_id),p=u?.data??{};return lv(d.outcome,{row_id:n.id,req_id:t.req_id,type:"mitigated_by",..."remove"===l?{action:"remove"}:{role:null},scheme:i,...a?{redirected_from:a}:{},asil:"string"==typeof p.asil?p.asil:null,asil_source:"string"==typeof p.asil_source?p.asil_source:null,acceptance_revoked:uv(d.answers)},d)}async function KS(e){try{const n=await Bu(),r=await VS(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=Wl(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=Tc(r.schemeId).some(e=>"requirement"===e.scope)?await async function(e,t,n){const r=(await Sn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null).eq("type","requirement"),pn)).filter(e=>e.data?.req_type===Lo&&function(e,t){const n=Vl(e);return n.length>0&&n===Vl(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 On([...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??Bo,severity:zc(e.severity),props:r.gapFacts.get(e.id)?.props??null,affectsLinked:r.gapFacts.get(e.id)?.affectsLinked??!1})),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=bS(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:ec(e),overallJudged:""!==Xl(e,a?vo:ol).residual_risk,everyRowSettled:t.every(e=>e.linked&&e.residualLevel!==Bo),catalogsDraft:r,accepted:"accepted"===e?.acceptance_state}}(r.parentProps,o,r.schemeId,l),d=await async function(e,t,n,r){if(!j_(n))return[];if("items"!==await Bf(e,t))return[];const a=await Sn(()=>e.from("items").select("id, type, title").eq("project_id",t).eq("type","function").is("deleted_at",null),pn),{data:i,error:s}=await e.from("function_tag_items").select("tag_key, item_id").eq("project_id",t).is("reverted_at",null).order("tag_key",{ascending:!0}).range(0,999);if(s)throw new Error(`Function tag map read failed: ${s.message??"unknown error"}`);const o=Array.isArray(i)?i:[];if(o.length>=1e3)throw new Error("Function tag map read failed: the moved functions could not be read in full.");return function(e,t,n,r){if(!j_(e))return[];const a=new Map(n.map(e=>[e.id,e])),i=new Set,s=[];for(const n of t){const t=d_(n,e,a,r);"live"===t.state&&t.id?i.add(t.id):"trashed"===t.state&&s.push(n.id)}const o=n.filter(e=>"function"===e.type&&!i.has(e.id)).map(e=>e.id),l=[];return o.length>0&&l.push({kind:"function_not_analysed",label:`${o.length} ${1===o.length?"function":"functions"} not analysed`,rowIds:[],reqIds:[],functionIds:o,count:o.length,fix:"open_item",fixLabel:"Open function"}),s.length>0&&l.push({kind:"function_missing",label:`${s.length} ${1===s.length?"row names":"rows name"} a function that is not live`,rowIds:s,reqIds:[],count:s.length,fix:"open_row",fixLabel:"Open row"}),l}(n,r,a,o)}(n,e.project_id,r.schemeId,r.rows.map(e=>({id:e.id,analysis_props:r.gapFacts.get(e.id)?.props??null}))),u=[...Pc(r.schemeId,o,s,c),...d],p=r.stamped?function(e,t,n){const r=function(e){const t=e=>e.reduce((e,t)=>e.concat(t.rowIds),[]);return[{kind:"row_no_goal",count:e.rowNoGoal.length,rowIds:[...e.rowNoGoal],goalIds:[],hazardIds:[],criticalIds:[...e.rowNoGoalCritical]},{kind:"goal_no_safety_req",count:e.goalNoSafetyReq.length,rowIds:t(e.goalNoSafetyReq),goalIds:e.goalNoSafetyReq.map(e=>e.goalId),hazardIds:[],criticalIds:e.goalNoSafetyReq.filter(e=>e.critical).map(e=>e.goalId)},{kind:"goal_no_test",count:e.goalNoTest.goals.length+e.goalNoTest.rowIds.length,rowIds:[...e.goalNoTest.rowIds,...t(e.goalNoTest.goals)].sort(),goalIds:e.goalNoTest.goals.map(e=>e.goalId),hazardIds:[],criticalIds:[]},{kind:"hazard_uncited",count:e.hazardUncited.length,rowIds:[],goalIds:[],hazardIds:[...e.hazardUncited],criticalIds:[]},{kind:"goal_trashed",count:e.goalTrashed.rowIds.length,rowIds:[...e.goalTrashed.rowIds],goalIds:[...e.goalTrashed.goalIds],hazardIds:[],criticalIds:[]}].filter(e=>e.count>0)}(function(e,t){const n=e=>e!==Bo&&"QM"!==e&&O_(e)>0,r=[],a=[],i=[],s=new Map,o=[],l=new Set;for(const c of t){const t=mc(c.analysis_props),d=e.goalOf(c.id);if(d&&e.isLiveId(d)){let e=s.get(d);e||s.set(d,e=[]),e.push(c.id);continue}if(d&&(o.push(c.id),l.add(d)),!n(t))continue;const u=e.directMitigators(c.id).filter(t=>e.isLiveId(t));0===u.length?(r.push(c.id),"C"!==t&&"D"!==t||a.push(c.id)):u.some(t=>e.requirementVerified(t))||i.push(c.id)}const c=new Map(t.map(e=>[e.id,mc(e.analysis_props)])),d=[],u=[];for(const t of[...s.keys()].sort()){const n=e.goalCoverage(t,s.get(t));if(n.uncoveredRows.length>0){const e=n.uncoveredRows.some(e=>"C"===c.get(e)||"D"===c.get(e));d.push({goalId:t,critical:e,rowIds:[...n.uncoveredRows]})}n.untestedRows.length>0&&u.push({goalId:t,critical:!1,rowIds:[...n.untestedRows]})}return{rowNoGoal:r,rowNoGoalCritical:a,goalNoSafetyReq:d,goalNoTest:{goals:u,rowIds:i},hazardUncited:e.hazardIds.filter(t=>0===e.rowsOfHazard(t).length),goalTrashed:{rowIds:o,goalIds:[...l].sort()}}}(t,$h(n))).map(e=>{const t=Dl.find(t=>t.kind===e.kind);return{kind:e.kind,label:t.label(e.count),rowIds:[...e.rowIds],reqIds:[],count:e.count,fix:t.fix,fixLabel:t.fixLabel,...e.goalIds.length>0?{goalIds:[...e.goalIds]}:{},...e.hazardIds.length>0?{hazardIds:[...e.hazardIds]}:{},...e.criticalIds.length>0?{criticalIds:[...e.criticalIds]}:{},...t.informational?{informational:!0}:{}}});return[...r.filter(e=>!e.informational),...e.filter(e=>"unmitigated"!==e.kind&&"no_test"!==e.kind),...r.filter(e=>e.informational)]}(u,r.stamped.index,r.stamped.rows):u,m=p.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,...e.goalIds?{goal_ids:e.goalIds}:{},...e.hazardIds?{hazard_ids:e.hazardIds}:{},...e.criticalIds?{critical_ids:e.criticalIds}:{},...e.informational?{informational:!0}:{},...e.functionIds?{function_ids:e.functionIds}:{}}));return Iu(Xd({analysis_id:r.analysis.id,subtype:r.analysis.subtype,scheme:r.analysis.scheme,labels:r.analysis.labels,gaps:a,count:(t=p,t.reduce((e,t)=>e+(t.informational?0:t.count),0)),gap_kinds:m,system_level:i.level,system_level_source:i.source}))}catch(e){return qu(vu(e,{read:!0}))}var t}async function ZS(e,t){let n;const r=m_("atoms_propose_rows",e);if(r)return qu(r);try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();n=i;const s=await ky(r,e.project_id,e.analysis_id);if(!s)return qu(nu("Analysis",e.analysis_id));if("analysis"!==s.type)return qu(su(`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 qu(su(`Analysis ${e.analysis_id} is missing a valid analysis.subtype`));const{variant:d,schemeId:u}=await TS(r,e.project_id,c,o);if("hara"===c&&e.source_req)return qu(su("A risk analysis row is seeded from a function, never a requirement: pass source_function_id"));if("dfmea"===c&&void 0!==e.source_function_id)return qu(su("source_function_id applies to a HARA or a risk analysis only; seed an FMEA row with source_req"));const p=Array.isArray(e.rows)?e.rows:[];if(0===p.length)return qu(su("rows must contain at least one drafted row"));if(p.length>Wo)return qu(su(`Propose rows accepts at most ${Wo} rows per call; ${p.length} were sent. Split the proposal and call again.`));const m=[],f=[];for(let t=0;t<p.length;t++){const n=await x_(u,Object.keys(p[t]??{}),()=>Bf(r,e.project_id));if(n)return qu(su(`row ${t+1}: ${n}`,Ud));const a=ch(p[t]??{});if(a.error)return qu(su(`row ${t+1}: ${a.error}`));const i=PS(u,c,a.rest,{extraKeys:"hara"===c?["effect","title"]:["effect"],where:`row ${t+1}`});if(!i.ok)return qu(su(i.message));NS(i.writes);const s=mh(`row ${t+1}`,null,Object.keys(i.writes),a.picks);if(s)return qu(su(s,Ud));m.push(i.writes),f.push(a.picks)}const _=rc(o);for(let t=0;t<f.length;t++){const n=await _h(r,e.project_id,`row ${t+1}`,u,vh(u,o),f[t],null,t=>ky(r,e.project_id,t));if(n)return ES(n)}const h=await async function(e,t,n,r){if(void 0===r)return{ok:!0,seed:null};const a=await x_(n,[Zf],()=>Bf(e,t));if(a)return{ok:!1,error:S_(a)};if("string"!=typeof r)return{ok:!1,error:{status:"error",message:'Validation error: source_function_id must be a string, the id of a Function item ("" clears it on a project with Function items turned on). Nothing was written.',next_steps:["Find the project's Functions with atoms_list_items type 'function'"],code:"function_id_invalid",retryable:!1}};const i=await y_(e,t,r.trim()?[r]:[]);if(!i.ok)return i;const s=i.functions[0];return{ok:!0,seed:s?{text:s.title,functionId:s.id}:null}}(r,e.project_id,u,e.source_function_id);if(!h.ok)return qu(h.error);const g=h.seed;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=ul[r],l=ac(a,e.model),c=i.map((t,a)=>function(e,t,n,r,a){return function(e,t){return Tr({analysis_id:e,writes:Sa(t)})}(e,{...t,__seed:"hara"===n?r?r.functionId??r.text:"":a??null})}(n.analysis_id,{...t,...hh(null,e.rowPicks[a]??{})},r,e.seed,n.source_req)),d=await mv({projectId:s,tool:"atoms_propose_rows",key:n.idempotency_key,contents:c}),u=await Ba(t,s,[...d.createRefs,...d.link]),p=d.create.filter(e=>!u.has(e)).length,m=p>0?nv(await rv(t,s,{[l]:p})):null,f=d.create.map(e=>u.get(e)?.item_id??m(l)),_=[],h=[];i.forEach((t,a)=>{const i={source_req:"dfmea"===r?n.source_req??null:null,..."hara"===r?$_(e.seed):{},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=Jl(t)),h.push({writes:t,props:i}),_.push({op_id:d.create[a],kind:"create_item",item_id:f[a],path:[],value:{type:"requirement",title:l,data:{body:s,req_type:o,analysis_props:i}}})}),f.forEach((e,t)=>{_.push({op_id:d.link[t],kind:"add",item_id:n.analysis_id,path:["relationships","children"],value:e})}),f.forEach((t,n)=>_.push(...zS(t,null,e.rowPicks[n]??{})));const g=await ov({client:t,projectId:s,ops:fv(_,d),preFound:u,labels:HS(a)}),y=d.create.map(e=>g.answers.find(t=>t.op_id===e)),{tokens:w,unread:v}=await _v(t,s,y.filter(e=>!!e)),b=h.map((t,n)=>{const r=y[n]?.item_id??f[n];return{id:r,written_fields:Object.keys(t.writes),written_columns:oc(a,Object.keys(t.writes)),computed_level:vc(a,t.props),...dh(e.rowPicks[n]??{})?hh(null,e.rowPicks[n]):{},...w.get(r)?{base_token:w.get(r)}:{}}});return lv(g.outcome,{analysis_id:n.analysis_id,subtype:r,scheme:a,...e.variant?{variant:e.variant}:{},labels:wh(a,e.model),...A_(r,e.seed,n.source_req),rows:b,count:b.length,max_rows:Wo,approved:!1,acceptance_revoked:uv(g.answers),...g.outcome.replayed?{message:yr}:{},...v?{warning:Yn}:{}},g)}({client:r,params:e,parent:s,subtype:c,schemeId:u,variant:d,validatedRows:m,seed:g,model:_,rowPicks:f});const y=async()=>{const t=(new Date).toISOString(),n=ul[c],i=[],s=[],o=ac(u,_),l=nv(await rv(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?$_(g):{},approved:!1,approved_at:null,approved_by:null,field_source:{}};let f="",_="";for(const[e,t]of Object.entries(d))"effect"===e?f=t:"title"===e?_=t:(m[e]=t,"failure_mode"===e&&"dfmea"===c&&(_=t)),m.field_source[e]="mcp";_||(_=Jl(d));const h={id:p,type:"requirement",title:_,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:y}=await Sd(()=>r.rpc("save_item_with_revision",{p_item_id:p,p_project_id:e.project_id,p_type:"requirement",p_title:_,p_data:h,p_user_id:a,p_event_source:"mcp",p_event_session_id:q$()??null,p_diff_summary:null}),{scope:e.project_id});if(y)throw new Error(y.message);const{error:w}=await Sd(()=>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"}),{scope:e.project_id,afterWrite:!0});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:h,actor:M$(),session_id:q$(),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),written_columns:oc(u,Object.keys(d)),computed_level:vc(u,m)})}let p=!1,f=null;if(i.length>0)try{for(let t=0;t<3;t+=1){const n=await ky(r,e.project_id,e.analysis_id);if(!n)break;const i=n.data,{revoked:s,parentProps:o}=Po(i);if(!s)break;const l={...i,analysis_props:o},{error:c}=await Sd(()=>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:q$()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at}),{scope:e.project_id,afterWrite:!0});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`),f=`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`),f=`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 Iu(Xd({analysis_id:e.analysis_id,subtype:c,scheme:u,...d?{variant:d}:{},labels:wh(u,_),...A_(c,g,e.source_req),rows:i,count:i.length,max_rows:Wo,approved:!1,acceptance_revoked:p,...s.length>0||null!==f?{...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,f].filter(e=>null!==e).join(" ")}:{}}))};return await y()}catch(r){const a=cv(n,t,r);return a?ZS(e,a):qu(vu(r))}}async function XS(e,t){let n;try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();n=i;const s=await ky(r,e.project_id,e.row_id);if(!s)return qu(nu("Analysis row",e.row_id));const o=s.data,l=SS(o?.req_type);if(!l)return qu(su(Sh(e.row_id,s.type,"atoms_suggest_field"),Ud));const{schemeId:c}=await CS(r,e.project_id,l,o),d=e.rationale?function(e,t){return tl[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 qu(su(`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=await qS(r,e.project_id,c,u);if(!p.ok)return p.result;const m=0===Object.keys(p.rest).length?{ok:!0,writes:{}}:PS(c,l,p.rest,{extraKeys:"hara"===l?["effect","title"]:["effect"]});if(!m.ok)return qu(su(m.message));const f=m.writes;NS(f),Object.assign(f,p.writes);const _=p.answer;if("ops"===i){const{ops:t,refusals:n}=await pv({client:r,projectId:e.project_id,itemId:s.id,tokens:dv(e.base_token),cells:FS(l,f)}),a=await ov({client:r,projectId:e.project_id,ops:t,refusals:n,labels:HS(c)}),i={...o?.analysis_props??{}},u={...i.field_source??{}};for(const[e,t]of Object.entries(f))"effect"!==e&&"title"!==e&&(i[e]=t),u[e]="mcp";const p=Cc({...i}),m=Object.entries(u).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return lv(a.outcome,{row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(f),written_columns:oc(c,Object.keys(f)),...d?{rationale_field:d}:{},...p?{approval_cleared:!0}:{},row:{id:s.id,computed_level:vc(c,i),approved:!0===i.approved&&!p,mcp_fields:m,...Object.fromEntries(nl[c].map(e=>[e,i[e]??null])),..._},acceptance_revoked:uv(a.answers),..._},a)}const h=async()=>{const t=IS(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(f))"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=Cc(n),p=(new Date).toISOString();t.metadata={...t.metadata??{},updated_at:p,updated_by:a};const{data:m,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:q$()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(h)throw new Error(h.message);if(!m)return qu(tu(`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:M$(),session_id:q$(),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 g=OS(o),y=g?await Do(g,"The suggestion was",{readParent:()=>ky(r,e.project_id,g),saveParent:(t,n)=>Sd(()=>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:q$()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at}),{scope:e.project_id,afterWrite:!0}),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 Iu(Xd({row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(f),written_columns:oc(c,Object.keys(f)),...d?{rationale_field:d}:{},...u?{approval_cleared:!0}:{},acceptance_revoked:y.revoked,...y.warning?{warning:y.warning}:{},row:{id:s.id,computed_level:vc(c,n),approved:!0===n.approved,mcp_fields:w,...Object.fromEntries(nl[c].map(e=>[e,n[e]??null])),..._},..._}))};return await h()}catch(r){const a=cv(n,t,r);return a?XS(e,a):qu(vu(r))}}async function e$(e,t){let n;try{const r=await Bu(),a=Yu();try{await tp(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}const i=t??await iv(r,e.project_id);if("unreadable"===i)return sv();n=i;const s=await ky(r,e.project_id,e.row_id);if(!s)return qu(nu("Analysis row",e.row_id));const o=s.data,l=SS(o?.req_type);if(!l)return qu(su(Sh(e.row_id,s.type,"atoms_approve_row"),Ud));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 qu(su(`Approver '${c}' is not a member of this project's organization. Approve as a project member (omit approver_id to approve as yourself).`));if("viewer"===d)return qu(su(function(e){return`Approver '${e}' is a viewer of this project's organization, and a viewer cannot be the human checker. Name an editor or admin (omit approver_id to approve as yourself).`}(c)));const{schemeId:u}=await CS(r,e.project_id,l,o),p=o?.analysis_props??{},m=vc(u,p);if(m===Bo)return qu(su(`${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=Su(e.note??""),n=(new Date).toISOString(),{ops:a,refusals:i}=await pv({client:r,projectId:e.project_id,itemId:s.id,tokens:dv(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 ov({client:r,projectId:e.project_id,ops:a,refusals:i,labels:HS(u)}),f=Object.entries(p.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return lv(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:f,acceptance_revoked:uv(o.answers)},o)}const f=async()=>{const t=IS(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=Su(e.note??""),f=(new Date).toISOString();n.approved=!0,n.approved_at=f,n.approved_by=c,n.approved_note=i;const _=[];for(const[e,t]of Object.entries(n.field_source))"mcp"===t&&(n.field_source[e]="user",_.push(e));_.sort(),t.metadata={...t.metadata??{},updated_at:f,updated_by:a};const{data:h,error:g}=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:q$()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(g)throw new Error(g.message);if(!h)return qu(tu(`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:f,approved_by:c,approved_note:i},actor:M$(),session_id:q$(),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 y=OS(o);if(y){const t=await ky(r,e.project_id,y);if(t){const{revoked:n,parentProps:i}=Po(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:q$()??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 Iu(Xd({row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:c,approved_at:f,approved_note:i,approver_role:d,computed_level:m,cleared_markers:_}))};return await f()}catch(r){const a=cv(n,t,r);return a?e$(e,a):qu(vu(r))}}D(xS,{approveRowHandler:()=>e$,createAnalysisHandler:()=>DS,fillRowHandler:()=>US,getAnalysisHandler:()=>BS,getGapsHandler:()=>KS,linkMitigationHandler:()=>QS,proposeRowsHandler:()=>ZS,suggestFieldHandler:()=>XS});var t$=P({"src/tools/analysis.ts"(){yS(),sp(),fe(),qy(),mk(),av(),Rd(),vd(),kr(),E$(),zu(),ai(),vv(),ai(),sd(),Wc(),M_(),s_(),jS(),Di(),Nh(),rh(),$o(),hf(),Nl(),kS=new Set(["safety-goal","failure-mode"])}}),n$={};async function r$(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=bS(n?.scenario_catalogs??[]);return a.ok?a.value:[]}async function a$(e){try{const t=await Bu(),n=Math.min(Math.max(e.limit??50,1),200),r=Math.max(e.offset??0,0),a=await r$(t,e.project_id);return Iu(Xd(a.slice(r,r+n),ld(a.length,n,r)),{paging:{}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(vu(e,{read:!0}))}}async function i$(e){const t=m_("atoms_mutate_scenario_catalog",e);if(t)return qu(t);try{const t=await Bu();Yu();try{await tp(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return qu(iu("Viewer"));throw e}if("string"!=typeof(n=e.op)||!gS.includes(n))return qu(su("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 r$(t,e.project_id)).length>=hS)return qu(su(`This project already carries the maximum of ${hS} catalogs.`));const a={};if("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=Su(e.name)),void 0!==e.entry_id&&(a.entry_id=e.entry_id),void 0!==e.text&&(a.text=Su(e.text)),void 0!==e.function_ids){const n=await async function(e,t,n){const r=await Bf(e,t);if(0===n.length){if("tags"===r)return{ok:!0,payload:{function_tags:[]}};if("items"===r)return{ok:!0,payload:{function_ids:[],function_tags:[]}}}else if("tags"===r)return{ok:!1,error:{status:"error",message:t_,next_steps:[...n_],code:"function_items_off",retryable:!1}};const a=await w_(e,t,n,r);return a.ok?{ok:!0,payload:{function_ids:a.functions.map(e=>e.id)}}:a}(t,e.project_id,e.function_ids);if(!n.ok)return qu(n.error);Object.assign(a,n.payload)}void 0!==e.by&&(a.by=e.by),void 0!==e.on&&(a.on=e.on);const{data:i,error:s}=await t.rpc("mutate_project_scenario_catalogs",{p_project_id:e.project_id,p_op:r,p_payload:a});return s?qu(Y(s.message)??su(s.message)):Iu(Xd({scenario_catalogs:i?.scenario_catalogs??[]}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?qu(ou()):qu(ju(e instanceof Error?e.message:String(e)))}var n}D(n$,{listScenarioCatalogsHandler:()=>a$,mutateScenarioCatalogHandler:()=>i$});var s$,o$,l$,c$,d$,u$,p$,m$,f$,_$,h$,g$,y$,w$,v$,b$,k$,j$=P({"src/tools/catalogs.ts"(){vd(),sp(),re(),zu(),M_(),jS()}}),x$={};function S$(e){Ge(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=z.default.dirname(n);return z.default.resolve(r,"apps","src","apps",e,t)}(t.appName,t.htmlFile),a=[...ly.resourceDomains,...t.extraResourceDomains??[]];l.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:n}}},t.handler),l.registerAppResource(e,`${t.title} UI`,n,{mimeType:l.RESOURCE_MIME_TYPE},async()=>{const e=await E.default.readFile(r,"utf-8");return{contents:[{uri:n,mimeType:l.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:a}}}}]}})}(d$,e)}function $$(e){return void 0===e?.requestId?void 0:String(e.requestId)}function A$(e,t,n){const r=t instanceof Error?t.message:String(t?.message??t);return process.stderr.write(`[atoms-mcp] ${e} lookup failed: ${r}\n`),t instanceof $t||/^auth_unavailable:/.test(r)?qu(Mt()):Kt(r)?qu(uu()):/not authenticated/i.test(r)?qu(ou()):wu(t)||Zt(r)?qu(lu()):qu(n())}function I$(e,t){return async(n,r)=>{let a="",i=null,s=!1;try{i=await Bu(),a=Yu()}catch(e){i=null,s=e instanceof $t}if(i){const e=await async function(e,t){let n;try{n=await Ru(e,t)}catch(e){return process.stderr.write(`[atoms-mcp] platform_status lookup failed: ${e instanceof Error?e.message:String(e?.message??e)}\n`),wu(e)?lu():tu("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?ru("account"):"pending"===n?tu("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 qu(e)}if(i&&await Ue(i,a),Te)return qu({status:"error",message:L,next_steps:["Wait a few seconds, then retry the same call"],code:"policy_unavailable",retryable:!0,retry_after_seconds:2});if(!Re&&h.has(e))return qu(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}:ou());if(!ne.has(e)){let t;try{t=await Qu(async()=>(i=await Bu(),a=Yu(),async function(e,t,n,r){if(ne.has(n))return{refused:!1};const a=await ae(e,t);if(ie(a))return{refused:!0,reason:"viewer_everywhere"};const i=se(a);if(0===i.size)return{refused:!1};const{projectIds:s}=await oe(e,r);for(const t of s){const n=await le(e,t);if(n&&i.has(n))return{refused:!0,reason:"viewer_in_org"}}return{refused:!1}}(i,a,e,n)))}catch(e){return A$("viewer gate",e,de)}if(t.refused)return qu((o=t.reason,{status:"error",message:X,next_steps:[..."viewer_everywhere"===o?te:ee]}))}var o;{let t;try{t=await Qu(async()=>{let t=null,r=null;try{t=await Bu(),i=t,a=Yu()}catch(s){r=s}return async function(e){const{client:t,toolName:n,params:r}=e;let a=e.set;const i=e.envProjectId??null,s=e.envOrgId??null,o=t=>e.envProjectRefusal?.(t)??null,l=r&&"object"==typeof r?r:{};if(!s&&!function(e,t,n){if(e.orgs.length<2)return!1;const r=e.orgs.map(e=>e.effective);if(r.some(e=>null!==e.project_scope))return!0;const a=e=>new Set(r.map(t=>JSON.stringify(e(t)))).size>1;return!!a(e=>ve(e,t,n))||!!a(e=>e.require_confirmation_for.includes(t))||pe.has(t)&&a(e=>J(e,"atoms_create_level").allowed)}(a,n,r)){const e=a.orgs[0]?.effective??H,s=ve(e,n,r);if(s)return s;if(i&&"string"==typeof l.project_id&&l.project_id!==i)return o(i);let c={projectIds:"string"==typeof l.project_id?[l.project_id]:[],unresolved:0};return ue.some(e=>"string"==typeof l[e])&&(i||null!==e.project_scope)&&(c=await oe(t,r)),i&&(c.unresolved>0||c.projectIds.some(e=>e!==i))?o(i):K(e,c.projectIds,c.unresolved)}const{targets:c,unresolved:d}=await async function(e,t,n){const r=n&&"object"==typeof n?n:{},a="string"==typeof r.project_id?[r.project_id]:[];let i=0;for(const t of ue){const n=r[t];if("string"!=typeof n)continue;const s=await ce(e,n);s?a.push(s):i++}const s=[];for(const n of a)s.push({projectId:n,orgId:await be(e,t,n)});return{targets:s,unresolved:i}}(t,a,r);if(s&&(d>0||c.some(e=>e.orgId!==s)))return e.envOrgRefusal?.(s)??null;const u=()=>c.filter(e=>null!==e.orgId&&!a.orgs.some(t=>t.orgId===e.orgId));if(e.reload&&u().length>0){a=await e.reload();for(const e of u())a.projectOrgs.delete(e.projectId)}const p=new Map,m=c.filter(e=>null===e.orgId).map(e=>e.projectId);for(const e of c)null===e.orgId||p.has(e.orgId)||p.set(e.orgId,{policy:ge(a,e.orgId),projectIds:[],unresolved:0});for(const e of c)null!==e.orgId&&p.get(e.orgId).projectIds.push(e.projectId);if(0===p.size)p.set("",{policy:ye(a),projectIds:m,unresolved:d});else for(const e of p.values())e.projectIds.push(...m),e.unresolved=d;for(const e of p.values()){const t=ve(e.policy,n,r);if(t)return t}if(i&&(d>0||c.some(e=>e.projectId!==i)))return o(i);for(const e of p.values()){const t=K(e.policy,e.projectIds,e.unresolved);if(t)return t}return null}({client:t??(s=r,{from:()=>{throw s instanceof Error?s:new Error("Not authenticated")}}),set:Fe(),toolName:e,params:n,envProjectId:$e(),envProjectRefusal:cu,envOrgId:Ae(),envOrgRefusal:du,reload:t?()=>async function(e,t){return Oe=0,await Ue(e,t),Me}(t,a):void 0});var s})}catch(e){return A$("project scope",e,Z)}if(t)return qu(t)}if(!i)return t(n,r);const l=await async function(e,t){const n=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Pp,r=new Date,a=new Date(r.getTime()-Dp);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())+Dp-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*Dp);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(!l.allowed)return qu(uu(l.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(()=>(sp(),Vu));await t(i,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(zu(),Yd));return qu(e("Viewer (lockdown mode: read access requires editor or admin)"))}}}const c=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let d,u="success";try{const e=await t(n,r),a=e;if(!0===a?.isError){u="error";const e=a?.content;if(e?.[0]?.text)try{d=JSON.parse(e[0].text).message}catch{}}return Xp(e,c$)}catch(e){throw u="error",d=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:n,status:u,duration_ms:c(),error_msg:d,project_id:n.project_id,session_id:p$,client_name:O$(),client_version:c$};try{!function(e,t,n){const r=Cp(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 Bu(),a,t)}catch{}}}}function q$(){return p$}function M$(){return Lt(O$())}function O$(){const e=process.env.ATOMS_CLIENT_NAME;return Ft(e&&e.trim()?e:d$.server.getClientVersion()?.name)}D(x$,{ATOMS_MCP_SERVER_VERSION:()=>c$,getMcpActor:()=>M$,getMcpClientName:()=>O$,getMcpSessionId:()=>q$,server:()=>d$});var E$=P({"src/server.ts"(){var e;Ap(),Rp(),Vp(),Bp(),Ye(),Ie(),We(),wm(),re(),Se(),Qt(),vm(),Wc(),B(),dg(),lg(),Jg(),sy(),M_(),cy(),Zm(),ai(),Qd(),Nh(),sp(),Wu(),fe(),zu(),re(),an(),zt(),my(),e=d.z,s$=e.string().datetime({offset:!0}),o$=u.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href),l$=o$("../package.json"),c$=l$.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)}}(d$=new c.McpServer({name:"atoms-mcp-server",version:c$})),function(e){Pe=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&&Ce.set(e,r),r}}(d$),u$=(e,t,n)=>{if(Ge(e))return d$.registerTool(e,t,n)},p$=i.randomUUID(),u$("atoms_status",{title:"ATOMS MCP Health Check",description:og.atoms_status,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>em(await(async()=>{const e=(e,t)=>async function(e,t,n){try{const e=await(async()=>async function(e,t){Ou.delete(t);const n=await Ru(e,t);let r=null;const{data:a,error:i}=await e.from("organizations").select("id, name").eq("status","suspended");let s;i||(r=(a??[]).map(e=>({org_id:e.id,name:e.name})));try{s=ie(await ae(e,t))}catch{s=null}return{platform_status:n,org_suspended:r,viewer_only:s}}(await Bu(),Yu()))();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"]}:null===e.viewer_only?function(e){return{status:"error",email:e,message:"Your sign-in is valid, but ATOMS could not read your role in your organizations, so tool calls are refused until it can.",next_steps:["Retry in a moment; if it keeps failing, run atoms_status again or contact ATOMS support"]}}(t):!0===e.viewer_only?{status:"viewer_only",email:t,message:X,next_steps:[...te]}:{status:"authenticated",email:t,message:(e.org_suspended??[]).length>0?Eu: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(()=>(ut(),Ke)),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(()=>(Ht(),Rt)),{email:n}=await t(),{invalidateClient:r}=await Promise.resolve().then(()=>(sp(),Vu));return r(),{content:[{type:"text",text:Tu(await e(n,"Token was expired but has been refreshed. You're good to go!"))}]}}catch(e){return e instanceof $t?{content:[{type:"text",text:JSON.stringify({...Mt(),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:Tu(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)}]}}})(),c$)),u$("atoms_list_projects",{title:"List ATOMS Projects",description:og.atoms_list_projects,inputSchema:{offset:d.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:d.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_projects",async e=>{const{listProjectsHandler:t}=await Promise.resolve().then(()=>(Ey(),My));return t(e)})),u$("atoms_list_items",{title:"List ATOMS Items",description:og.atoms_list_items,inputSchema:{project_id:d.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:d.z.enum(G_).optional().describe("Filter by item type"),domain:d.z.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:d.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:d.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:d.z.number().int().min(0).default(0).describe("Pagination offset (default 0)"),after:d.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:d.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:s$.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}},I$("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(Ty(),zy));return t(e)})),u$("atoms_get_item",{title:"Get ATOMS Item Details",description:og.atoms_get_item,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:d.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:s$.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}},I$("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(rw(),Zy));return t(e)})),u$("atoms_list_changes",{title:"List ATOMS Changes",description:M,inputSchema:{project_id:d.z.string().uuid(),since_seq:d.z.number().int().min(0).optional(),limit:d.z.number().int().min(1).max(500).default(100)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_changes",async e=>{const{listChangesHandler:t}=await Promise.resolve().then(()=>(ow(),aw));return t(e)})),u$("atoms_search",{title:"Search ATOMS Items",description:og.atoms_search,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),query:d.z.string().min(1).max(1e3).describe("Search text"),type:d.z.enum(G_).optional().describe("Filter by item type"),asset:d.z.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:d.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:d.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}},I$("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(uw(),cw));return t(e)})),u$("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:og.atoms_semantic_search,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),query:d.z.string().min(1).max(1e3).describe("Natural-language concept query"),type:d.z.enum(G_).optional().describe("Filter by item type"),limit:d.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}},I$("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(fw(),pw));return t(e)})),S$({appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:og.atoms_get_coverage,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),domain:d.z.string().max(64).optional().describe("Filter by domain tag"),level:d.z.string().max(32).optional().describe("Filter by level"),baseline_id:d.z.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:s$.optional().describe("Compute coverage as of this ISO 8601 moment"),offset:d.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:d.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:I$("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(ww(),_w));return t(e)})}),u$("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.\npoints_run counts every point with a verdict, a passed point that needs a rerun included,\nso points_run / points_total is not the share of required runs complete while\nstale is true: the app counts such a point as a run still to do.\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\n${wg}\n\nverified_in: a Release promoted after carry shipped, while the rollout switch\nrelease_carry is on for the project, also counts a pass from an earlier\nRelease at a point that has no run bound to it, when nothing changed after\nthat run (the requirement's content, the test case's content or the link). A\nrequirement that reads verified and not stale through such a pass carries\nverified_in {version, build, run_at, tester}, naming the oldest such run (the\napp shows "Verified in <version>"); every other row has verified_in null. A\ncarried pass that something changed after makes the requirement stale and\nnames its test case under rerun; an earlier failure counts as failing.\n\naccepted_failures is present only while Accept failure is switched on for\nthe project. It lists each test case whose failure an editor or admin\naccepted in the app for this Release with a written reason: the app reads\nthat test as "Failed, accepted for <version>" (label) and never as Verified.\nThe app reads a requirement whose linked tests are each Verified or accepted,\nwith at least one accepted, as "Accepted for <version> (N known anomalies)".\nIts row in requirements keeps the projection's state (failing), so read it\nwith the requirement_ids of accepted_failures. An acceptance holds for this\nRelease only, and a newer run of the test in this Release, or a content\nchange to the test or a linked requirement, reopens it (it is then left out).\nWhile Accept failure is switched on, readiness counts each requirement that\nthe app reads as accepted for this Release under accepted and under no other\ncount, and counts a requirement with an accepted test that does not read\naccepted by its other linked tests, as the app's readiness strip does.\nNo tool accepts a failure: a person does that in the app.\n\ndocument_closures is present only while Close with a document is switched\non for the project, also when release is null. It lists each requirement an\neditor or admin closed in the app with a document named in their own words\n(document_name, link, closed_by, closed_at). The app reads a requirement\nclosed by a document as "Closed by document", covered and done, and a hazard\nwhose controls are each Verified or closed by a document as "Verified via\nmitigation". A requirement closed by a document with a linked test case\nkeeps its row in requirements, with the projection's state and\nclosed_by_document: true (false for a requirement with no standing\nclosure); read a row with closed_by_document true as covered and done.\nA requirement closed by a document with no linked test case has no row in\nrequirements but is still counted in readiness.requirements.\nWhile Close with a document is switched on, readiness counts each\nrequirement whose closure stands, with or without a linked test case,\nunder closed_by_document and under no other count, and leaves its points\nout of points_total and points_run. A closure holds in every Release until it is reopened in the app\nor the requirement's content changes (it is then left out). No tool closes a\nrequirement: a person does that in the app.\n\n${Gg}\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 - include_report (boolean, optional, default false): Also return\n release_report, the Release report of the Release read.\n\nReturns:\n { release: {id, version, status} or null,\n readiness: {requirements, verified, failing, incomplete, not_run, stale,\n points_total, points_run, closed_by_document?}. 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, plus\n closed_by_document while Close with a document is switched on (a row\n closed by a document is counted there instead),\n requirements: [{requirement_id, state, stale, points_total, points_run, verified_in}]\n (each row also closed_by_document? while Close with a document is on),\n rerun: [{requirement_id, test_case_ids}],\n accepted_failures?: [{test_case_id, requirement_ids, label, reason, link,\n accepted_by, accepted_at}],\n document_closures?: [{requirement_id, label, document_name, link,\n closed_by, closed_at}],\n gaps?: [{tc_id, asset, point_key}],\n needs_attention?: [{id, action, reason}],\n release_report?: {release_id, release_version, status, stored_at, sha256,\n report_text} or null }\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:d.z.string().uuid().describe("UUID of the project"),release_id:d.z.string().uuid().optional().describe("Formal Release (baselines row) UUID; defaults to the project's current Release"),include_gaps:d.z.boolean().default(!1).describe("Include the not-run (test x unit x value) points for the Release"),include_report:d.z.boolean().default(!1).describe("Include release_report, the Release report of the Release read (where the Release report is switched on)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_verification_status",async e=>{const{verificationStatusHandler:t}=await Promise.resolve().then(()=>(Iw(),bw));return t(e)})),u$("atoms_get_history",{title:"Get Item Change History",description:og.atoms_get_history,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).describe("Item ID"),limit:d.z.number().int().min(1).max(100).default(20).describe("Max entries (default 20)"),offset:d.z.number().int().min(0).default(0).describe("Revisions to skip from the newest (default 0); call again with offset=meta.next_offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(Nw(),Tw));return t(e)})),S$({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:og.atoms_export_mermaid,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),root_item_id:d.z.string().max(20).optional().describe("Root item ID to start from"),depth:d.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:d.z.boolean().default(!0).describe("Include test case links"),baseline_id:d.z.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:s$.optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:I$("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(Xw(),Qw));return t(e)})}),f$=()=>d.z.string().max(128).optional().describe(x),_$=()=>d.z.enum(["edit","apply_mine"]).describe(S).optional(),h$=()=>d.z.string().min(1).max(600).optional().describe(A),g$=(m$=()=>d.z.union([d.z.string().min(1).max(Ln),d.z.array(d.z.string().min(1).max(Ln)).min(1).max(Un)]).describe(j).optional())(),y$=f$(),u$("atoms_create_item",{title:"Create ATOMS Item",description:og.atoms_create_item,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the target project"),type:d.z.enum(D_).describe(N_),title:d.z.string().min(1).max(500).describe("Item title"),req_type:d.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe($p),body:d.z.string().max(5e4).optional().describe("Rich text body"),summary:d.z.string().max(2e3).optional().describe("Brief summary"),domains:d.z.array(d.z.string().max(64)).max(20).optional().describe("Domain tags"),level:d.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:d.z.array(d.z.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:d.z.record(d.z.string().max(60),d.z.string().max(2e3)).optional().describe("Project-field values keyed by defined field name"),echo:d.z.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens"),idempotency_key:f$()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Cb(),Rb));return t(e)})),w$={steps:d.z.array(d.z.object({id:d.z.string().describe(mm),instruction:d.z.string().describe("What the tester does"),test_data:d.z.string().optional().describe("Optional test data for the step"),expected:d.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. "+mm),params:d.z.array(d.z.object({name:d.z.string().describe("Parameter name; steps reference it as {name}"),unit:d.z.string().optional().describe("Optional unit (e.g. km/h, V, m)"),values:d.z.array(d.z.union([d.z.string(),d.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. "+pm)},u$("atoms_update_item",{title:"Update ATOMS Item",description:og.atoms_update_item,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).optional().describe("Item ID (single form)"),title:d.z.string().min(1).max(500).optional().describe("New title"),body:d.z.string().max(5e4).optional().describe("New body"),summary:d.z.string().max(2e3).optional().describe("New summary"),domains:d.z.array(d.z.string().max(64)).max(20).optional().describe("New domain tags (a function tag is not a domain and is rejected)"),level:d.z.string().max(32).optional().describe("New level"),status:d.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:d.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe($p),fields:d.z.record(d.z.string().max(60),d.z.string().max(2e3)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),...w$,expected_updated_at:s$.optional().describe(`metadata.updated_at value from atoms_get_item; rejects stale writes. ${I}`),base_token:m$(),intent:_$(),asil_confirm_lower:d.z.string().max(8).optional().describe(wp),widget_proof:h$(),echo:d.z.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:d.z.string().max(500).optional().describe(Wh),updates:d.z.array(d.z.object({item_id:d.z.string().min(1).max(20),title:d.z.string().min(1).max(500).optional(),body:d.z.string().max(5e4).optional(),summary:d.z.string().max(2e3).optional(),domains:d.z.array(d.z.string().max(64)).max(20).optional(),level:d.z.string().max(32).optional(),status:d.z.enum(["passed","failed","blocked","not-run"]).optional(),req_type:d.z.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional(),fields:d.z.record(d.z.string().max(60),d.z.string().max(2e3)).optional(),...w$,expected_updated_at:s$.optional(),base_token:m$(),intent:_$(),asil_confirm_lower:d.z.string().max(8).optional().describe(wp)},{errorMap:oy("atoms_update_item","updates")}).strict()).optional().describe("Array form: update many items in one call"),idempotency_key:f$(),continue_on_error:d.z.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(wk(),fk));return t(e)})),u$("atoms_delete_item",{title:"Delete ATOMS Item",description:og.atoms_delete_item,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:d.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}},I$("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(kk(),vk));return t(e)})),u$("atoms_restore_item",{title:"Restore ATOMS Item",description:Ed,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().max(256).describe("ID of the item in Trash"),confirm:d.z.boolean().optional().describe(zd)},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(Mk(),jk));return t(e)})),u$("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|allocated_to|allocated_from), 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 - allocated_to/allocated_from (Function items): links a requirement and a Function (the requirement is\n allocated_to the Function, the Function holds allocated_from). Needs a project with Function items turned on.\n A Function takes only allocation links and parent/child links to other Functions; any other pair is 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?: Change rationale, shown with the change in atoms_get_history and on its History line in the app\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 written in calls of up to 100 operations (removes before adds), each call all or nothing; a batch of more than 100 is NOT one transaction: a failure leaves earlier calls committed and names which operations\n - reason?, idempotency_key? supported\n\nidempotency_key: ${x}`,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),from_id:d.z.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:d.z.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:d.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]).optional().describe("Relationship type"),action:d.z.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:s$.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:s$.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:d.z.boolean().optional().describe("false → lean response"),reason:d.z.string().max(500).optional().describe(Wh),operations:d.z.array(d.z.object({action:d.z.enum(["add","remove"]),from_id:d.z.string().min(1).max(20),to_id:d.z.string().min(1).max(20),type:d.z.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]),expected_from_updated_at:s$.optional(),expected_to_updated_at:s$.optional()},{errorMap:oy("atoms_link_items","operations")}).strict()).optional().describe("Array form: batch relationship ops, DAG-validated as a whole then written in calls of up to 100 ops, each all or nothing (the batch is not one transaction); a failure reports which ops committed."),idempotency_key:f$()},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},I$("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(Lk(),Nk));return t(e)})),S$({appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:og.atoms_bulk_import,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the target project"),items:d.z.array(d.z.object({type:d.z.enum(D_).describe(N_),title:d.z.string().min(1).max(500).describe("Item title"),body:d.z.string().max(5e4).optional().describe("Rich text body"),summary:d.z.string().max(2e3).optional().describe("Brief summary"),domains:d.z.array(d.z.string().max(64)).max(20).optional().describe("Domain tags"),level:d.z.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:d.z.string().max(20).optional().describe("Parent item ID to link")},{errorMap:oy("atoms_bulk_import","items",iy)}).strict()).min(1).max(500).describe("Items to create (1-100; 1-500 on a project that saves one field at a time)"),confirmation_token:d.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),idempotency_key:f$()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:I$("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(Zk(),Gk));return t(e)})}),v$={point:d.z.record(d.z.string(),d.z.union([d.z.string(),d.z.number()])).optional().describe('Matrix point this run executed, e.g. {"speed": 40}'),release_id:d.z.string().uuid().optional().describe("Formal Release to bind this run to (a baseline with a release_version)"),build:d.z.string().optional().describe("Free-text build label"),environment:d.z.string().optional().describe("Structured environment field, distinct from build"),tooling:d.z.string().optional().describe("Structured tooling field, distinct from build"),steps_rev:d.z.string().optional().describe(cm),evidence_url:d.z.string().optional().describe(um),step_results:d.z.array(d.z.object({step_id:d.z.string().describe("Step id from atoms_get_item steps[].id"),status:d.z.enum(["passed","failed","blocked","skipped"]).describe("Per-step status"),actual:d.z.string().optional().describe("Actual-result note"),evidence_url:d.z.string().optional().describe(dm)}).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.")},u$("atoms_record_test_result",{title:"Record Test Result",description:og.atoms_record_test_result,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:d.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:d.z.string().max(500).optional().describe("Reason or comment for this result"),asset:d.z.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new."),date:d.z.string().optional().describe(im),...v$,idempotency_key:y$},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_record_test_result",async(e,t)=>{const{recordTestResultHandler:n}=await Promise.resolve().then(()=>(nj(),Xk));return n({...e,request_id:$$(t)})})),u$("atoms_record_test_results",{title:"Record Test Results (bulk)",description:og.atoms_record_test_results,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:d.z.array(d.z.object({asset:d.z.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:d.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:d.z.string().max(500).optional().describe("Run note"),date:d.z.string().optional().describe("Ignored: runs are stamped with server time. A supplied date is reported in the response warning, never stored."),...v$},{errorMap:oy("atoms_record_test_results","results")}).strict()).min(1).max(100).describe("1 to 100 result entries on this test case"),idempotency_key:y$},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_record_test_results",async(e,t)=>{const{recordTestResultsBulkHandler:n}=await Promise.resolve().then(()=>(ij(),rj));return n({...e,request_id:$$(t)})})),S$({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:og.atoms_trace,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).describe("Starting item ID"),direction:d.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:d.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:d.z.array(d.z.enum(["parent","child","related","verifies","verified_by","mitigated_by","mitigates","affects","affected_by","allocated_to","allocated_from","event_hazard","hazard_events","event_goal","goal_events"])).optional().describe("Filter to specific relationship types"),offset:d.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:d.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:I$("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(lj(),sj));return t(e)})}),u$("atoms_list_assets",{title:"List Project Assets",description:og.atoms_list_assets,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),include_archived:d.z.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(uj(),cj));return t(e)})),b$=()=>d.z.string().regex(/^MD-\d{3,}$/i).describe("The design's MD id, such as MD-001"),k$=()=>d.z.string().max(4194304).describe("The diagram as a Mermaid flowchart (the form atoms_get_model_design returns)"),u$("atoms_list_model_designs",{title:"List Model Designs",description:og.atoms_list_model_designs,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_model_designs",async e=>{const{listModelDesignsHandler:t}=await Promise.resolve().then(()=>(wj(),pj));return t(e)})),u$("atoms_get_model_design",{title:"Get Model Design",description:og.atoms_get_model_design,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),display_id:b$()},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_get_model_design",async e=>{const{getModelDesignHandler:t}=await Promise.resolve().then(()=>(wj(),pj));return t(e)})),u$("atoms_create_model_design",{title:"Create Model Design",description:og.atoms_create_model_design,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(1e3).describe("The design's name, 1 to 200 characters after blanks at either end are removed"),description:d.z.string().max(1e4).optional().describe("What the design shows, at most 5000 characters"),mermaid:k$().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_model_design",async e=>{const{createModelDesignHandler:t}=await Promise.resolve().then(()=>(wj(),pj));return t(e)})),u$("atoms_update_model_design",{title:"Update Model Design",description:og.atoms_update_model_design,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),display_id:b$(),expected_version:d.z.number().int().min(1).describe("The version you read with atoms_get_model_design"),name:d.z.string().min(1).max(1e3).optional().describe("A new name, 1 to 200 characters after blanks at either end are removed"),description:d.z.string().max(1e4).optional().describe("A new description, at most 5000 characters"),mermaid:k$().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_update_model_design",async e=>{const{updateModelDesignHandler:t}=await Promise.resolve().then(()=>(wj(),pj));return t(e)})),u$("atoms_list_variables",{title:"List Project Variables",description:og.atoms_list_variables,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),baseline_id:d.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:s$.optional().describe("Optional ISO timestamp for time-travel reads"),limit:d.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:d.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(Fj(),Ij));return t(e)})),u$("atoms_get_variable",{title:"Get Project Variable",description:og.atoms_get_variable,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),variable_name:d.z.string().min(1).max(64).describe("Variable name"),baseline_id:d.z.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:s$.optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(Fj(),Ij));return t(e)})),u$("atoms_update_variable",{title:"Update Project Variable",description:og.atoms_update_variable,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),variable_name:d.z.string().min(1).max(64).describe("Variable name"),value:d.z.string().max(500).optional().describe("New value"),unit:d.z.string().max(32).optional().describe("Unit abbreviation"),description:d.z.string().max(2e3).optional().describe("Description"),echo:d.z.boolean().optional(),base_token:g$},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(Fj(),Ij));return t(e)})),u$("atoms_create_variable",{title:"Create Project Variable",description:og.atoms_create_variable,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(64).optional().describe("Variable name (single form)"),value:d.z.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:d.z.string().max(32).optional().describe("Unit abbreviation"),description:d.z.string().max(2e3).optional().describe("Description"),echo:d.z.boolean().optional().describe("false → lean response (default true)"),variables:d.z.array(d.z.object({name:d.z.string().min(1).max(64).describe("Variable name"),value:d.z.string().min(1).max(500).describe("Initial value"),unit:d.z.string().max(32).optional().describe("Unit abbreviation"),description:d.z.string().max(2e3).optional().describe("Description")},{errorMap:oy("atoms_create_variable","variables")}).strict()).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:d.z.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(Fj(),Ij));return t(e)})),u$("atoms_delete_variable",{title:"Delete Project Variable",description:og.atoms_delete_variable,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(64).describe("Variable name to delete"),force:d.z.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:d.z.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),base_token:g$},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},I$("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(Fj(),Ij));return t(e)})),u$("atoms_list_domains",{title:"List Project Domains",description:og.atoms_list_domains,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(Qj(),Lj));return t(e)})),u$("atoms_create_domain",{title:"Create Project Domain",description:og.atoms_create_domain,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(Qj(),Lj));return t(e)})),u$("atoms_list_levels",{title:"List Project Levels",description:og.atoms_list_levels,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(Kv(),Ov));return t(e)})),u$("atoms_create_level",{title:"Create Project Level",description:og.atoms_create_level,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(Kv(),Ov));return t(e)})),u$("atoms_delete_level",{title:"Delete Project Level",description:og.atoms_delete_level,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(64).describe("Level name to delete"),confirmation_token:d.z.string().optional().describe("Token from the first (preview) call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},I$("atoms_delete_level",async e=>{const{deleteLevelHandler:t}=await Promise.resolve().then(()=>(Kv(),Ov));return t(e)})),u$("atoms_reorder_levels",{title:"Reorder Project Levels",description:og.atoms_reorder_levels,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),names:d.z.array(d.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}},I$("atoms_reorder_levels",async e=>{const{reorderLevelsHandler:t}=await Promise.resolve().then(()=>(Kv(),Ov));return t(e)})),u$("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 }, meta\n\n${cg("fields")}`,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),offset:d.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:d.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(zb(),_b));return t(e)})),u$("atoms_create_field",{title:"Create Project Field",description:og.atoms_create_field,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:d.z.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:d.z.array(d.z.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:d.z.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization"),appliesTo:d.z.array(d.z.enum(["requirement","test-case","note","table","function"])).max(5).optional().describe("Item types this field shows on (requirement|test-case|note|table|function); omit for all types")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(zb(),_b));return t(e)})),u$("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; they come back only if a field of the same name and a type that takes them is created again (a create of a type that cannot take them is refused, naming the item count).\n\nOnly an org admin of the project\'s organization can delete a field definition.\n\nWhen your organization requires confirmation for this tool, the first call returns { status: "confirmation_required", preview, confirmation_token } and deletes nothing; re-call with the same project_id, name and that confirmation_token to delete.\n\nArgs:\n - project_id (string, UUID): Project containing the field\n - name (string): Field name to delete\n - confirmation_token (string, optional): Token from the preview call, when confirmation is required',inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(60).describe("Field name"),confirmation_token:d.z.string().max(500).optional().describe("Token from the preview call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},I$("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(zb(),_b));return t(e)})),u$("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\nOnly an org admin of the project's organization can reorder field definitions.\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:d.z.string().uuid().describe("UUID of the project"),names:d.z.array(d.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}},I$("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(zb(),_b));return t(e)})),u$("atoms_update_domain",{title:"Update Project Domain",description:og.atoms_update_domain,inputSchema:d.z.object({project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(64).describe("Current domain name"),new_name:d.z.string().min(1).max(64).describe("New domain name"),dry_run:d.z.boolean().optional().describe("Preview impact without applying (default false)")},{errorMap:f_("atoms_update_domain")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(Qj(),Lj));return t(e)})),u$("atoms_delete_domain",{title:"Delete Project Domain",description:og.atoms_delete_domain,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(64).describe("Domain name to delete"),force:d.z.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:d.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}},I$("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(Qj(),Lj));return t(e)})),S$({appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:og.atoms_project_summary,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:I$("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(Zj(),Yj));return t(e)})}),S$({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:og.atoms_browse,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),type:d.z.enum(G_).optional().describe("Filter by item type"),domain:d.z.string().max(64).optional().describe("Filter by domain tag"),level:d.z.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:d.z.string().max(1e3).optional().describe("Full-text search query"),limit:d.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:d.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:I$("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(tx(),Xj));return t(e)})}),u$("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:og.atoms_impact_analysis,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),item_id:d.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:d.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:d.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:d.z.boolean().default(!0).describe("Also list the items that share a {variable} with the item (no relationship needed), each with shared_variables naming every variable it shares. Default true."),offset:d.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:d.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(gx(),nx));return t(e)})),u$("atoms_list_baselines",{title:"List ATOMS Baselines",description:og.atoms_list_baselines,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),limit:d.z.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:d.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(dS(),Xx));return t(e)})),u$("atoms_create_baseline",{title:"Create ATOMS Baseline",description:og.atoms_create_baseline,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),name:d.z.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:d.z.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(dS(),Xx));return t(e)})),u$("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:og.atoms_lock_baseline,inputSchema:{baseline_id:d.z.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(dS(),Xx));return t(e)})),u$("atoms_diff_baselines",{title:"Diff ATOMS Baselines",description:og.atoms_diff_baselines,inputSchema:{baseline_a_id:d.z.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:d.z.string().uuid().describe("UUID of the second (newer) baseline"),detail:d.z.boolean().default(!1).describe("Add a per-field from/to diff object to each modified item (default false)"),limit:d.z.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:d.z.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(dS(),Xx));return t(e)})),u$("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:og.atoms_restore_baseline,inputSchema:{baseline_id:d.z.string().uuid().describe("UUID of the baseline to restore from"),confirm:d.z.boolean().default(!1).describe("Set true to execute; false (default) returns a preview"),source_seq:d.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:d.z.string().uuid().optional().describe($),after_id:d.z.string().min(1).max(64).optional().describe($),confirmation_token:d.z.string().max(500).optional().describe("Token from the preview, when your organization requires confirmation for this tool")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},I$("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(dS(),Xx));return t(e)})),u$("atoms_create_analysis",{title:"Create Analysis (HARA, Risk analysis, FMEA)",description:og.atoms_create_analysis,inputSchema:d.z.object({project_id:d.z.string().uuid().describe("UUID of the target project"),subtype:d.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:d.z.string().min(1).max(500).optional().describe("Analysis title"),source_function_ids:d.z.array(d.z.string().min(1).max(20)).max(50).optional().describe("HARA or risk analysis only: the ids of the Function items to seed rows from (0-50), e.g. FN-001"),source_assets:d.z.array(d.z.string().min(1).max(100)).max(50).optional().describe("Security risk analysis only: the asset names to seed rows from (0-50), kept as text"),source_req_ids:d.z.array(d.z.string().min(1).max(20)).max(50).optional().describe("dfmea only: requirement IDs to seed rows from (0-50)"),revision:d.z.string().min(1).max(32).optional().describe("Revision label (default 1.0)"),variant:d.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:d.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:d.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:d.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:d.z.string().max(1e4).optional().describe("Security risk analysis only: the threat modeling methodology used, e.g. STRIDE."),threat_model_rationale:d.z.string().max(1e4).optional().describe("Security risk analysis only: why that methodology was chosen."),environment_assumptions:d.z.string().max(1e4).optional().describe("Security risk analysis only: assumptions about the operating environment, one per line."),attack_surfaces:d.z.string().max(1e4).optional().describe("Security risk analysis only: interfaces and entry points considered, one per line."),related_documents:d.z.string().max(1e4).optional().describe("Security risk analysis only: where the SBOM, the security testing report and the architecture views live."),idempotency_key:y$,hazard_id:d.z.string().max(20).optional().describe(H_),goal_id:d.z.string().max(20).optional().describe(F_)},{errorMap:f_("atoms_create_analysis")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("atoms_fill_row",{title:"Fill Analysis Row Fields",description:og.atoms_fill_row,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),row_id:d.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:d.z.record(d.z.string().max(64),d.z.union([d.z.string().max(5e4),d.z.number()])).describe("Field name to value map (see description for allowed keys per subtype)"),base_token:g$},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("atoms_get_analysis",{title:"Get Analysis",description:og.atoms_get_analysis,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),analysis_id:d.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),offset:d.z.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:d.z.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:og.atoms_link_mitigation,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),row_id:d.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:d.z.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:d.z.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows (every FMEA); must be omitted for hara rows."),override:d.z.boolean().optional().describe("hara only: apply the row's level (ASIL or Risk) over a conflicting existing value (history-logged)"),control_type:d.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:d.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:!0,idempotentHint:!1,openWorldHint:!1}},I$("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:og.atoms_get_gaps,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),analysis_id:d.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}},I$("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("atoms_propose_rows",{title:"Write Proposed Analysis Rows",description:og.atoms_propose_rows,inputSchema:d.z.object({project_id:d.z.string().uuid().describe("UUID of the project"),analysis_id:d.z.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),rows:d.z.array(d.z.record(d.z.string().max(64),d.z.union([d.z.string().max(5e4),d.z.number()]))).min(1).max(Wo).describe(`The drafted rows (1-${Wo}), each a scheme field name to value map`),source_function_id:d.z.string().min(1).max(20).optional().describe("HARA or risk analysis only: the id of the Function item these rows analyse, e.g. FN-001"),source_req:d.z.string().min(1).max(20).optional().describe("FMEA only: the requirement these rows analyse"),idempotency_key:y$},{errorMap:f_("atoms_propose_rows")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_propose_rows",async e=>{const{proposeRowsHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("atoms_suggest_field",{title:"Write a Suggested Value for One Analysis Field",description:og.atoms_suggest_field,inputSchema:{project_id:d.z.string().uuid().describe("UUID of the project"),row_id:d.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),field:d.z.string().min(1).max(64).describe("The field to fill (a scheme key of this row)"),value:d.z.union([d.z.string().max(5e4),d.z.number()]).describe("The suggested value"),rationale:d.z.string().max(5e4).optional().describe("The evidence behind a suggested rating; written to the scheme's evidence field"),base_token:g$},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_suggest_field",async e=>{const{suggestFieldHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("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:d.z.string().uuid().describe("UUID of the project"),row_id:d.z.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),approver_id:d.z.string().uuid().optional().describe("The approving project member; defaults to the calling user"),note:d.z.string().max(2e3).optional().describe("Optional note captured with the approval"),base_token:g$},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_approve_row",async e=>{const{approveRowHandler:t}=await Promise.resolve().then(()=>(t$(),xS));return t(e)})),u$("atoms_list_scenario_catalogs",{title:"List Operational Scenario Catalogs",description:og.atoms_list_scenario_catalogs,inputSchema:{project_id:d.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),limit:d.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:d.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},I$("atoms_list_scenario_catalogs",async e=>{const{listScenarioCatalogsHandler:t}=await Promise.resolve().then(()=>(j$(),n$));return t(e)})),u$("atoms_mutate_scenario_catalog",{title:"Mutate an Operational Scenario Catalog",description:og.atoms_mutate_scenario_catalog,inputSchema:d.z.object({project_id:d.z.string().uuid().describe("UUID of the project"),op:d.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:d.z.string().min(1).max(64).optional().describe("The catalog id (optional for create_catalog: generated when omitted)"),name:d.z.string().min(1).max(100).optional().describe("The catalog name (create_catalog, rename_catalog)"),entry_id:d.z.string().min(1).max(64).optional().describe("The entry id (caller-generated for add_entry)"),text:d.z.string().min(1).max(100).optional().describe("The entry's operational scenario text"),function_ids:d.z.array(d.z.string().min(1).max(20)).optional().describe("The ids of the Function items this entry applies to (e.g. FN-001); [] = every function, accepted on any project; ids need Function items turned on"),by:d.z.string().min(1).max(200).optional().describe("The accepter's name (accept_catalog)"),on:d.z.string().min(1).max(32).optional().describe("The acceptance date (accept_catalog)")},{errorMap:f_("atoms_mutate_scenario_catalog")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},I$("atoms_mutate_scenario_catalog",async e=>{const{mutateScenarioCatalogHandler:t}=await Promise.resolve().then(()=>(j$(),n$));return t(e)})),Le()}});Ye(),We(),sp();var z$=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"),R$=process.argv.slice(2),T$=R$[0];(async function(){switch(T$){case"login":{const{login:e,loginWithEmail:t}=await Promise.resolve().then(()=>(fp(),op));try{const n=R$.indexOf("--email"),{email:r}=n>0?await t(R$[n+1]):await e();process.stderr.write(`\n [32m✓[0m Authenticated as ${r}\n`),process.stderr.write(" [32m✓[0m Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" [1mNext steps:[0m\n"),process.stderr.write(" [36m$[0m claude mcp add atoms -- npx -y @atoms-tech/atoms-mcp@latest\n"),process.stderr.write("\n Or add to Claude Desktop (Settings → MCP → Edit Config):\n"),process.stderr.write(' [90m{\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp@latest"]\n }\n }\n }[0m\n\n')}catch(e){process.stderr.write(`\n [31m✗[0m ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>(Ht(),Rt));try{const{email:t,user_id:n}=await e();process.stderr.write(`\n [32m✓[0m Logged in as ${t}\n [90mUser ID: ${n}[0m\n\n`)}catch(e){process.stderr.write(`\n [31m✗[0m 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(()=>(ut(),Ke));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${z$.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 login --email [address]\n Sign in with email and password instead of the browser\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 e=!0;try{const{startupAuth:t}=await Promise.resolve().then(()=>(vp(),_p)),n=await t();e=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(e)try{const e=await Bu(),t=Yu();await async function(e,t){try{const n=await qe(e,t);!function(e){Me=e,Oe=Date.now(),Re=!0,Te=!1}(n),Ne(n)}catch(e){Re=!1,Te=e instanceof me,process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). `+(Te?"No tool runs until it loads.\n":"Changes are paused until it loads; RLS still enforces row-level access.\n"))}}(e,t)}catch(e){He(),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 He(),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=Be(),t=Ve(),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:t}=await Promise.resolve().then(()=>(E$(),x$)),n=new p.StdioServerTransport;await t.connect(n);const{startUpdateCheck:r}=await Promise.resolve().then(()=>(wm(),Gp));r(),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}})().catch(e=>{process.stderr.write(`[atoms-mcp] Fatal: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)});
|