@atoms-tech/atoms-mcp 0.67.0 → 0.89.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 +3 -3
- package/dist/apps/src/apps/editor/editor-app.html +18 -18
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import e,{readFile as t,mkdir as n,writeFile as r,unlink as a,stat as i,open as s}from"fs/promises";import{homedir as o}from"os";import l,{join as c}from"path";import{createClient as d}from"@supabase/supabase-js";import{createServer as u}from"http";import p,{randomUUID as m,randomBytes as _,createHash as f}from"crypto";import{fileURLToPath as h,URL as y}from"url";import{promises as g}from"fs";import{z as w}from"zod";import{registerAppTool as v,registerAppResource as b,RESOURCE_MIME_TYPE as j}from"@modelcontextprotocol/ext-apps/server";import{McpServer as k}from"@modelcontextprotocol/sdk/server/mcp.js";import{createRequire as S}from"module";import{StdioServerTransport as A}from"@modelcontextprotocol/sdk/server/stdio.js";var I,x,$,q,E,O,R,M,T,C,D,H,F,N,P,U,z,L=Object.defineProperty,W=Object.getOwnPropertyNames,V=(e,t,n)=>function(){if(n)throw n[0];try{return e&&(t=(0,e[W(e)[0]])(e=0)),t}catch(e){throw n=[e],e}},B=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})};function J(e){return M.get(e)}var G,Q,K,Y,Z,X=V({"src/core/tool-catalog.ts"(){I=new Set(["atoms_status","atoms_list_projects"]),x=new Set(["atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_link_items","atoms_bulk_import","atoms_record_test_result","atoms_record_test_results","atoms_create_variable","atoms_update_variable","atoms_delete_variable","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_create_level","atoms_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"]),$=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_level","atoms_delete_field","atoms_restore_baseline"]),q={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"]}},E=new Set(["atoms_bulk_import"]),O={items:["atoms_list_items","atoms_get_item","atoms_search","atoms_semantic_search","atoms_browse","atoms_get_history","atoms_list_changes","atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_bulk_import"],traceability:["atoms_trace","atoms_link_items","atoms_export_mermaid","atoms_impact_analysis"],coverage:["atoms_get_coverage","atoms_verification_status","atoms_record_test_result","atoms_record_test_results","atoms_project_summary","atoms_list_assets"],variables:["atoms_list_variables","atoms_get_variable","atoms_create_variable","atoms_update_variable","atoms_delete_variable"],domains:["atoms_list_domains","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_list_levels","atoms_create_level","atoms_delete_level","atoms_reorder_levels","atoms_list_fields","atoms_create_field","atoms_delete_field","atoms_reorder_fields"],baselines:["atoms_list_baselines","atoms_create_baseline","atoms_lock_baseline","atoms_diff_baselines","atoms_restore_baseline"],analysis:["atoms_create_analysis","atoms_fill_row","atoms_get_analysis","atoms_link_mitigation","atoms_get_gaps","atoms_propose_rows","atoms_suggest_field","atoms_approve_row","atoms_list_scenario_catalogs","atoms_mutate_scenario_catalog"]},R=Object.keys(O),M=new Map;for(const[e,t]of Object.entries(O))for(const n of t)M.set(n,e);T="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.",C="Retry key: sending the same call again with the same key within 24 hours changes nothing twice.",D="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.",H="Set both from the previous answer when it says complete is false, to continue the same restore.",F="Set by the ATOMS editor card. Do not set this yourself.",N="Ignored on projects that save one field at a time; send base_token instead.",P="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.",U="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.",z="If a call answers code rate_limited, wait retry_after_seconds seconds before calling again. Do not retry sooner."}}),ee=V({"src/core/types.ts"(){G={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:[]},Q={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 te(e,t){if(I.has(t))return{allowed:!0};if(e.lockdown&&!new Set(["atoms_list_items","atoms_get_item","atoms_search","atoms_browse"]).has(t))return{allowed:!1,reason:"lockdown"};if(e.forbidden_tools.includes(t))return{allowed:!1,reason:"forbidden_tool"};if(e.read_only&&x.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&$.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&E.has(t))return{allowed:!1,reason:"block_bulk_import"};const n=J(t);return void 0===n||e.allowed_toolsets.includes(n)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function ne(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 re(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?Y:ne(r),"Contact your org admin to adjust the MCP access policy.","Do not retry this call."],code:n,retryable:!1}}function ae(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:K,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:Z,next_steps:a}:t.some(t=>!function(e,t){return null===e.project_scope||e.project_scope.includes(t)}(e,t))?{status:"error",message:Y,next_steps:a}:null}function ie(){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 se,oe,le,ce,de=V({"src/core/policy.ts"(){X(),K="Your admin set Project scope to No projects for your role. Ask an org admin to change it.",Y="Tool call rejected: project_id is outside your org's MCP project scope.",Z="Tool call rejected: this baseline is not in a project your org's MCP project scope allows, or could not be found."}});async function ue(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 pe(e){return e.length>0&&e.every(e=>"viewer"===e.role)}function me(e){return new Set(e.filter(e=>"viewer"===e.role&&"string"==typeof e.org_id).map(e=>e.org_id))}async function _e(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 he(e,i);s?r.push(s):a++}return{projectIds:r,unresolved:a}}async function fe(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 he(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 ye(){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 ge,we,ve=V({"src/core/viewer-gate.ts"(){se="Viewers cannot use the ATOMS MCP. Ask an org admin for editor access.",oe=["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"],le=["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"],ce=new Set(["atoms_status"])}});function be(e,t=new Map){return{orgs:e,projectOrgs:t}}function je(e,t){return e.orgs.find(e=>e.orgId===t)?.effective??Q}function ke(e){if(0===e.orgs.length)return G;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 Se(e,t){return!!I.has(t)||(0===e.orgs.length?te(G,t).allowed:e.orgs.some(e=>te(e.effective,t).allowed))}function Ae(e,t,n){const r=te(e,t);if(!r.allowed)return{status:"error",message:`Tool ${t} is blocked by org policy.`,next_steps:[ne(r.reason),"Contact your org admin to adjust the MCP access policy."]};const a=function(e,t,n){const r=q[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:[ne(a.reason),"Contact your org admin to adjust the MCP access policy."]}}async function Ie(e,t,n){const r=t.projectOrgs.get(n);if("string"==typeof r)return r;const a=await fe(e,n);return null!==a&&t.projectOrgs.set(n,a),a}function xe(e,t){if(e.orgs.length<=1)return e.orgs[0]?.effective??G;const n=t?e.projectOrgs.get(t):void 0;return"string"==typeof n?je(e,n):ke(e)}var $e,qe,Ee=V({"src/core/org-policy.ts"(){ee(),de(),X(),ve(),ge=["baseline_id","baseline_a_id","baseline_b_id"],we=new Set(["atoms_create_item","atoms_update_item","atoms_bulk_import"])}});function Oe(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?$e.test(e)?e:(qe||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),qe=!0),null):null}function Re(){return process.env.ATOMS_MCP_ORG_ID?.trim()||null}var Me=V({"src/middleware/project-scope.ts"(){$e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qe=!1}});async function Te(e,t,n){return async function(e,t,n=new Map){const r=await Promise.all(e.map(t));return be(e.map((e,t)=>({orgId:e,role:r[t].role,effective:r[t].effective,failedClosed:r[t].effective===Q})),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=Re();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:G};const{data:r,error:a}=await e.rpc("mcp_resolve_policy",{p_user_id:t,p_org_id:n});return a?(process.stderr.write(`[atoms-mcp] mcp_resolve_policy failed (${a.code}): ${a.message}. Falling back to fail-closed policy.\n`),{role:null,is_member:!1,effective:Q}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:G};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,G.read_only),lockdown:s(a.lockdown,G.lockdown),block_destructive:s(a.block_destructive,G.block_destructive),block_bulk_import:s(a.block_bulk_import,G.block_bulk_import),cross_project_browse:s(a.cross_project_browse,G.cross_project_browse),allowed_toolsets:i(a.allowed_toolsets,G.allowed_toolsets),forbidden_tools:i(a.forbidden_tools,G.forbidden_tools),project_scope:l,require_confirmation_for:i(a.require_confirmation_for,G.require_confirmation_for)}}}(r)}(e,t,n),n)}var Ce,De,He,Fe,Ne,Pe,Ue,ze=V({"src/db/policy.ts"(){Ee(),Me(),ee()}});function Le(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 We(){Ne=!1}function Ve(){return Ce}function Be(){const e=Ue,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 Pe){const n=Se(Ce,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 Je(e,t){Ne&&Date.now()-De<=He||(Fe||(Fe=(async()=>{try{const n=await Te(e,t,Ce.projectOrgs);Ce=n,Ne||Le(n),Ne=!0}catch{Ne=!1}De=Date.now(),Be()})().finally(()=>{Fe=null})),await Fe)}var Ge=V({"src/middleware/session-policy.ts"(){Ee(),ze(),Ce=be([]),De=Date.now(),He=3e4,Fe=null,Ne=!0,Pe=new Map,Ue=null}});function Qe(){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)R.includes(e)?n.add(e):r.push(e);return{allowed:n,unknown:r}}function Ke(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function Ye(e){if(Ke()&&x.has(e))return!1;if(I.has(e))return!0;const t=Qe();if(null===t)return!0;const n=J(e);return!!n&&t.allowed.has(n)}var Ze,Xe,et=V({"src/middleware/tool-registry.ts"(){X(),Ee(),Ge()}}),tt={};async function nt(){try{const e=await t(Xe,"utf-8"),n=JSON.parse(e);return n.access_token&&n.refresh_token?n:null}catch{return null}}async function rt(e){await n(Ze,{recursive:!0,mode:448}),await r(Xe,JSON.stringify(e,null,2),{mode:384})}async function at(){const e=await nt();return!!e&&e.expires_at>Date.now()+6e4}function it(e){return e.expires_at>Date.now()+6e4}async function st(){try{await a(Xe)}catch{}}function ot(){return Xe}B(tt,{clearCredentials:()=>st,getCredentialsPath:()=>ot,hasValidCredentials:()=>at,isTokenValid:()=>it,readCredentials:()=>nt,writeCredentials:()=>rt});var lt,ct,dt,ut,pt,mt,_t,ft=V({"src/auth/token-store.ts"(){Ze=c(o(),".atoms"),Xe=c(Ze,"credentials.json")}}),ht={};async function yt(){try{await n(lt,{recursive:!0,mode:448});const e=await s(ct,"wx");try{await e.writeFile(`${process.pid} ${Date.now()}`)}finally{await e.close()}return!0}catch(e){if("EEXIST"===e.code)return!1;throw e}}async function gt(){try{await a(ct)}catch{}}async function wt(){try{const e=await i(ct);return Date.now()-e.mtimeMs>dt}catch{return!1}}async function vt(e,t,n=_t){const r=n.now()+ut;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(pt)}}}B(ht,{runExclusiveAuth:()=>vt});var bt,jt,kt,St=V({"src/auth/lock.ts"(){lt=c(o(),".atoms"),ct=c(lt,".auth.lock"),dt=7e4,ut=12e4,pt=300,mt=e=>new Promise(t=>setTimeout(t,e)),_t={now:Date.now,wait:mt,tryAcquire:yt,release:gt,isStale:wt}}}),At={};function It(e){return e.trim().replace(/\/+$/,"")}B(At,{ATOMS_APP_URL:()=>kt,ATOMS_SUPABASE_ANON_KEY:()=>jt,ATOMS_SUPABASE_URL:()=>bt,resolveUrl:()=>It});var xt,$t,qt,Et,Ot,Rt=V({"src/config.ts"(){bt=It(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),jt=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",kt=process.env.ATOMS_APP_URL??"https://atoms.tech"}});function Mt(e){return e instanceof Et||!!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||!!Ot.statuses.includes(n)||Ot.codedStatuses.includes(n)&&"string"==typeof r&&Ot.codes.includes(r)}(e)}function Tt(){return{status:"error",code:xt,retryable:!0,message:qt,next_steps:[`Wait ${$t} seconds, then retry the same call`,"Do not sign out or log in again: the saved session is still valid"]}}var Ct,Dt,Ht=V({"src/core/auth-outage.ts"(){xt="auth_unavailable",$t=5,qt="ATOMS could not check your sign-in just now. Your session is kept. Try again in a moment.",Et=class extends Error{code=xt;constructor(e){super(`${xt}: ${e}`),this.name="AuthServiceUnavailableError"}},Ot={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"]}}}),Ft={};async function Nt(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=Ut(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await nt();if(t&&t.expires_at>Date.now()+6e4){const e=Ut(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 Pt(){const e=await Nt();if(e)return e;const t=await nt();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp@latest login' to connect your ATOMS account.");return vt(async()=>{const e=await Nt();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=d(bt,jt,{global:{fetch:Dt}});let n=await t.auth.refreshSession({refresh_token:e.refresh_token});if(n.error||!n.data.session){const r=await nt();if(r&&r.expires_at>Date.now()+6e4){const e=Ut(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(Mt(n.error))throw new Et(`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 r=n.data.session;return await rt({access_token:r.access_token,refresh_token:r.refresh_token,expires_at:Date.now()+1e3*(r.expires_in??3600),user_email:r.user?.email}),{access_token:r.access_token,refresh_token:r.refresh_token,user_id:r.user?.id??"",email:r.user?.email??""}}(t))}function Ut(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}B(Ft,{AUTH_CALL_TIMEOUT_MS:()=>Ct,getValidToken:()=>Pt,readValidToken:()=>Nt});var zt,Lt=V({"src/auth/refresh.ts"(){ft(),St(),Rt(),Ht(),Ct=1e4,Dt=async(e,t)=>{const n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Auth did not answer within ${Ct} ms`)),Ct),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 Wt(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?zt:t:zt}function Vt(e){const t=Wt(e);return"cursor"===t?"mcp_cursor":"copilot"===t?"mcp_copilot":"mcp_claude"}var Bt,Jt,Gt,Qt,Kt,Yt=V({"src/core/client-identity.ts"(){zt="claude_desktop"}});function Zt(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 Xt(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 en(e){return"string"==typeof e&&e.includes(Gt)}function tn(e){return"string"==typeof e&&e.includes(Qt)}function nn(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 rn(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]}var an,sn,on,ln,cn,dn,un,pn,mn,_n,fn,hn,yn,gn,wn,vn,bn,jn,kn,Sn,An,In,xn,$n,qn,En,On,Rn,Mn,Tn,Cn,Dn,Hn,Fn,Nn,Pn,Un,zn=V({"src/core/errors.ts"(){Bt=[/^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 /],Jt=class extends Error{},Gt="rollout_switched:multiuser_saving: This project still saves whole items. Reload, then save again.",Qt="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.",Kt=10}});function Ln(e){return/rollout_switched:multiuser_saving/i.test(e)}function Wn(){return{status:"error",message:sn,next_steps:[on],code:"rollout_switched",retryable:!1}}function Vn(e){return/project_in_trash/i.test(e)||e===cn}function Bn(){return{status:"error",message:ln,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 Jn(e){return e===un||/not a member of this project's organization/i.test(e)}function Gn(){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 Qn(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 Kn(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 Yn(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&&Zt(t.message)?new Error(t.message):t&&"42501"!==t.code||!mn.test(e)?new Error(`Project '${e}' not found`):new Error(un)}function Zn(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 Xn(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 er(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":er(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)}:${er(t[e])}`).join(",")}}`}return"null"}async function tr(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 nr(e,t,n="item"){return e&&"object"==typeof e?"variable"===n?"variables"!==t[0]?null:t.length<=2?e:rr(e[t[2]],t.slice(3)):0===t.length?e.data??null:vn.has(t[0])?1===t.length?e[t[0]]??null:null:rr(e.data,t):null}function rr(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 ar(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function ir(e,t){return e.length<=t.length&&e.every((e,n)=>e===t[n])}function sr(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=>ir(e,t)));if(0===t.length||bn.has(t[0]))return!1;switch(r){case"item":case"all":return!0;case"core":return hn.some(e=>ar(e,t));case"analysis":return ar(t,["title"])||ar(t,["body"])||("analysis_props"===t[0]||"relationships"===t[0])&&t.length>=2;case"paths":return(a??[]).some(e=>ir(e,t))}return!1}async function or(e,t,n="item"){let r;if("string"!=typeof t)r=t.paths.map(t=>nr(e,t,n));else if("core"===t||"analysis"===t){const a="core"===t?hn:yn;r=Object.fromEntries(a.map(t=>[JSON.stringify(t),nr(e,t,n)]))}else r=e??null;return(await tr(er(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 cr(e,t,n="item"){return lr(e.id,await or(e.fields_snapshot,t,n),t)}function dr(e){if("string"!=typeof e||0===e.length||e.length>_n)return null;const t=wn.exec(e);if(!t)return null;const n=t[1].toLowerCase(),r=t[2].toLowerCase(),a=t[3];if(gn.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 ur(e){return"variable"===e?{table:"variable_revisions",idCol:"variable_id"}:{table:"item_revisions",idCol:"item_id"}}function pr(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 mr(e,t){return new Error(String(e?.message??`${t} failed`))}async function _r(e,t,n,r="item"){const a=new Map,i=[...new Set(n)];if(0===i.length)return a;const{table:s,idCol:o}=ur(r),{data:l,error:c}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in(o,i).is("valid_to",null).is("deleted_at",null);if(c)throw mr(c,`${s} read`);for(const e of l??[]){const t=pr(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 fr(e,t,n,r="item"){const a=new Map,i=[...new Set(n)];if(0===i.length)return a;const{table:s,idCol:o}=ur(r),{data:l,error:c}=await e.from(s).select(`id, ${o}, revision_number, valid_from, fields_snapshot, diff_summary`).eq("project_id",t).in("id",i);if(c)throw mr(c,`${s} read`);for(const e of l??[]){const t=pr(e,o);a.set(t.id,t)}return a}async function hr(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 mr(r,"changes_since");const a=n?.head_seq;return"number"==typeof a?a:Number(a??0)}async function yr(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 mr(o,"fresh_typing_notes");for(const e of s??[]){const t=a.get(e.item_id)??[];t.push({path:e.path,field_label:gr(e.path,r),person:{name:e.user_name??"Someone",kind:"person"}}),a.set(e.item_id,t)}return a}function gr(e,t){if(!e||0===e.length)return"Item";const n=jn[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 wr(e){return JSON.stringify(e)}async function vr(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=dr(n);t?(e.parsed.push(t),r.push(t.revisionId)):e.bad=!0}n.set(t.itemId,e)}const a=await fr(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 or(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)sr(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(wr(n),{base:nr(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 _r(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",...br(t,e.req),path:e.path,seq:null,current:r?nr(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",...br(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 br(e,t){return"variable"===e?{item_id:null,name:t.name??t.itemId,variable_id:t.itemId}:{item_id:t.itemId}}function jr(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 kr(e){return e?"agent"===e.kind?e.label??e.name??null:e.name??null:null}async function Sr(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??""}|${wr(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(kn.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:kr(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??""}|${wr(c??[])}`),u={item_id:l.item_id??null,...null===l.item_id&&l.name?{name:l.name}:{},path:c,field_label:gr(c,e.labels),status:l.status,reason:l.reason??("skipped_typing"===l.status?"typing":"locked"===l.status?"item_locked":null)};d&&"value"in d?u.your_value=d.value:"sent"in l&&(u.your_value=l.sent);const p=l.item_id?r.get(l.item_id):void 0,m=l.item_id&&"skipped"===l.status?e.openRevisions?.get(l.item_id):void 0;let _=null;"conflict"===l.status?("current"in l&&(u.theirs_value=l.current),l.current_revision_id&&(_={revId:l.current_revision_id,rev:e.revisionsById?.get(l.current_revision_id),value:l.current??null})):m&&c?(u.theirs_value=nr(m.fields_snapshot,c),_={revId:m.id,rev:m,value:u.theirs_value}):"current"in l&&"deleted"!==l.status&&(u.theirs_value=l.current),"base"in l?u.base_value=l.base:d&&"base"in d&&(u.base_value=d.base);const f=l.current_author??p?.change?.author??null;f&&(u.changed_by={kind:f.kind,name:kr(f)});const h=l.current_at??p?.change?.at??null;(f||h)&&(u.changed_at=h);const y=l.current_seq??p?.change?.seq;if(null!=y&&(u.seq=y),("skipped_typing"===l.status||"skipped"===l.status&&"typing"===l.reason)&&(u.typing={name:l.typing?.name??null,renewed_at:l.typing?.renewed_at??null}),("locked"===l.status||"skipped"===l.status&&"locked"===l.reason)&&(u.locked_by=l.locked_by?{name:l.locked_by.name??null}:null),l.target&&(u.target=l.target),"boolean"==typeof l.restorable&&(u.restorable=l.restorable),l.replayed&&(u.replayed=!0),_&&c){const e=`${u.item_id??u.name??""}|${_.revId}`,t=i.get(e)??{revId:_.revId,rev:_.rev,entries:[]};t.entries.push({entry:u,value:_.value}),i.set(e,t)}s.push({entry:u,answer:l})}for(const e of i.values()){const t=new Set,n=[],r=[];for(const{entry:a,value:i}of e.entries){const s=wr(a.path);t.has(s)||(t.add(s),n.push(a.path),r.push(e.rev?nr(e.rev.fields_snapshot,a.path):i))}const a=(await tr(er(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=Ir(e,t),a.not_applied.push($r(e));return a.replayed=e.answers.length>0&&e.answers.every(e=>!0===e.replayed),a}function Ar(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 Ir(e,t){const n=Ar(e),r=e.field_label,a=e.changed_by?.name??"Someone",i=e.changed_at?` at ${e.changed_at}`:"",s=e.reason??"",o=e.locked_by&&e.locked_by.name?`is locked to ${e.locked_by.name}`:"is locked for everyone";switch(e.status){case"conflict":return"no_base"===s?t?.no_revision?`${n} ${r} not saved: ${n} has no saved revision yet; save it once in ATOMS, then try again.`:`${n} ${r} not saved: no base_token covers it. Its current value is in theirs_value; send your change again with this entry's base_token. If you are in an ATOMS editor card, close the card and open ${n} again.`:"bad_token"===s?t?.no_revision?`${n} ${r} not saved: ${n} has no saved revision yet; save it once in ATOMS, then try again.`:`${n} ${r} not saved: the base_token you sent is not a token for ${n}. Its current value is in theirs_value; send your change again with this entry's base_token.`:`${n} ${r} not saved: ${a} changed it${i} after you read it.`;case"skipped_typing":return`${n} ${r} skipped: ${e.typing?.name??"Someone"} is typing in it.`;case"locked":return`${n} ${r} skipped: ${n} ${o}, and this org has Agents respect item locks on.`;case"deleted":return"in_trash"===s?`${n} ${r} not saved: ${n} is in the Trash.`:"row_deleted"===s||"column_deleted"===s?`${n} ${r} not saved: that row was deleted.`:"field_deleted"===s?`${n} ${r} not saved: that field was removed from the project.`:`${n} ${r} not saved: ${n} no longer exists.`;case"forbidden":return s.startsWith("mcp_policy_")?`${n} ${r} not saved: your org's MCP Access Policy does not allow this change.`:"change_open_by_other"===s?`${n} ${r} not saved: ${kr(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`${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 xr(e){if("string"==typeof e)return e.length;const t=JSON.stringify(e);return void 0===t?0:t.length}function $r(e){const t={...e},n=[];for(const e of Mn)e in t&&xr(t[e])>Sn&&(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 ${Sn} characters and was left out. Read it with atoms_get_item (${Ar(e)}), then send your change again.`),t}function qr(e){return"string"==typeof e?`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`:Array.isArray(e)?e.map(qr):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,qr(t)])):e}function Er(e){const t=new TextEncoder,n=t.encode(JSON.stringify(e)??"").length,r=t.encode(JSON.stringify(qr(e),null,2)??"").length;return Math.max(n,r)}function Or(e,t=Er){if(t(e)<=An)return e;const n=e.not_applied.map(e=>{const t={...e};let n=!1;for(const e of Mn)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)<=An)return r;const a=n.map(e=>{const{message:t,hint:n,...r}=e;return r});if(r={...r,not_applied:a},t(r)<=An)return r;const{applied:i,...s}=r,o={...s,applied_count:i?.length??r.applied_count??0},l=e=>{const t=a.slice(e),n=[];for(const e of t){const t=e.item_id??e.name;t&&!n.includes(t)&&n.length<xn&&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))<=An?c=e:d=e-1}return l(c)}function Rr(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??Ir(a),i=t-r-1>0?` And ${t-r-1} more.`:"";if([...n,e].join(" ").length+i.length>In)break;n.push(e),r+=1}r<t&&n.push(`And ${t-r} more.`);const a=n.join(" ");return a.length<=In?a:a.slice(0,In)}function Mr(e){const t=t=>e.not_applied.some(t),n=[$n];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(qn),t(e=>"skipped_typing"===e.status||"skipped"===e.status&&"typing"===e.reason)&&n.push(En),t(e=>"locked"===e.status||"skipped"===e.status&&"locked"===e.reason)&&n.push(On),t(e=>"conflict"===e.status&&("no_base"===e.reason||"bad_token"===e.reason))&&n.push(Rn),n}function Tr(e,t,n){const r=e.applied.length+e.captured.length;return{isError:0===r,result:Or({...t??{},status:r>0?"partial":"error",code:"not_all_applied",retryable:!1,message:Rr(e),next_steps:Mr(e),applied:e.applied,not_applied:e.not_applied,seq:e.seq,...e.merged_fields.length>0?{merged_fields:e.merged_fields}:{}},n)}}function Cr(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 Dr(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)}`}(Tn,e.map(String).join("\n"))}function Hr(){return crypto.randomUUID()}function Fr(e){return[e.userId,e.projectId,"create_item",e.content,e.k,e.sessionId]}function Nr(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 Pr(e){return[e.userId,e.projectId,"append_run",e.itemId,e.runHash,e.k,e.effectiveKey]}function Ur(e){return[e.userId,e.projectId,e.what,e.name]}function zr(e){return"atoms_create_item"===e||"atoms_bulk_import"===e?"item":e}function Lr(e){const t=new Map;return e.map(e=>{const n=t.get(e)??0;return t.set(e,n+1),n})}function Wr(e){return"string"==typeof e?e.replace(/<\s*\/?\s*user_content\s*>/gi,""):Array.isArray(e)?e.map(Wr):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Wr(t)])):e}function Vr(e){return er(Wr({type:e.type,title:e.title,body:e.body??null,summary:e.summary??null,req_type:e.req_type??null,domains:Cn(e.domains),level:e.level??null,parent_ids:Cn(e.parent_ids),fields:e.fields??{}}))}function Br(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 Jr(e,t,n){const r=[];let a=[],i=0;for(const s of e)a.length>0&&(i+1>t||a.length+s.ops.length>n)&&(r.push(a),a=[],i=0),a.push(...s.ops),i+=1;return a.length>0&&r.push(a),r.map(e=>e.sort((e,t)=>e.index-t.index).map(e=>e.op))}function Gr(e){return e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message:e)}function Qr(e){return/too_many_items/.test(Gr(e))}function Kr(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 Yr(e,t){try{const{data:n,error:r}=await e.rpc("rollout_state",{p_project_id:t});return r?null:!!n&&"object"==typeof n&&!0===n.multiuser_saving}catch{return null}}function Zr(){return{status:"error",message:Fn,next_steps:["Send the same call again in a moment"],code:"rollout_state_unreadable",retryable:!0}}function Xr(e,t){const n=Gr(t);return"ops"===e&&en(n)?"main":"main"===e&&(tn(n)||n.includes(an))?"ops":null}async function ea(e,t){try{return await t(e)}catch(n){const r=Xr(e,n);if(!r)throw n;return t(r)}}function ta(e,t,n){const r=(t??"").trim().split(/\s+/)[0]??"";return`${e} for ${r?r.slice(0,40):((n??"").split("@")[0]||"someone").slice(0,40)}`}async function na(e,t,n){const r=new Map,a=[...new Set(n.filter(e=>"string"==typeof e&&e.length>0))];for(let n=0;n<a.length;n+=Un){const{data:i,error:s}=await e.rpc("mcp_op_answers",{p_project_id:t,p_op_ids:a.slice(n,n+Un)});if(s)throw mr(s,"mcp_op_answers");for(const e of i?.answers??[])e&&e.op_id&&r.set(e.op_id,{...e,replayed:!0})}return r}async function ra(e,t,n){const r=n.filter(e=>"invalid"===e.status&&"op_id_reused"===e.reason).map(e=>e.op_id);if(0===r.length)return n.map(e=>({...e}));const a=await na(e,t,r);return n.map(e=>{if("invalid"!==e.status||"op_id_reused"!==e.reason)return{...e};const t=a.get(e.op_id);return t?{...t,replayed:!0}:{...e,message:Nn}})}function aa(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 ia,sa,oa,la,ca,da=V({"src/core/agent-saving.ts"(){Yt(),zn(),X(),an="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.",sn="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: ",""),on="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.",ln="This project is in the Trash. Nothing was saved. A project admin can restore it in ATOMS, then try again.",cn="PROJECT_IN_TRASH",dn="You no longer have access to this project. Ask an admin of its organization to add you back.",un="PROJECT_ACCESS_LOST",pn="it is approved under change control, so it cannot be moved to Trash",mn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,_n=2e3,fn=20,hn=[["title"],["summary"],["body"],["req_type"],["status"],["tags","domains"],["tags","level"]],yn=[["title"],["body"],["analysis_props"],["relationships"]],gn=new Set(["item","all","analysis","core","variable"]),wn=/^([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,vn=new Set(["title","type","approver_user_id","requires_impacted_approval"]),bn=new Set(["variables","taxonomy","settings"]),jn={'["title"]':"Title",'["summary"]':"Summary",'["body"]':"Body",'["req_type"]':"Type",'["type"]':"Type",'["status"]':"Status",'["tags","level"]':"Level",'["tags","domains"]':"Domains",'["asil_confirm_lower"]':"ASIL"},kn=new Set(["applied","noop","replaced"]),Sn=4e3,An=65536,In=600,xn=200,$n="Changes under applied are saved; do not send them again. Tell the person which changes were not saved and why.",qn="For each conflict: merge theirs_value with your change, then call the tool again with that entry's base_token.",En="For a field someone is typing in: offer to try again in a minute.",On="For a locked item: ask the person it is locked to, or an admin, to unlock it.",Rn="For a change with no base: read the item with atoms_get_item, or use the entry's base_token, then send it again.",Mn=["your_value","theirs_value","base_value"],Tn="0b7e5c1a-3d2f-4e6b-9a8c-1f2e3d4c5b6a",Cn=e=>[...new Set((e??[]).map(e=>String(Wr(e))))].sort(),Dn=50,Hn=500,Fn="Could not read how this project saves, so nothing was saved. Try again.",Nn="idempotency_key already used for a different change; use a new key.",Pn="Already created by an earlier identical call. Nothing new was created. To create another copy, call again with a new idempotency_key.",Un=500}});function ua(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 pa(e){return{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken.replace(/^Bearer\s+/i,"")}`,...e.anonKey?{apikey:e.anonKey}:{}}}function ma(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&&ca.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?function(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&&ia.includes(e))&&t.add(n.item_id)}return[...t]}(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);!function(e){const t=globalThis.EdgeRuntime;try{t?.waitUntil?.(e)}catch{}}(async function(e,t,n){try{if(!e.supabaseUrl||!e.accessToken)return;const r=e.fetch??fetch,a=[...new Set(n)],i=[];for(let n=0;n<a.length;n+=la){const s=a.slice(n,n+la).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(s)})`,l=await r(o,{method:"GET",headers:pa(e)});if(!l.ok){console.error(`[embed-on-save] item read failed (${l.status})`);continue}const c=await l.json();Array.isArray(c)&&i.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:ua(e.data??{})})).filter(e=>e.text.trim().length>=3),i=[];for(let e=0;e<a.length;e+=sa)i.push(a.slice(e,e+sa));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:pa(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(oa,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,i)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}(n,a,r))}}}catch(e){console.error("[embed-on-save] not queued:",e instanceof Error?e.message:e)}return a}}var _a,fa,ha,ya,ga,wa,va=V({"src/core/embed-on-save.ts"(){ia=["title","body","summary","tags","type"],sa=5,oa=3,la=100,ca=new Set(["save_item_with_revision","bulk_save_items_with_revisions","apply_item_ops"])}});function ba(e){const t=_a[e];return[...t.top,...t.other]}async function ja(e,t,n){const r=function(e){const t=ba(e);return ya.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 ka(e){return function(e){return"medical"!==(e.industry??"automotive")&&!e.holdsAnalysisOutsideAutomotive}(e)?e.hazardGoalItemsOn&&e.multiuserSavingOn?null:wa:ga}var Sa,Aa,Ia,xa,$a,qa=V({"src/core/analysis-industry.ts"(){_a={automotive:{top:["iso26262","design"],other:[]},medical:{top:["iso14971","tir57","process"],other:["software","use"]}},fa={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"},ha={automotive:"Automotive (ISO 26262)",medical:"Medical device (ISO 14971)"},ya=Object.keys(fa),ga="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.",wa="rollout_switched:hazard_goal_items"}});function Ea(e){const t=Sa.exec(e);return t?t[1]:null}function Oa(e){return e.includes("function_is_item")}function Ra(){return{status:"error",code:"function_is_item",retryable:!1,message:xa,next_steps:['Create a Function with atoms_create_item and type "function", or edit the Function item itself',"Do not retry this call"]}}function Ma(){return{status:"error",code:"rollout_switched",key:"hazard_goal_items",retryable:!1,message:$a,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 Ta(e){return e.includes("hazard_goal_not_automotive")}function Ca(){return{status:"error",code:"hazard_goal_not_automotive",retryable:!1,message:`Validation error: ${ga} This change was not saved.`,next_steps:["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)","Do not retry this call"]}}var Da,Ha,Fa,Na,Pa,Ua,za,La=V({"src/core/rollout-errors.ts"(){qa(),Sa=/rollout_switched:([a-z][a-z0-9_]{2,62})/,Aa="This project's saving rules just changed. Read the item again, then retry your change.",Ia="Function items are not on for this project yet, so a Function item cannot be created here. This change was not saved.",xa="Validation error: this project's Functions are items now, so its function tag list no longer changes. This change was not saved.",$a="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 Wa(e,t){const n=Fa.indexOf(String(e??"")),r=Fa.indexOf(String(t??""));return n<0||r<0?Da:Na[n][r]}function Va(e){return"Moderate"===e||"High"===e||"Very High"===e}var Ba,Ja,Ga,Qa=V({"src/core/securityScheme.ts"(){Da="-",Ha=["Very Low","Low","Moderate","High","Very High"],Fa=["1","2","3","4","5"],Na=[["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"]],Pa={"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"},Ua=[{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"}],za={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 Ka(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 Ya(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. ${Ga}`}function Za(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 Xa(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function ei(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 ti(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}=ei(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 ni,ri,ai,ii,si,oi,li,ci,di,ui,pi,mi,_i,fi,hi,yi,gi,wi,vi,bi,ji,ki,Si,Ai,Ii,xi,$i,qi,Ei,Oi,Ri,Mi,Ti,Ci,Di,Hi,Fi,Ni,Pi,Ui,zi,Li,Wi,Vi,Bi,Ji,Gi,Qi,Ki,Yi,Zi,Xi,es,ts,ns=V({"src/core/acceptance.ts"(){Ba=["acceptance_state","accepted_by","accepted_at","acceptance_note","open_gaps_at_acceptance"],Ja=["prev_accepted_by","prev_accepted_at","accepted_snapshot_id","accepted_snapshot_name"],Ga="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 rs(e){return t=e?.industry,"automotive"===t||"medical"===t?e.industry:null;var t}function as(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 is(e){return ri[e]}function ss(e){return ai.some(t=>t.id===e)||function(e){return Ua.some(t=>t.id===e)}(e)}function os(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:si,source:"fallback"}}function ls(e){const t=(e??"").trim().toLowerCase();return"sub-system"===t?"subsystem":t}function cs(e,t){const n=os(e),r=os(t);return ls(n.level)===ls(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 ds(e,t,n){if("title"!==t&&("dfmea"!==e||"failure_mode"!==t)||n.length<=li)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 ${li}. Shorten it to ${li} or fewer.`}function us(e){const t=(e.failure_mode??"").trim()||(e.hazard??"").trim()||"";if(t.length<=li)return t;const n=t.slice(0,li);return/[\uD800-\uDBFF]$/.test(n)?n.slice(0,-1):n}function ps(e){return"hazard_iso14971"===e?ki:"security_tir57"===e?xi:[]}function ms(e){return"security_tir57"===e?Ha:Si}function _s(e){return String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e)}function fs(e){const t=e??{};return{intended_use:String(t.intended_use??"").trim(),foreseeable_misuse:_s(t.foreseeable_misuse),safety_characteristics:_s(t.safety_characteristics)}}function hs(e,t=Si){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:Ai.includes(a)?a:"",safety_rationale:String(n.software_safety_rationale??"").trim()}}function ys(e){return""!==fs(e).intended_use}function gs(e,t){const n=ps(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 ws(e,t,n){return`Invalid ${e} value ${JSON.stringify(t)}. Allowed: ${n.join(", ")}`}function vs(e){const t=e?.analysis_props;return null===t||"object"!=typeof t||Array.isArray(t)?"legacy":t.event_model===Ri?"hazard_goal":"legacy"}function bs(e,t){return"hara_iso26262"===e&&"hazard_goal"===t?Mi:qi[e]}function js(e){return"risk_analysis"===e||"hazard_analysis"===e?["iso14971"]:"security_risk"===e?["tir57"]:ni[Ti[e]]}function ks(e){return Object.entries(Wi[e]).map(([e,t])=>({key:e,label:t}))}function Ss(e){return Object.entries(function(e){return"hara_iso26262"===e?Ni:"dfmea_rpn"===e?zi:"hazard_iso14971"===e?Ui:"security_tir57"===e?za:Li}(e)).map(([e,t])=>({key:e,text:t}))}function As(e){return"hazard_iso14971"===e?hi:"security_tir57"===e?Pa:null}function Is(e,t){const n=As(e);return n?n[t]??null:null}function xs(e){return(e??"").trim().toLowerCase()}function $s(e,t){const n=xs(e);if(!n)return null;for(const e of t)if(xs(e)===n)return e;return null}function qs(e){const t=e?.severity||"",n=e?.exposure||"",r=e?.controllability||"";return t&&n&&r?"S0"===t||"E0"===n||"C0"===r?"QM":ui[`${t}-${n}-${r}`]||ci:ci}function Es(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)?ci:String(t*n*r)}function Os(e,t,n){const r=String(e??""),a=String(t??""),i=String(n??"");if(mi.indexOf(r)<0||mi.indexOf(a)<0||mi.indexOf(i)<0)return ci;const s=_i[`${a}-${i}`];return s&&fi[`${s}-${r}`]||ci}function Rs(e){return Os(e?.severity,e?.p1,e?.p2)}function Ms(e){return Os(e?.residual_s,e?.residual_p1,e?.residual_p2)}function Ts(e){return Wa(e?.severity,e?.exploitability)}function Cs(e){return Wa(e?.residual_s,e?.residual_e)}function Ds(e,t){return"hara_iso26262"===e?qs(t):"hazard_iso14971"===e?Rs(t):"security_tir57"===e?Ts(t):"fmea_software"===e?function(e){return Es({...e??{},occurrence:yi})}(t):Es(t)}function Hs(e,t,n,r){if(n)return!1;if("hara_iso26262"===e&&r?.cited&&r.satisfied)return!1;if("hara_iso26262"===e){const e=qs(t);return"C"===e||"D"===e}if("hazard_iso14971"===e)return"High"===Rs(t);if("security_tir57"===e){const e=Ts(t);return"High"===e||"Very High"===e}const a=parseInt(Ds(e,t),10);return!Number.isNaN(a)&&a>=200}function Fs(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 Ns(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 Ps(e){return"fmea_software"===e?{field:"occurrence",value:yi}:null}function Us(e){const t=Ps(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 zs(e){return Gi[e]}function Ls(e){return"security_tir57"===e?Ua:function(e){return"hazard_iso14971"===e||"fmea_process"===e||"fmea_software"===e||"fmea_use"===e}(e)?ai:[]}function Ws(e){return Ls(e).map((e,t)=>({...e,precedence:t+1}))}function Vs(e){return"hara_iso26262"===e||"hazard_iso14971"===e||"security_tir57"===e}function Bs(e,t){return`${e} is not a ${Gi[t].mitigating_requirement}: a mitigation target must be a requirement of req_type '${ii}'. Create or convert one, then link it.`}function Js(e){return`control_type applies to the medical schemes only (ISO 14971 clause 7); ${Gi[e].parent} links carry none, so omit it.`}function Gs(e){return"security_tir57"===e?`control_type is required for a security control link (FDA Appendix 1). Choose one of: ${Ua.map(e=>`${e.id} (${e.label})`).join(", ")}.`:`control_type is required for a risk control link (ISO 14971 clause 7). Choose one of: ${ai.map(e=>`${e.id} (${e.label})`).join(", ")}.`}function Qs(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 Ks(e){const t=parseInt(e,10);return!Number.isNaN(t)&&t>=100}function Ys(e){return"hara_iso26262"===e?Yi:"hazard_iso14971"===e?Zi:"security_tir57"===e?es:Xi}function Zs(e){return!0===e.approved&&(e.approved=!1,e.approved_at=null,e.approved_by=null,e.approved_note="",!0)}function Xs(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function eo(e,t,n=xs){const r=new Set(t.map(n).filter(e=>e.length>0));return e.filter(e=>r.has(n(e)))}function to(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 no,ro,ao,io=V({"src/core/analysis.ts"(){Qa(),Qa(),ns(),ni={hara:["iso26262","iso14971","tir57"],dfmea:["design","process","software","use"]},ri={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"},ai=[{id:"inherent",label:"Inherent design",abbr:"ID"},{id:"protective",label:"Protective measure",abbr:"PM"},{id:"information",label:"Information for safety",abbr:"IFS"}],ii="safety",si="L1",oi=8,li=500,ci="-",di=["prevention","detection","mitigation"],ui={"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"},_i={"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"},fi={"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"},hi={Low:"Acceptable",Medium:"Acceptable with justification",High:"Not acceptable"},yi="10",gi={hara_iso26262:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea_rpn:{severity:pi=["1","2","3","4","5","6","7","8","9","10"],occurrence:pi,detection:pi},hazard_iso14971:{severity:mi=["1","2","3","4","5"],p1:mi,p2:mi,residual_s:mi,residual_p1:mi,residual_p2:mi},fmea_process:{severity:pi,occurrence:pi,detection:pi},fmea_software:{severity:pi,detection:pi},fmea_use:{severity:pi,occurrence:pi,detection:pi},security_tir57:{severity:[...Fa],exploitability:[...Fa],residual_s:[...Fa],residual_e:[...Fa]}},wi={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"]},vi={threat_event:"failure_mode",vulnerability:"operating_scenario",impact:"effect",harm:"hazard",security_control:"safety_goal"},bi=["intended_use","foreseeable_misuse","safety_characteristics"],ji=["overall_residual_risk","overall_residual_rationale","software_safety_class","software_safety_rationale"],ki=[...bi,...ji],Si=["Low","Medium","High"],Ai=["A","B","C"],Ii=["threat_model_method","threat_model_rationale","environment_assumptions","attack_surfaces","related_documents","overall_residual_risk","overall_residual_rationale"],xi=[...Ii,"lifecycle_sources"],$i={hara:"safety-goal",dfmea:"failure-mode"},qi={hara_iso26262:"SG",dfmea_rpn:"FM",hazard_iso14971:"RSK",fmea_process:"PF",fmea_software:"FM",fmea_use:"FM",security_tir57:"CYB"},Ei={hara_iso26262:"HARA",dfmea_rpn:"DFMEA",hazard_iso14971:"RA",fmea_process:"PFMEA",fmea_software:"SFMEA",fmea_use:"UFMEA",security_tir57:"SEC"},Oi=["HA"],Array.from(new Set([...Object.values(Ei),...Object.values(qi),...Oi])).sort(),Ri="hazard_goal",Mi="HE",Ti={hara:"hara",dfmea:"dfmea",risk_analysis:"hara",fmea:"dfmea",hazard_analysis:"hara",security_risk:"hara"},Ci=["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"],Di={hara:"iso26262",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"design",fmea:"process",security_risk:"tir57"},Hi={hara:"iso14971",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"process",fmea:"process",security_risk:"tir57"},Fi={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."},Ni={...Fi,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:Ya("The confirmation review of the HARA (ISO 26262)")},Pi={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)."},Ui={...Fi,...Pi,accept_analysis:Ya("The ISO 14971 clause 8 overall residual risk conclusion")},zi={...Fi,dfmea_s:Ni.dfmea_s,o:Ni.o,d:Ni.d,rpn:Ni.rpn,accept_analysis:Ya("The AIAG-VDA FMEA sign-off")},Li={...Fi,dfmea_s:Pi.dfmea_s,o:Pi.o,o_sw:Pi.o_sw,d:Pi.d,rpn:Pi.rpn,process_step:Pi.process_step,controls:Pi.controls,fn:Pi.fn,risk_control:Pi.risk_control,control_req:Pi.control_req,verified_by:Pi.verified_by,accept_analysis:Ya("The FMEA sign-off")},Wi={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"}},Vi=["asil","rpn","risk","p0"],Bi=["approved","approved_at","approved_by","approved_note","field_source","link_roles","mitigation_types"],Ji=[...Vi,...Bi],Gi={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"}},Qi=(e,t,n)=>1===e?t:n,Yi=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft safety requirement",label:e=>`${e} ${Qi(e,"safety goal","safety goals")} unmitigated`,matches:e=>e.level!==ci&&"QM"!==e.level&&!e.linked},{kind:"no_test",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Qi(e,"safety goal","safety goals")} without a test on its ODD`,matches:e=>e.level!==ci&&"QM"!==e.level&&e.linked&&!e.verified},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} ${Qi(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},Ki={kind:"not_accepted",scope:"analysis",fix:"open_analysis",fixLabel:"Accept analysis",label:()=>"Analysis not accepted",matchesAnalysis:e=>e.hasRows&&!e.accepted}],Zi=[{kind:"no_control",scope:"row",fix:"link_requirement",fixLabel:"Draft risk control requirement",label:e=>`${e} ${Qi(e,"risk","risks")} above Low with no control`,matches:e=>e.level!==ci&&"Low"!==e.level&&!e.linked},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Qi(e,"control","controls")} not verified for effectiveness`,matches:e=>e.level!==ci&&"Low"!==e.level&&e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual ${Qi(e,"risk","risks")} not assessed`,matches:e=>e.level!==ci&&"Low"!==e.level&&e.linked&&e.residualLevel===ci},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} risk ${Qi(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},Ki],Xi=[{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=>Ks(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=>!Ks(e.level)&&null!==e.severity&&e.severity>=9&&!e.linked},Ki],es=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft security control",label:e=>`${e} security ${Qi(e,"risk","risks")} above Low with no control`,matches:e=>Va(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===ci},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Qi(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===ci},{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(Va(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 ${Qi(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},Ki],ts=[{kind:"row_no_goal",fix:"open_row",fixLabel:"Set the safety goal",informational:!1,label:e=>`${e} hazardous ${Qi(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} ${Qi(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} ${Qi(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} ${Qi(e,"hazard","hazards")} cited by no hazardous event`},{kind:"goal_trashed",fix:"open_row",fixLabel:"Open row",informational:!0,label:e=>`${e} hazardous ${Qi(e,"event cites","events cite")} a safety goal in Trash`}]}});async function so(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:$s(n,r)??$s(n,a);return{spelling:i,registered:null!==i&&r.includes(i),carried:a.filter(e=>null!==$s(e,[n]))}}async function oo(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 lo(e){return`Domain "${e}" registered. You can now tag items with domains=["${e}"].`}function co(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 uo(e){return`Domain "${e}" already exists. Choose a different name.`}var po,mo,_o,fo,ho,yo,go=V({"src/core/domains.ts"(){io(),no="domain_not_function",ro=class extends Error{code=no;names;unregistered;constructor(e,t=[]){super(`${no}: ${e.join(", ")}`),this.name="DomainNotFunctionError",this.names=[...e],this.unregistered=[...t]}},ao="domain_rename_onto_function"}}),wo=V({"src/core/read-budget.ts"(){po=25e3,mo="read_timed_out",_o="ATOMS did not answer this read in time, so nothing was returned. The read changes nothing: asking again is safe.",fo=class extends Error{code=mo;constructor(e){super(`${mo}: the read did not finish within ${e} ms`),this.name="ReadBudgetExceededError"}}}});function vo(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-yo({...e,data:{preview:""},meta:r})-200);for(;;){const n={...e,data:{preview:a.slice(0,i)},meta:r},s=yo(n)-t;if(s<=0||0===i)return n;i=Math.max(0,i-s)}}var bo,jo,ko,So=V({"src/core/response-limit.ts"(){ho=25e3,yo=e=>JSON.stringify(e,null,2).length}});function Ao(e){if(!e)return!1;const t=String(e.code??""),n=String(e.message??"");return"55P03"===t||"40P01"===t||/item_save_busy|deadlock detected/i.test(n)}async function Io(e,t=bo){let n=await e();for(const r of t){if(!Ao(n.error))return n;await jo.sleep(Math.round(r*jo.jitter())),n=await e()}return n}async function xo(e){const t=await e();return function(e){return null!=e.error&&[0,502,503,504].includes(e.status??-1)}(t)?(await jo.sleep(250),e()):t}var $o,qo,Eo,Oo,Ro,Mo,To=V({"src/core/busy-retry.ts"(){bo=[50,100,200,400,800],jo={sleep:e=>new Promise(t=>setTimeout(t,e)),jitter:()=>.5+Math.random()},ko=[250,1e3,3e3]}});function Co(){return{status:"error",message:$o,next_steps:["Do not retry this call","Tell the user that a person can restore it from Trash in ATOMS"],code:qo,retryable:!1}}function Do(e,t){const n=function(e){const t=e.status??-1;return 0===t||t>=500||Ao(e)||"57014"===e.code||/timeout|timed out|canceling statement/i.test(e.message)}(t),r=Eo.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 Ho(e){const t=e.trashed_by,n=t?.name?.trim()||"Someone";return t?.agent?`${n}'s agent`:n}function Fo(e){return(e.deleted_at??"").slice(0,10)}function No(e,t){const n=`Restored ${e.item_id} from Trash. It was moved there by ${Ho(e)} on ${Fo(e)}`;return e.trashed_by?.user_id&&e.trashed_by.user_id!==t?`${n}; they have been notified.`:`${n}.`}var Po,Uo,zo,Lo,Wo,Vo,Bo,Jo,Go,Qo=V({"src/core/restore-confirm.ts"(){To(),$o="This item has been in Trash for more than 7 days. Only a person can restore it, from Trash in ATOMS.",qo="item_trash_too_old",Eo=[[/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}`]],Oo=["Show the user this message","Call atoms_restore_item again with confirm: true only after the user agrees"],Ro='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',Mo="true only after the user has seen the needs_confirmation message and agreed to the restore"}}),Ko={};function Yo(e,t=Uo){if("string"!=typeof e)return"";const n=e.replace(Wo,"").replace(Vo,"");return n.length<=t?n:n.slice(0,t)+"..."}function Zo(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Xo(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function el(e,t,n){return{total_count:e,limit:t,offset:n,has_more:n+t<e}}function tl(e,t,n={}){return{status:"error",message:e,next_steps:t,...n}}function nl(e,t){return tl(`${e} '${Yo(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function rl(e){return"account"===e?tl("Account suspended.",["Your ATOMS account is suspended, so ATOMS tools are unavailable","Contact ATOMS support or your organization admin to restore access"]):tl("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 al(e){const t=/\b(account|organization) suspended\b/i.exec(e);return t?t[1].toLowerCase():null}function il(e){return tl(`${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 sl(e,t=zo){return tl(`Validation error: ${Yo(e,t)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function ol(){return tl("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 ll(){return tl("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 cl(e){return tl("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 dl(e){return tl("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 ul(e){return function(e){const t=e&&e>0?Math.ceil(e):Kt;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 pl(){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 ml(e){return tl(`Parse error: ${Yo(e,zo)}`,["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 _l(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function fl(){return tl("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 hl(){return tl("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 yl(){return tl("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 gl(){return tl("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 wl(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 vl(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e),n=e&&"object"==typeof e&&"code"in e?String(e.code??""):"";if(r=t,Bt.some(e=>e.test(r)))return sl(t,Lo);var r,a;if(e instanceof Jt)return sl(t);if(en(t))return bl(e);if(Ln(t))return Wn();if(Ea(t))return"function_items"===(a=Ea(t))?{status:"error",code:"rollout_switched",key:"function_items",retryable:!1,message:Ia,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"===a?Ma():{status:"error",code:"rollout_switched",retryable:!0,message:Aa,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(Oa(t))return Ra();if(Ta(t))return Ca();if(/^auth_unavailable:/.test(t))return Tt();if(/^read_timed_out:/.test(t))return{status:"error",code:mo,retryable:!0,message:_o,next_steps:["Send the same call again in a moment","If it times out again, tell the user ATOMS is slow right now"]};if(/not authenticated/i.test(t))return ol();const i=function(e){const t=function(e){if(e instanceof ro)return e.names;if(e&&"object"==typeof e&&e.code===no){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!==$s(e,t)),i={code:no,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!==i)return i;if(wl(e))return ll();if(Vn(t))return Bn();if(function(e){return/item_trash_too_old/i.test(e)}(t))return Co();if(Jn(t))return Gn();const s=Zn(t);if(null!==s)return s;const o=Qn(t);if(null!==o)return o;const l=Kn(t);if(null!==l)return l;const c=re(t);if(null!==c)return c;if("55P03"===n||function(e,t){return"40P01"===e||/deadlock detected/i.test(t)}(n,t)||/item_save_busy/i.test(t))return hl();if(function(e,t){return!/^[0-9A-Z]{5}$/.test(e)&&/rate.?limit|too many requests|429/i.test(t)}(n,t))return ul();if(_l(t))return fl();if(/soft_deleted_item_write/i.test(t))return gl();if(/save_temporarily_unavailable/i.test(t))return yl();if("55P03"===n||"57014"===n||/item_save_busy|statement timeout|request timeout|upstream request timeout/i.test(t))return hl();const d=al(t);return d?rl(d):"42501"===n&&/org_project_field_admin_required/i.test(t)?nn("organization"):"42501"===n&&/project_field/i.test(t)?nn("project"):"P0002"===n&&/project_field/i.test(t)?tl("Project field not found.",["Refresh the field list and retry with an existing field name"]):["22023","23505","23514"].includes(n)&&/project_field/i.test(t)?sl(t.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?ml(t):kl(t)}function bl(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??"");if(!en(t)&&!tn(t))return null;const n=t.indexOf(Bo);return tl((n>=0?t.slice(n+Bo.length):t).trim(),["Wait a moment, read the item again (atoms_get_item), then send your change again"],{code:"rollout_switched",retryable:!0})}function jl(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=re(t);return["40001","PT409","55P03","57014"].includes(n)||null!==Ea(t)||null!==r&&"mcp_policy_block_destructive"!==r.code||/stale_item_write|soft_deleted_item_write|save_temporarily_unavailable|item_save_busy|statement timeout|request timeout|upstream request timeout|fetch failed|network error|connection (?:closed|reset|refused)/i.test(t)}function kl(e){if(/^auth_unavailable:/.test(e))return Tt();if(Zt(e))return ul();if(Xt(e))return ll();if(/^not authenticated/i.test(e))return ol();if(Vn(e))return Bn();if(Ln(e))return Wn();if(Oa(e))return Ra();if(Ta(e))return Ca();if(Jn(e))return Gn();const t=Zn(e);if(null!==t)return t;const n=Qn(e);if(null!==n)return n;const r=Kn(e);if(null!==r)return r;const a=re(e);return null!==a?a:/row.level security|permission denied for/i.test(e)?tl("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"]):tl(`Database error: ${Yo(e,zo)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function Sl(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function Al(e){return"string"!=typeof e?e:e.replace(/<\s*\/?\s*user_content\s*>/gi,"")}function Il(e){return Jo.has(e)}function xl(e,t,n=!1){return"string"==typeof e?n||null!=t&&Jo.has(t)?Sl(e):e:Array.isArray(e)?e.map(e=>xl(e,t,n)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,xl(t,e,n||Go.has(e))])):e}function $l(e,t={}){const n=t.complete?e:function(e,t=ho){if(yo(e)<=t)return e;if("success"!==e.status)return e;const n=n=>({...e.meta??{},truncated:!0,truncation_message:`Response truncated to stay under ${t} characters (${n}). Use 'offset' or 'limit' or add filters to see more results.`});if(Array.isArray(e.data)){const r=e.data.length;let a=e.data,i={...e,data:a,meta:n(`${r} items cut`)};for(;yo(i)>t&&a.length>1;)a=a.slice(0,Math.max(1,Math.floor(a.length/2))),i={...e,data:a,meta:n(`from ${r} to ${a.length} items`)};return yo(i)<=t?i:vo(e,t,n)}if(e.data&&"object"==typeof e.data){const r={...e.data},a=[],i={},s=()=>({...e,data:r,meta:n(`arrays cut: ${a.join(", ")}`)});for(;;){if(yo(s())<=t)return s();let e,n=0;for(const[t,a]of Object.entries(r))if(Array.isArray(a)&&a.length>1){const r=JSON.stringify(a).length;r>n&&(e=t,n=r)}if(!e)break;const o=r[e];i[e]??=o.length,r[e]=o.slice(0,Math.floor(o.length/2));const l=`${e} ${i[e]} to ${r[e].length}`,c=a.findIndex(t=>t.startsWith(`${e} `));c>=0?a[c]=l:a.push(l)}}return vo(e,t,n)}(e);return{content:[{type:"text",text:JSON.stringify(xl(n),null,2)}],structuredContent:n}}function ql(e){return{content:[{type:"text",text:JSON.stringify(xl(e),null,2)}],structuredContent:e,isError:!0}}B(Ko,{CHARACTER_LIMIT:()=>Po,USER_CONTENT_KEYS:()=>Jo,VALIDATION_MESSAGE_LONG:()=>Lo,accessDeniedError:()=>il,authError:()=>ol,classifyError:()=>vl,dbError:()=>kl,errorResponse:()=>tl,formatErrorResult:()=>ql,formatToolResult:()=>$l,isAutoWrappedKey:()=>Il,isItemSaveStopError:()=>jl,isJwtExpiredErrorForTool:()=>wl,isStaleWriteErrorMessage:()=>_l,jwtExpiredError:()=>ll,notFoundError:()=>nl,orgScopeError:()=>dl,paginationMeta:()=>el,parseError:()=>ml,policyNotLoadedError:()=>pl,rateLimitError:()=>ul,sanitizeForEcho:()=>Yo,sanitizeTagOrLevel:()=>Zo,saveBusyError:()=>hl,saveUnavailableError:()=>yl,scopeError:()=>cl,softDeletedItemError:()=>gl,staleWriteError:()=>fl,stripUserContentMarkers:()=>Al,success:()=>Xo,suspendedError:()=>rl,suspensionKind:()=>al,switchRedoFailedError:()=>bl,validationError:()=>sl,wrapMcpUserContentFields:()=>xl,wrapUserContent:()=>Sl});var El,Ol,Rl,Ml=V({"src/tools/_base.ts"(){zn(),La(),go(),Ht(),wo(),de(),So(),da(),Qo(),Po=25e3,Uo=50,zo=200,Lo=600,Wo=new RegExp("[\\u0000-\\u001F\\u007F]","g"),Vo=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g"),Bo="rollout_switched:multiuser_saving: ",Jo=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"]),Go=new Set(["fields","diff","point","theirs_value","base_value","your_value","old_value","new_value"])}});async function Tl(e,t){const n=Ol.get(t),r=Date.now();if(n&&r-n.at<El)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 Ol.set(t,{status:s,at:r}),s}function Cl(e){return JSON.stringify(xl(e),null,2)}var Dl,Hl,Fl,Nl,Pl,Ul,zl,Ll,Wl=V({"src/middleware/status-gate.ts"(){Ml(),ve(),El=3e4,Ol=new Map,Rl="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."}}),Vl={};async function Bl(){if(Dl)try{const e=await nt();e&&e.expires_at>Pl&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),Jl())}catch{}if(Dl&&Nl>Date.now()+6e4)return Dl;Dl&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:n}=await async function(){if(Ul&&Date.now()-Ul.at<1e3*$t)throw Ul.error;return zl??=Pt().then(e=>(Ul=null,e)).catch(e=>{throw e instanceof Et&&(Ul={at:Date.now(),error:e}),e}).finally(()=>{zl=null}),zl}(),r=e.split(".");if(3===r.length)try{const e=JSON.parse(Buffer.from(r[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());Nl=1e3*(e.exp??0)}catch{Nl=Date.now()+36e5}try{const e=await nt();Pl=e?.expires_at??0}catch{Pl=0}const a=d(bt,jt,{global:{headers:{Authorization:`Bearer ${e}`},fetch:ma({supabaseUrl:bt,anonKey:jt,accessToken:e})}});return Hl=t,Fl=n,Dl=a}function Jl(){Ul=null,Dl=null,Hl=null,Fl=null,Ll=void 0,Nl=0,Pl=0,Ol.clear()}function Gl(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 Ql(e){try{return await e()}catch(t){if(!Gl(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),Jl(),await e()}}function Kl(){if(!Hl)throw new Error("Not authenticated. Call getClient() first.");return Hl}function Yl(){return Fl??""}async function Zl(e){const t=Kl();if(Ll&&Ll.userId===t)return Ll.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 Ll={userId:t,name:a},a}catch{return null}}function Xl(e){if(e&&e.deleted_at)throw new Error(cn)}async function ec(e,t){const{data:n,error:r}=await e.from("projects").select("deleted_at").eq("id",t).maybeSingle();if(r||!n)throw Yn(t,r);Xl(n)}async function tc(e,t){const n=Kl(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Yn(t,a);Xl(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 nc(e,t){const n=Kl(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Yn(t,a);Xl(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")}B(Vl,{assertProjectLive:()=>ec,getClient:()=>Bl,getUserEmail:()=>Yl,getUserId:()=>Kl,getUserName:()=>Zl,invalidateClient:()=>Jl,isJwtExpiredError:()=>Gl,requireProjectFieldDefinitionAccess:()=>nc,requireWriteAccess:()=>tc,throwIfProjectInTrash:()=>Xl,withJwtRetry:()=>Ql});var rc,ac,ic=V({"src/db/client.ts"(){Lt(),Ht(),ft(),Rt(),da(),va(),Wl(),Dl=null,Hl=null,Fl=null,Nl=0,Pl=0,Ul=null,zl=null}}),sc={};async function oc(){const e=_(32).toString("base64url"),t=f("sha256").update(e).digest("base64url"),n=`http://localhost:${rc}${ac}`,r=new y(`${kt}/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 a;function i(){clearTimeout(a)}const s=u(async(r,a)=>{const o=new y(r.url??"/",`http://localhost:${rc}`);if(o.pathname!==ac)return a.writeHead(404),void a.end("Not found");try{if("access_denied"===o.searchParams.get("error"))return a.writeHead(200,{"Content-Type":"text/html"}),a.end(lc("Authorization was cancelled.")),i(),s.close(),void n(new Error("Authorization cancelled by user."));const r=o.searchParams.get("code");if(r){const o=await fetch(`${bt}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:jt},body:JSON.stringify({auth_code:r,code_verifier:e})}),l=await o.json();if(!o.ok||!l.access_token){const e=l.error_description??l.msg??"Unknown error";return a.writeHead(200,{"Content-Type":"text/html"}),a.end(lc(`Code exchange failed: ${e}`)),i(),s.close(),void n(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(l.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:d}=await import("@supabase/supabase-js"),u=d(bt,jt,{global:{headers:{Authorization:`Bearer ${l.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(lc('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.')),i(),s.close(),void n(new Error("No ATOMS account found. Sign up at atoms.tech first."))):l.refresh_token?(await rt({access_token:l.access_token,refresh_token:l.refresh_token,expires_at:Date.now()+1e3*(l.expires_in??3600),user_email:c}),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)),i(),s.close(),void t({email:c})):(a.writeHead(200,{"Content-Type":"text/html"}),a.end(lc("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.")),i(),s.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(lc("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"),i(),s.close(),n(e)}});s.listen(rc,"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")}}),a=setTimeout(()=>{s.close(),n(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp@latest login' to try again."))},6e4)})}function lc(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>`}B(sc,{login:()=>oc});var cc=V({"src/auth/login.ts"(){ft(),Rt(),rc=19275,ac="/callback"}}),dc={};async function uc(){const{getValidToken:e,readValidToken:t}=await Promise.resolve().then(()=>(Lt(),Ft)),{runExclusiveAuth:n}=await Promise.resolve().then(()=>(St(),ht)),{login:r}=await Promise.resolve().then(()=>(cc(),sc));try{return(await e()).email}catch(e){if(e instanceof Et)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}}B(dc,{startupAuth:()=>uc});var pc,mc,_c,fc=V({"src/auth/startup.ts"(){Ht()}});function hc(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&&pc.has(n.level)?{level:n.level,source:"string"==typeof n.source?n.source:null,dismissed:!0===n.dismissed}:null}function yc(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?hc(e.data):null;return a&&(r.asil_pending_lower={value:a.level,source:a.source,dismissed:a.dismissed,since:t.since}),r}function gc(e){return{op_id:"",status:"forbidden",reason:"asil_lower_needs_person",item_id:e,path:[...mc],seq:null}}var wc,vc,bc,jc=V({"src/core/asil-read.ts"(){pc=new Set(["QM","A","B","C","D"]),mc=["asil_confirm_lower"],_c="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 kc(e){return e.startsWith("req_type '")}function Sc(e,t){if("requirement"!==t)return`req_type applies only to requirements (type='requirement'), not '${t}'.`;const n=`Plain requirement types: ${wc.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}`:wc.includes(e)?null:`Unknown req_type '${e.slice(0,50)}'. Allowed: ${wc.join(", ")}.`}var Ac,Ic,xc,$c,qc=V({"src/core/req-type.ts"(){wc=["functional","interface","performance","safety"],vc=["safety-goal","failure-mode"],bc="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 Ec(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of xc)if(t.test(e.trim()))return"[redacted]";return e.length>$c?e.slice(0,$c)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Ec(e,t+1));if(null!==e&&"object"==typeof e){const n={};for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();Ac.has(e)?n[r]="[redacted]":Ic.has(e)?n[r]="string"==typeof a?"[content]":Ec(a,t+1):n[r]=Ec(a,t+1)}return n}return e}function Oc(e){return Ec(e)}var Rc,Mc,Tc,Cc,Dc,Hc,Fc,Nc,Pc=V({"src/middleware/audit.ts"(){Ac=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),Ic=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),xc=[/^[^\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_-]+$/],$c=200}}),Uc=V({"src/middleware/rate-limiter.ts"(){Rc=60,Mc=6e4}}),zc={};function Lc(){return l.join(o(),".atoms","update-check.json")}async function Wc(){if(!Nc&&(Nc=!0,"1"!==process.env.ATOMS_MCP_NO_UPDATE_CHECK))try{const e=await async function(){try{const e=JSON.parse(await g.readFile(Lc(),"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<Cc)return void(Hc=e.latest);const t=new AbortController,n=setTimeout(()=>t.abort(),Dc);try{const e=await fetch(process.env.ATOMS_MCP_UPDATE_URL??Tc,{signal:t.signal});if(!e.ok)return;const n=await e.json();if("string"!=typeof n.version)return;Hc=n.version,await async function(e){try{await g.mkdir(l.dirname(Lc()),{recursive:!0}),await g.writeFile(Lc(),JSON.stringify({checked_at:Date.now(),latest:e}),"utf8")}catch{}}(n.version)}finally{clearTimeout(n)}}catch{}}function Vc(e){return null!==Hc&&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,Hc)?{current:e,latest:Hc,args:["@atoms-tech/atoms-mcp@latest"],command:"npx @atoms-tech/atoms-mcp@latest"}:null}function Bc(e){const t=Vc(e);return t?Xn(t.current,t.latest):null}function Jc(e){if(Fc)return null;const t=Bc(e);return null===t?null:(Fc=!0,t)}function Gc(e,t){const n=Jc(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 Qc(e,t){const n=Vc(t);if(null===n||!e||"object"!=typeof e)return e;const r=Xn(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 Kc(){Hc=null,Fc=!1,Nc=!1}B(zc,{UPDATE_CHECK_TIMEOUT_MS:()=>Dc,attachUpdateAvailable:()=>Qc,attachUpdateNotice:()=>Gc,getUpdateAvailable:()=>Vc,resetUpdateCheckForTests:()=>Kc,startUpdateCheck:()=>Wc,takeUpdateNotice:()=>Jc,updateStatusSentence:()=>Bc});var Yc,Zc,Xc,ed,td,nd,rd,ad,id,sd,od,ld,cd,dd,ud,pd,md,_d,fd=V({"src/middleware/update-check.ts"(){da(),Tc="https://registry.npmjs.org/@atoms-tech/atoms-mcp/latest",Cc=864e5,Dc=3e3,Hc=null,Fc=!1,Nc=!1}}),hd=V({"src/core/timestamps.ts"(){Yc=w.string().datetime({offset:!0})}});function yd(e){return 32===e||9===e||13===e||10===e}function gd(e){if("string"!=typeof e)return NaN;const t=Zc.exec(function(e){let t=0,n=e.length;for(;t<n&&yd(e.charCodeAt(t));)t++;for(;n>t&&yd(e.charCodeAt(n-1));)n--;return e.slice(t,n)}(e));if(!t)return NaN;const[,n,r,a,i="0",s="0",o="0",l="",c="Z"]=t,d=Number(n),u=Number(r),p=Number(a),m=Date.UTC(d,u-1,p,Number(i),Number(s),Number(o));if(new Date(m).getUTCDate()!==p)return NaN;let _=0;if("Z"!==c.toUpperCase()){const e="-"===c[0]?-1:1,t=c.slice(1).replace(":","");_=e*(60*Number(t.slice(0,2))+(t.length>2?Number(t.slice(2,4)):0))}return 1e3*(m-6e4*_)+Number(`${l}000000`.slice(0,6))}function wd(e,t){const n=gd(e),r=gd(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 vd(e){return"passed"===e||"failed"===e||"blocked"===e}function bd(e){const t=[];return e.forEach((e,n)=>{e&&void 0!==e.date&&null!==e.date&&t.push(n)}),t}function jd(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 kd(e){const t=[];return e.forEach((e,n)=>{const r=e?.release_id;"string"==typeof r&&""!==r.trim()||t.push(n)}),t}function Sd(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 Ad(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 Id(e,t){return"string"==typeof e?t(e):Array.isArray(e)?e.map(e=>Id(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Id(n,t)])):e}function xd(e,t){const n=Id(e,t);return ud(n?.point)&&(n.point=Object.fromEntries(Object.entries(n.point).map(([e,n])=>[t(e),n]))),n}function $d(e,t){if(!Array.isArray(e)||!Array.isArray(t))return e;const n=["source","plus","minus"];return e.map(e=>{if(!ud(e)||n.some(t=>t in e))return e;const r=t.find(t=>ud(t)&&t.name===e.name);return ud(r)&&JSON.stringify(r.values)===JSON.stringify(e.values)?{...e,...Object.fromEntries(Object.entries(r).filter(([e])=>n.includes(e)))}:e})}function qd(e){const t=e.data?.status,n="test-case"===e.type?Cd(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||wd(r.date,n.date)<0)&&(n=r);return n}(e,e=>vd(e.result))?.result;return vd(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 Ed(e){const t=e.data?.runs;return"test-case"===e.type&&Array.isArray(t)&&t.length>0}function Od(e){return`${e} has runs: ${pd}. Record a run: atoms_record_test_result(s).`}function Rd(e,t){return"test-case"===e.type&&!Ed(e)&&("passed"===t||"failed"===t||"blocked"===t)}function Md(e){return`${e} has no runs: ${md}. Record a run: atoms_record_test_result(s).`}function Td(e,t){const n="string"==typeof e.result?e.result:void 0;if(vd(n))return n;if(!Array.isArray(e.step_results)||0===e.step_results.length)return"not-run";const r=e.step_results.map(e=>ud(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 Cd(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=>ud(e)?{...e,result:Td(e,n)}:e)}var Dd=V({"src/core/run-order.ts"(){Zc=/^([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,Xc="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).",ed="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.",td="Ignored: the run is stamped with server time. A supplied date is reported in the response warning, never stored.",nd="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.",rd="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.",ad="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).",id="Ignored: the server pins the test case's current steps revision itself",sd="Link to evidence kept elsewhere, at most 2048 characters. Stored as text; ATOMS does not open it",od="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",ld="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.",cd="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.",dd="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.",ud=e=>!!e&&"object"==typeof e&&!Array.isArray(e),pd="its status comes from its runs and cannot be set",md="a result can only come from a run",_d="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 Hd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Fd(e){return e.replace(/[\\%_*]/g,e=>`\\${e}`)}function Nd(e){return Hd(`*${Fd(e)}*`)}function Pd(e){return Fd(e)}function Ud(e){return`*"${Fd(e)}"*`}async function zd(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 Ld,Wd,Vd,Bd,Jd,Gd,Qd,Kd,Yd,Zd,Xd,eu=V({"src/core/postgrest.ts"(){}});async function tu(e,t,n=1e3){if(!Number.isInteger(n)||n<1)throw new Error(`selectAllPaged: pageSize must be a positive integer, got ${n}`);if(0===t.length)throw new Error("selectAllPaged: at least one keyset column is required");const r=[];let a;for(let i=1;;i++){let s=e();void 0!==a&&(s=s.or(ru(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(`${nu(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(`${nu(s)} read, page ${i}: the page did not move past the last row read`);r.push(...c),a=d}}function nu(e){const t=e.url;return t instanceof URL?decodeURIComponent(t.pathname).replace(/^.*\/rest\/v1\//,""):"query"}function ru(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 Hd(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 au(e,t,n,r){return tu(()=>e.rpc(t,{p_project_id:n,p_snapshot_at:r}),Gd[t])}function iu(e,t,n){return"baselineId"in n?tu(()=>e.rpc("baseline_variables_state",{p_baseline_id:n.baselineId}),Jd):au(e,"variables_at",t,n.at)}async function su(e,t){const n=[];for(let r=0;r<e.length;r+=Yd){const{data:a,error:i}=await t(e.slice(r,r+Yd));if(i)throw new Error(i.message);n.push(...a??[])}return n}function ou(e){if("string"==typeof e.created_at&&"string"==typeof e.id)return function(e){const t=(new TextEncoder).encode(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(JSON.stringify([e.created_at,e.id]))}var lu,cu,du,uu,pu=V({"src/core/paginate.ts"(){eu(),Wd=["from_id","to_id","type"],Vd=["variable_id","item_id","field"],Bd=["name","id"],Gd={project_state_at:Ld=["id"],variables_at:Jd=["name","id"]},Qd=e=>({at:e}),Kd=e=>({baselineId:e}),Yd=200,Zd=["created_at","id"],Xd=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 mu(e){return"requirement"===e.type&&"string"==typeof e.data?.req_type&&vc.includes(e.data.req_type)}function _u(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 fu(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||!mu(a)&&"goal"!==a.type)return;if("requirement"!==i.type||mu(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 hu(e,t){const n=fu(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&&mu(i)&&"goal"===r.get(n)?.type&&a.set(t,n)}const i=new Map;for(const[e,t]of n)mu(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}async function yu(e,t){return tu(()=>e.from("items").select(lu).eq("project_id",t).eq("type","requirement").is("deleted_at",null).not("data->relationships->mitigates","is",null),Ld)}function gu(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 vu(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 vu(t.data?.relationships?.mitigated_by))r.push({from_id:t.id,to_id:e,type:"mitigated_by"})}const a=hu([...n.values()],r);for(const t of e){const e=a.get(t.id);e&&a.set(t.id,[...new Set([...vu(t.data?.relationships?.mitigated_by).filter(t=>e.includes(t)),...e])])}return a}async function wu(e,t,n,r){return gu([n],[...r.map(e=>({id:e.id,type:e.type,req_type:e.data?.req_type,mitigates:e.data?.relationships?.mitigates})),...await yu(e,t)]).get(n.id)??[]}function vu(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function bu(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 ju(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 ku(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 Su(e,t,n){return e.filter(e=>!t.has(e)&&(n.get(e)?.length??0)>0).length}var Au,Iu,xu=V({"src/core/coverage-mitigation.ts"(){pu(),io(),qc(),lu="id, type, updated_at, content_changed_at, req_type:data->>req_type, mitigates:data->relationships->mitigates",cu="role, control_type and override apply to action add only; omit them to remove a link.",du="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.",uu="coverage.covered and coverage.percent count a requirement's own linked test cases. coverage.via_mitigation counts the requirements with no test case of their own that are hazard, failure mode or risk rows with at least one live mitigating requirement, which the app reads as covered through its mitigation; it is not part of covered or percent."}});function $u(e,t){return t>0?Math.round(e/t*1e3)/10:Au}var qu,Eu=V({"src/core/project-summary.ts"(){Dd(),Au=100,Iu="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 Ou(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 qu){const a=e[n];if(Array.isArray(a))for(const e of a)"string"==typeof e&&i(t.id,e,r)}}return a}var Ru,Mu,Tu,Cu,Du,Hu=V({"src/core/relationship-sync.ts"(){qu=[["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"]]}});function Fu(e){const t=e?.trim();return t?`Release ${t}`:Ru}async function Nu(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 Mu;const a=function(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]}(n);return a?{releaseId:a.id,label:Fu(a.release_version)}:Mu}catch{return Mu}}async function Pu(e,t,n,r){return su([...new Set(n)],n=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:r,p_requirement_ids:n}))}async function Uu(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 Nu(e,t),s=new Set(r);if(a.length>0){const n=a.map(e=>e.id),r=[];for(let a=0;a<n.length;a+=200){const i=n.slice(a,a+200);r.push(...await tu(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verified_by").in("to_id",i),Wd)),r.push(...await tu(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verifies").in("from_id",i),Wd))}const i=await tu(()=>e.from("items").select("id, verified_by:data->relationships->verified_by").eq("project_id",t).eq("type","requirement").is("deleted_at",null),Ld),o=new Set(i.map(e=>e.id)),l=new Set(n),c=Ou([...a,...i.map(e=>({id:e.id,data:{relationships:{verified_by:Tu(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 Pu(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 zu(e,t){const n=e?.flags.get(t);return void 0!==n&&e?.scope?{needs_rerun:n,rerun_scope:e.scope.label}:{}}var Lu,Wu,Vu,Bu=V({"src/core/rerun.ts"(){pu(),Hu(),Mu={releaseId:null,label:Ru="All runs"},Tu=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],Cu="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.",Du='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 Ju(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 Gu(e){const t=["requirement","test-case","note","table"];return"items"===e?[...t,"function"]:t}function Qu(e){return"items"===e?null:"unknown"===e?{status:"error",message:Vu,next_steps:["Send the same call again in a moment"],code:"function_mode_unreadable",retryable:!0}:{status:"error",message:Lu,next_steps:Wu,code:"function_items_off",retryable:!1}}var Ku,Yu,Zu,Xu,ep,tp,np,rp,ap,ip,sp,op=V({"src/core/function-mode.ts"(){Lu="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.",Wu=["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"],Vu="The project's Function setting could not be read just now. Nothing was written. Send the same call again in a moment."}});function lp(e){return(e??"").trim().toLowerCase()}function cp(e){const t=e.analysis_props;return t&&"object"==typeof t?t:{}}function dp(e){return"string"==typeof e?e:""}function up(e,t,n,r){const a=cp(e),i=dp(a.source_function),s={id:null,title:null,label:i,state:"legacy-text"};if(!t||!Ku.has(t))return s;let o=dp(a.source_function_id).trim();if(!o){const e=lp(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 pp(e,t,n,r){const a=up(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 mp(e,t){const n=tp[e]?.[t]??`Create a Function with ${Yu}.`;return`${t} was removed in ATOMS MCP ${Zu}, with no deprecation period. ${n} Nothing was written.`}function _p(e,t){const n=function(e,t){const n=tp[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=>mp(e,t)).join(" ")}`,next_steps:[`Create a Function with ${Yu}, 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 fp(e){return(t,n)=>{if("unrecognized_keys"===t.code){const n=tp[e]??{},r=(t.keys??[]).filter(e=>e in n);if(r.length>0)return{message:r.map(t=>mp(e,t)).join(" ")}}return{message:n.defaultError}}}function hp(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 yp(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 ${Yu}`],code:"function_id_invalid",retryable:!1,invalid_function_ids:e.map(e=>e.id)}}function gp(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 wp(e,t,n){return vp(e,t,n,await Ju(e,t))}async function vp(e,t,n,r){const a=Qu(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:gp(n)};const i=hp(n);if(0===i.length)return{ok:!0,functions:[]};const s=await bp(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:yp(o)}:{ok:!0,functions:l}}async function bp(e,t,n){const r=new Map;if(0===n.length)return r;const{data:a,error:i}=await e.from("items").select("id, type, title, deleted_at, content_changed_at, updated_at").eq("project_id",t).in("id",[...n]);if(i)throw new Error(`Function read failed: ${i.message??"unknown error"}`);for(const e of Array.isArray(a)?a:[])r.set(e.id,e);return r}function jp(e){return e.functionId?{source_function:e.text,source_function_id:e.functionId}:{source_function:e.text}}function kp(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 Sp(e){return!!e&&Ku.has(e)}async function Ap(e,t,n){if(Sp(e)){if(!t.includes("source_function"))return null;const r=`source_function was removed in ATOMS MCP ${Zu}, 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 ${Yu}). 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(Xu)?"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 Ip(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 xp(e){return e?jp(e):{source_function:null}}function $p(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 qp,Ep,Op=V({"src/core/functions.ts"(){da(),op(),Ku=new Set(["hara_iso26262","hazard_iso14971"]),Zu="0.62.0",Xu="source_function_id",tp={atoms_update_domain:{is_function:`A function is no longer a flagged domain tag: it is an item. Create one with ${Yu="atoms_create_item type 'function'"}, on a project with Function items turned on. ${ep="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 ${Yu}); seed a security risk analysis with source_assets, its asset names. ${ep}`},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 ${Yu}). ${ep}`},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 ${Yu}). 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.`}},np="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.",rp=["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"],ap='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.',ip=["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"],sp=50}});function Rp(e){return e?qp.indexOf(e):-1}function Mp(e,t){const n=e?.[t];return"string"==typeof n?[n]:Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}function Tp(e){return[...Mp(e,"event_hazard"),...Mp(e,"event_goal")]}function Cp(e){const t=e.analysis_props;return"requirement"===e.type&&!!t&&"object"==typeof t}function Dp(e){return!!e&&!e.deleted_at}var Hp,Fp,Np,Pp,Up,zp,Lp,Wp,Vp,Bp,Jp,Gp,Qp,Kp,Yp,Zp,Xp,em,tm,nm,rm=V({"src/core/safety-index.ts"(){io(),xu(),Op(),qp=["QM","A","B","C","D"],Ep=new WeakMap}});function am(e){return"safety_goal"===e?"goal":e}function im(e){return"hazard"===e||"goal"===e}async function sm(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=rs(n),i="automotive"===(a??"automotive")&&await ja(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 om(e){if(!e)return{status:"error",message:Gp,next_steps:["Send the same call again in a moment"],code:"hazard_goal_unreadable",retryable:!0};const t=ka(e);return null===t?null:t===ga?Ca():Ma()}async function lm(e,t){return om(await sm(e,t))}function cm(e){const t={},n={};for(const[r,a]of Object.entries(e??{})){const e=Kp[r];if(!e){n[r]=a;continue}if("string"!=typeof a)return{picks:{},rest:{},error:`${r} must be the id of a ${"goal"===Yp[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 dm(e){return Object.keys(e).length>0}function um(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=wi[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 ${Gi[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 pm(e,t,n){const r=Yp[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`${Xp[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 mm(e,t,n,r={}){for(const a of["event_hazard","event_goal"]){const i=Zp[a];if(!n.includes(i))continue;const s=void 0!==r[a]?r[a]:Mp(t,a)[0]??null;if(!s)continue;const o="goal"===Yp[a]?"Safety goal":"Hazard";return`${e} names its ${o} as an item (${s}), so its ${i} text is read-only. Pick another ${o} with ${Xp[a]}, or change the item itself with atoms_update_item. Nothing was written.`}return null}function _m(e,t){const n=[];for(const r of["event_hazard","event_goal"]){if(void 0===t[r])continue;const a=Mp(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 fm(e,t,n,r,a,i,s,o){if(!dm(i))return null;if(!a)return{kind:"validation",message:um(n,r)};const l=_m(s,i).filter(e=>"add"===e.kind);if(0===l.length)return null;const c=om(await sm(e,t));if(c)return{kind:"tool",error:c};for(const e of l){const t=pm(e.path[1],e.value,await o(e.value));if(t)return{kind:"validation",message:t}}return null}function hm(e,t){const n={};for(const r of["event_hazard","event_goal"])void 0!==t[r]?n[Xp[r]]=t[r]??null:Mp(e,r).length>0&&(n[Xp[r]]=Mp(e,r)[0]);return n}function ym(e){return e.filter(e=>em.has(e.trim().toLowerCase().replace(/[\s-]+/g,"_")))}function gm(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 wm(e,t){const n=Gi[e];return"hara_iso26262"===e&&"hazard_goal"===t?{...n,row:tm}:n}function vm(e,t){return"hara_iso26262"===e&&"hazard_goal"===vs(t)}function bm(e){return{event_label:tm,display_id:(t=e,/^SG-/.test(t)?`Event ${t}`:t)};var t}function jm(e){return"requirement"===e.type&&e.data?.req_type===nm}function km(e,t){if(!jm(e)||"analysis"!==t?.type)return!1;const n=t.data??null,r=n?.analysis_props?.variant;return vm(as("dfmea"===n?.analysis?.subtype?"dfmea":"hara","string"==typeof r?r:null,null),{analysis_props:n?.analysis_props})}function Sm(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 Am(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 Im(e){const t=Am(e);return function(e,t){const n=Ep.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=>Dp(n.get(e)),a=e=>r(e)&&"goal"===n.get(e)?.type,i=new Map,s=new Map;for(const t of e){if(!Cp(t))continue;const e=Mp(t.relationships,"event_goal")[0],r=e?n.get(e):void 0;!e||r&&"goal"!==r.type||i.set(t.id,e);const a=Mp(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 Mp(i.relationships,r)){const t=n.get(e);t&&Cp(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=>qs(n.get(e)?.analysis_props),p=e=>{let t=-1;for(const n of e)t=Math.max(t,Rp(u(n)));return t<0?"QM":qp[t]},m=new Set;for(const t of e)if(Dp(t))if("test-case"===t.type)for(const e of Mp(t.relationships,"verifies"))m.add(e);else for(const e of Mp(t.relationships,"verified_by")){const r=n.get(e);Dp(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=up(e,"hara_iso26262",_);"live"===a.state&&a.id&&t.add(a.id)}return[...t].sort()},h=t=>e.filter(e=>e.type===t&&Dp(e)).map(e=>e.id).sort(),y=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:y,goalCoverage:(e,n)=>{const i=y(e),s=a(e)?c.get(e)??[]:[],o=n?s.filter(e=>n.includes(e)):s,l=new Set(i),d=new Set,p=[],_=[];for(const e of o){const n=(t.byRow.get(e)??[]).filter(r);for(const e of n)l.has(e)||d.add(e);Rp(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:[...d].sort(),uncoveredRows:p,untestedRows:_}},directMitigators:e=>[...t.byRow.get(e)??[]],rowMitigated:e=>{if((t.byRow.get(e)??[]).length>0)return!0;const n=i.get(e);return!!n&&y(n).length>0},requirementVerified:e=>m.has(e),hazardFunctions:e=>f(d.get(e)??[]),goalFunctions:e=>f(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 Ep.set(e,{links:t,index:r}),r}(t,function(e){const t=[],n=[];for(const r of e)if(Dp(r)){t.push({id:r.id,type:r.type,data:{req_type:r.req_type,analysis_props:r.analysis_props}});for(const e of Mp(r.relationships,"mitigated_by"))n.push({from_id:r.id,to_id:e,type:"mitigated_by"});for(const e of Mp(r.relationships,"mitigates"))n.push({from_id:r.id,to_id:e,type:"mitigates"})}return{byRow:fu(t,n)}}(t))}async function xm(e,t){return await tu(()=>e.from("items").select("id, title, type, data").eq("project_id",t).is("deleted_at",null),Ld)}async function $m(e,t,n,r){const a=Mp(n,"event_goal")[0];if(!a)return[];const i=await r(a);if(!i||"goal"!==i.type)return[];const s=[];for(const e of Mp(i.data?.relationships,"mitigated_by")){const t=await r(e);t&&s.push(t)}const o=await yu(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"});for(const e of o){l.some(t=>t.id===e.id)||l.push({id:e.id,type:e.type,data:{req_type:e.req_type}});for(const t of Mp({mitigates:e.mitigates},"mitigates"))c.push({from_id:e.id,to_id:t,type:"mitigates"})}const d=[];for(const e of fu(l,c).get(i.id)??[]){const t=s.find(t=>t.id===e)??await r(e);t?.data?.asil_source===a&&d.push(e)}return d}var qm,Em,Om,Rm,Mm,Tm,Cm,Dm,Hm,Fm,Nm=V({"src/core/hazard-goal-tools.ts"(){qa(),io(),ns(),La(),rm(),pu(),xu(),Fp=["requirement","test-case","note","function","hazard","goal","safety_goal"],Np=`Item type. function only where Function items are on. ${Hp="hazard and goal: ISO 26262 (automotive) projects only; in a medical device project hazards are rows of the ISO 14971 risk analysis"}. safety_goal is another name for goal (a Safety goal item, SG-n); a hazard is HAZ-n.`,Pp="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.",Up="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.",zp='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.',Lp='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.',Wp="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.",Vp="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.",Bp='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. 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.',Jp=["requirement","test-case","note","table","analysis","function","hazard","goal"],Gp="Could not read whether this project takes Hazard and Safety goal items, so nothing was written. Send the same call again in a moment.",Qp=["event_hazard","hazard_events","event_goal","goal_events"],Kp={hazard_id:"event_hazard",goal_id:"event_goal"},Yp={event_hazard:"hazard",event_goal:"goal"},Zp={event_hazard:"hazard",event_goal:"safety_goal"},Xp={event_hazard:"hazard_id",event_goal:"goal_id"},em=new Set(["safe_state","ftti"]),tm="Hazardous event",nm="safety-goal"}});function Pm(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 Um(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 zm(e,t){const n=Xa(e.data);return km(e,n?t.get(n):void 0)?bm(e.id):{}}function Lm(e){return Math.min(Math.max(e??5,1),10)}var Wm,Vm,Bm=V({"src/core/trace-graph.ts"(){ns(),Nm(),qm=200,Em=new Set(["parent","verifies","mitigated_by","allocated_to","event_hazard","goal_events"]),Om=new Set(["child","verified_by","mitigates","allocated_from","hazard_events","event_goal"]),Rm=["allocated_to","allocated_from"],Mm={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"},Tm=["parent","verifies","mitigated_by","traces_to","allocated_to","decomposed_from","event_hazard","goal_events"],Cm=["child","verified_by","mitigates","allocated_from","decomposes_to","traced_by","hazard_events","event_goal"],Dm={...Mm,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"},Hm="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.",Fm="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."}}),Jm=V({"src/core/tool-descriptions.ts"(){Dd(),xu(),Eu(),Bu(),Bm(),X(),Nm(),Wm={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\n\nReturns:\n { status: "success", data: [{ id, name, description, org_id, org_name, created_at }] }\n\nExamples:\n - "What projects do I have?" → atoms_list_projects()\n - "Show my projects" → atoms_list_projects()\n\nWorkflow:\n atoms_list_projects → atoms_list_items(project_id) → atoms_get_item(project_id, item_id)',atoms_list_items:`List items in an ATOMS project with optional type/domain/level filters.\n\nThis is the primary ENTRY POINT for discovering items. Use it to browse\nproject contents before drilling into specific items with atoms_get_item.\n\nArgs:\n - project_id (string, UUID): The project to list items from\n - type (string, optional): Filter: requirement|test-case|note|table|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? } }\n\n${Cu}\n\nExamples:\n - "Show me all requirements" → atoms_list_items(project_id, type="requirement")\n - "What test cases exist?" → atoms_list_items(project_id, type="test-case")\n\nErrors:\n - "Project not found" → verify project_id\n - "Access denied" → check org membership`,atoms_get_item:`Get full details of a single item including relationships, test history, and ownership.\n\nUse after atoms_list_items or atoms_search to drill into a specific item.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID (e.g., "REQ-001", "TC-050")\n - baseline_id (string, UUID, optional): return the item as it was at that baseline\n - as_of (string ISO 8601, optional): return the item as it was at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\n${Cu}\n\n${dd}\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. ${T}\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${Bp}`,atoms_search:'Full-text search across items in a project. Searches title, body, and summary.\n\nAlternative entry point to atoms_list_items when you know what you\'re looking for.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Search text (max 1000 chars)\n - type (string, optional): Filter by type\n - asset (string, optional): Filter to items with at least one run on the given asset\n (VIN, module, lot, ...). Case-sensitive exact match.\n - limit (number, optional): Max results, 1-100 (default 25)\n - baseline_id (string, UUID, optional): search the project as it was at that baseline\n\nReturns:\n Matching items with @basic fields, ranked by relevance.\n\nExamples:\n - "Find braking requirements" → atoms_search(project_id, "braking system")\n - "Search for safety tests" → atoms_search(project_id, "safety", type="test-case")\n - "Tests that ran on this VIN" → atoms_search(project_id, "", asset="WEV...0005")',atoms_semantic_search:'Meaning-based search across items using pgvector embeddings (GTE-small, 384d).\n\nUse when atoms_search (exact/substring) misses conceptually related items.\nBest for natural-language concept queries; atoms_search is better for exact phrases or IDs.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Natural-language concept query (max 1000 chars)\n - type (string, optional): Filter by type\n - limit (number, optional): Max results, 1-50 (default 10)\n\nReturns:\n Semantically similar items ranked by cosine similarity.\n\nExamples:\n - "Find braking-related requirements" → atoms_semantic_search(project_id, "braking deceleration stopping distance")\n - "Safety-related test cases" → atoms_semantic_search(project_id, "hazard risk mitigation safety", type="test-case")',atoms_get_coverage:`Find requirements without linked test cases (coverage gaps).\n\nEssential for compliance reporting in safety-critical industries.\n\nIn MCP App hosts (Claude, ChatGPT), renders a visual coverage heatmap.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to analyze\n - domain (string, optional): Filter by domain\n - level (string, optional): Filter by level\n - baseline_id (string, UUID, optional): coverage at that baseline's moment\n - as_of (string ISO 8601, optional): coverage at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n { covered, uncovered, total, coverage_percent, covered_via_mitigation: { count, ids }, uncovered_items: [...] }\n\n${du}\n\nExamples:\n - "What's our test coverage?" → atoms_get_coverage(project_id)\n - "Safety coverage gaps?" → atoms_get_coverage(project_id, domain="Safety")\n - "Coverage at PDR submission" → atoms_get_coverage(project_id, baseline_id="...")`,atoms_get_history:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_<client>) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",atoms_export_mermaid:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Shows parent-child relationships\nand requirement-to-test-case verification links.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive pan/zoom diagram.\nFalls back to Mermaid text for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to visualize\n - root_item_id (string, optional): Start node (default: all roots)\n - depth (number, optional): Max depth (default 3, max 10)\n - include_tests (boolean, optional): Show test case links (default true)\n - baseline_id (string, UUID, optional): render the graph at that baseline's moment\n - as_of (string ISO 8601, optional): render the graph at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n { mermaid: string, node_count, edge_count }",atoms_create_item:`Create a new requirement, test case, 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: ${Hp}. 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. ${C} ${P}`,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 - ${_d}\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). ${cd}\n - params? (array): matrix parameters [{name, unit, values[]}], matrix points capped at 64 (DB-enforced)\n - expected_updated_at may be metadata.updated_at from atoms_get_item to reject stale writes\n - echo? (bool, default true): false gives a lean {id, updated_fields} response, saves ~580 tokens\n - reason? (string): change rationale persisted in audit history\n\nArray form (batch updates, same tool, much faster):\n - project_id, updates: [{item_id, title?, body?, summary?, domains?, level?, status?, fields?, steps?, params?, expected_updated_at?}]\n - echo? false recommended for large passes\n - reason?: applied to all history rows in the batch\n - idempotency_key?: safe to retry with same key within 24h\n - continue_on_error? (bool, default false): allow partial success\n\nbase_token: ${T}\nidempotency_key: ${C}\n${P}`,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: ${Hp}\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\nReturns:\n { created: number, items: [{ id, title, type }], errors: [] }\n\nLimits:\n - Maximum 100 items per call (500 on a project that saves one field at a time)\n - If any item fails, others still succeed — errors reported separately\n\nSide effects:\n - Logs to change_history with actor='mcp_<client>' for each created item\n - Creates parent relationships for items with parent_id\n\nOn projects that save one field at a time: the items are created in parts of at most 50, each part all or nothing. ${C} ${P}`,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: ${Xc}\n\n${rd}\n\n${ad}\n\n${nd}\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${rd}\n\n${ad}\n\n${nd}\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${Fm}\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], total_count }\n\nExamples:\n - "What does TC-003 verify?" → atoms_trace(project_id, "TC-003", "upstream")\n - "What's affected by REQ-001?" → atoms_trace(project_id, "REQ-001", "downstream")`,atoms_list_assets:"List asset identifiers registered in a project.\n\nAssets are free-form per-instance IDs (VINs, module names, lot numbers,\nserial numbers) that test runs are tagged against. They are auto-registered\nthe first time they appear on a run via atoms_record_test_result.\n\nArgs:\n - project_id (string, UUID): Project to list assets for\n - include_archived (boolean, optional): Include archived assets (default false)\n\nReturns:\n { assets: [{ id, name, archived_at, created_at }], total }",atoms_list_variables:"List all parameterized variables defined in a project.\n\nVariables are shared values (e.g., backup_camera_latency = 2s) that can be\nreferenced in requirement bodies as {variable_name}.\n\nArgs:\n - project_id (string, UUID): Project to list variables for\n - baseline_id (string, UUID, optional): list variables as they were at that baseline\n - as_of (string ISO 8601, optional): list variables as they were at that moment\n - limit (number, optional): max results (default 50, max 200)\n - offset (number, optional): pagination offset (default 0)\n\nReturns:\n { variables: [{ id, name, value, unit, description }], total }, meta: { total_count, limit, offset, has_more }",atoms_get_variable:'Get a specific variable by name, including which items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name (e.g., "backup_camera_latency")\n - baseline_id (string, UUID, optional): get the variable as it was at that baseline\n - as_of (string ISO 8601, optional): get the variable as it was at that moment\n\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',atoms_update_variable:"Update a variable's value, unit, or description.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name\n - value (string, optional): New value\n - unit (string, optional): Unit abbreviation (e.g., 's', 'Hz')\n - description (string, optional): Human-readable description\n - echo (boolean, optional, default true): false gives a lean { name, updated: true } answer\n\nReturns:\n { variable }",atoms_create_variable:'Create one or many parameterized variables for a project.\n\nSingle form: provide name + value.\nArray form: provide variables[] for bulk creation (one atomic INSERT).\n\nVariables can then be embedded in requirement bodies as {variable_name}.\n\nArgs (single form):\n - project_id (string, UUID): Project to add the variable to\n - name (string): Variable name, letters, digits, underscores; must start with letter/underscore\n - value (string): Initial value (e.g., "100", "true", "nominal")\n - unit (string, optional): Unit abbreviation (e.g., "Hz", "ms", "m/s²")\n - description (string, optional): Human-readable description\n - echo (bool, optional): false → lean {name} response (default true)\n\nArgs (array form):\n - project_id (string, UUID): Project UUID\n - variables[]: Array of { name, value, unit?, description? }\n - echo (bool, optional): false → lean {name} list (default true)\n - idempotency_key (string, optional): Dedup key\n\nReturns (single): { variable, message }\nReturns (array): { batch_id, created, variables, message }',atoms_delete_variable:"Delete a project variable. Refuses by default if any items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - name (string): Variable name to delete\n - force (bool, optional): Delete even if items still reference it (default false)\n\nReturns:\n { deleted, name, referenced_by_items, warning? }",atoms_list_levels:"List the project's level taxonomy in order, with each level's L# (positional index) and item count.\n\nArgs:\n - project_id (string, UUID): Project to list levels for\n\nReturns:\n { levels: [{ name, prefix, item_count }], total }",atoms_create_level:'Register a new level in the project taxonomy so items can be tagged with it and it shows in the Strata view. Appended to the ordered level list; its L# is the next index. Names are user-defined labels (lowercased automatically); matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID): Project to add the level to\n - name (string): Level name, e.g. "feature", "system", "subsystem"\n\nReturns:\n { level: { name, prefix }, message }',atoms_delete_level:"Delete an UNUSED level from the project taxonomy. Refuses if any item still uses the level (re-tag those items with atoms_update_item first). A level is positional, so deleting one shifts every later level's L# down by one. Matching is case-insensitive.\n\nArgs:\n - project_id (string, UUID)\n - name (string): the level to delete\n - confirmation_token (string, optional): from the first call, when confirmation is required\n\nReturns:\n { level: { name }, remaining_levels, message } — or a confirmation_required payload",atoms_reorder_levels:"Reorder the project's levels. Provide every existing level name exactly once, in the order you want them (any casing). L# is positional, so this changes every level's L# wherever it renders (Strata, sidebar, exports). Touches no item.\n\nArgs:\n - project_id (string, UUID)\n - names (string[]): every existing level name, in the new order\n\nReturns:\n { levels: [{ name, prefix }], message }",atoms_create_field:'Define a project custom field so items can carry a value for it (shown as a Matrix column, e.g. "Verification Method").\n\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${Du}\n\n${uu}\n\n${Iu}\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 } }\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${Hm}\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\nExamples:\n - "What breaks if I change REQ-001?" → atoms_impact_analysis(project_id, "REQ-001")\n - "What's upstream of TC-005?" → atoms_impact_analysis(project_id, "TC-005", direction="upstream")\n - "Show direct dependencies only" → atoms_impact_analysis(project_id, "REQ-001", depth=1)\n\nErrors:\n - "Item not found" → verify item_id exists in the project`,atoms_list_baselines:"List named baselines (named project snapshots) for a project, newest first.\n\nA baseline is a labeled moment in time. Use atoms_create_baseline to make one,\natoms_diff_baselines to compare two, and atoms_restore_baseline to roll back.\n\nArgs:\n - project_id (string, UUID)\n - limit (number, optional, default 50, max 100)\n - offset (number, optional, default 0)",atoms_create_baseline:"Create a named baseline (snapshot label) at the current moment for a project.\n\nThe baseline records a name + timestamp. It does NOT copy item data; the project\nstate at that moment is reconstructed via temporal queries against item_revisions.\nNames must be unique per project (case-insensitive).\n\nArgs:\n - project_id (string, UUID)\n - name (string, 1-200 chars, unique per project)\n - description (string, optional, max 2000)",atoms_lock_baseline:"Lock a baseline so it becomes audit-grade immutable. Admin only. One-way: there is no unlock.\n\nAfter locking, the baseline's name, description, and snapshot_at cannot be changed,\nand it cannot be deleted. Use for regulatory submissions and DRBs.\n\nArgs:\n - baseline_id (string, UUID)",atoms_diff_baselines:"Compute the diff between two baselines: which items were added, removed, or modified.\n\nReturns a summary plus a paginated items array. Each modified item lists the\nnames of the fields that changed in fields_changed. An item counts as modified exactly when the app's snapshot Compare lists it as Modified, so a difference only in metadata timestamps, the change-control review state, an empty versus an absent value or key order is not a change. With detail=true each modified item also carries a diff object keyed by every name in fields_changed, each with the from and to values. Under data, a list such as steps or runs holds only the entries that differ, keyed by the entry id (by position when entries have no id), with order giving each side's id sequence when it changed. A detail=true page is bounded to 20000 characters of items: when items are left out, page_info carries truncated: true and next_offset, so call again with that offset for the rest. Slower for large projects.\n\nArgs:\n - baseline_a_id (string, UUID)\n - baseline_b_id (string, UUID)\n - detail (boolean, optional, default false)\n - limit (number, optional, default 50, max 200)\n - offset (number, optional, default 0)",atoms_restore_baseline:"Restore project state to a baseline. Admin only. Preview-by-default.\n\nCall with confirm=false (default) for a dry run that returns items_to_restore,\nitems_to_trash and variables_to_archive, with a summary in plain words.\nCall with confirm=true to execute: each item present at the baseline gets a new\nrevision matching its historical state, event_source='restore'. The restore is\nexact: items added AFTER the baseline are moved to Trash (restorable from Trash)\nand variables added after it are archived; the answer counts items_trashed and\nvariables_archived. Every revision is kept, so a later baseline still holds them.\n\nArgs:\n - baseline_id (string, UUID)\n - confirm (boolean, optional, default false)\n\nWith confirm=false: returns { preview: true, items_to_restore: N, items_to_trash: T, variables_to_archive: V, summary }\nWith confirm=true: executes; returns { ok: true, items_restored: N, items_trashed: T, variables_archived: V, summary }",atoms_list_scenario_catalogs:"List a project's operational scenario catalogs: the situational analysis written\nand accepted before a HARA (ISO 26262) starts. Each catalog is a list of entries (operational\nscenarios), each 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 } }",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). A project\n with no industry set counts as automotive, as in the app. A variant the industry does not\n offer, an alias counting as the variant it implies, is refused before anything is written,\n naming the industry and what it offers. Analyses already in the project keep working\n whatever their variant. One exception: a project that counts as automotive but already\n holds a live medical device analysis (its industry was never chosen) is not limited and can\n keep creating the medical device analyses. A medical device project is always limited.\n Name none and the default follows the project's industry: automotive gives hara iso26262 and\n dfmea design, medical device gives hara iso14971 and dfmea process. The variant is stored on\n the analysis and selects its scheme for every later read and write; the setting never\n changes an analysis that already exists.\n - title (string, optional): Analysis title (default "New <parent label>": "New HARA",\n "New Risk analysis", "New DFMEA", "New PFMEA", "New Software FMEA", "New Use FMEA")\n - source_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${zp}`,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\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, computed_level, asil_propagated_to?, approval_cleared?,\n source_function_id?, source_function_title? }\n approval_cleared: true means the row WAS approved and this write cleared approved, approved_by,\n approved_at and approved_note: a signature never covers content the approver did not see. A\n person approves the row again with atoms_approve_row once they have read the new values.\n On the analysis parent instead: { analysis_id, scheme, written_fields,\n scope: { intended_use, foreseeable_misuse: string[], safety_characteristics: string[] },\n overall: { residual_risk, residual_rationale, safety_class, safety_rationale } }.\n\nSide effects:\n - Saves the row with stale-write protection and logs to change_history\n - On an approved row: clears the approval (history-logged with the reason)\n - ISO 26262 HARA only (scheme hara_iso26262): if the row is linked and its computed ASIL changed,\n updates the asil / asil_source of each requirement atoms_get_analysis lists in the row's\n mitigated_by, never the row itself or a test case (each update is history-logged). asil is an\n ISO 26262 field: a row of an ISO 14971 risk analysis or of a TIR57 security risk analysis never\n writes it (REQ-ANL-257)\n\n${zp}`,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 } }\n The vocabulary lists are given once per analysis, never repeated per row.\n\nA row's mitigated_by lists the live requirements that mitigate it, whichever side stored the link\n(the row's mitigated_by or the requirement's mitigates), read the way the app's analysis grid reads\nit; a link to the row itself, to a test case or to another analysis row does not count. The gap and\ncritical rules and counts.linked read this list.\n\n${Lp}`,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 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, 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${zp}`,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)\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, 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) }\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${Vp}`,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 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${Wp}`}}});var Gm=V({"src/apps/register.ts"(){Vm={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function Qm(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString().replace(/Z$/,"999Z")}var Km=V({"src/core/as-of.ts"(){}});async function Ym(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 Zm(e,t,n){let r=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0}).order("id",{ascending:!0});const a=void 0!==n.after?function(e){try{const t=JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return(new TextDecoder).decode(Uint8Array.from(n,e=>e.charCodeAt(0)))}(e));if(Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&t[0].length>0&&"string"==typeof t[1]&&t[1].length>0)return{created_at:t[0],id:t[1]}}catch{}return null}(n.after):null;if(void 0!==n.after&&null===a)throw new Xd;a&&(r=r.or(function(e){return ru(Zd,e)}(a))),n.type&&(r=r.eq("type",n.type)),n.domain&&(r=r.filter("data->tags->>domains","ilike",Ud(n.domain))),n.level&&(r=r.filter("data->tags->>level","ilike",Pd(n.level))),r=a?r.range(0,n.limit):r.range(n.offset,n.offset+n.limit);const{data:i,error:s,count:o}=await zd(r);if(s)throw new Error(s.message);const l=i??[],c=l.slice(0,n.limit),d=l.length>n.limit;return{items:c,totalCount:o??0,hasMore:d,nextCursor:d?ou(c[c.length-1]):void 0}}async function Xm(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 e_(e,t){if(t.baseline_id&&t.as_of)throw new Jt("baseline_id and as_of are mutually exclusive");if(t.as_of)return Qd(Qm(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 Jt("Baseline not found");if(n.project_id!==t.project_id)throw new Jt("Baseline does not belong to this project");return Kd(t.baseline_id)}return null}async function t_(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 n_(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 r_(e,t,n){return function(e,t,n){return"baselineId"in n?tu(()=>e.rpc("baseline_state",{p_baseline_id:n.baselineId}),Ld):au(e,"project_state_at",t,n.at)}(e,t,n).catch(e=>{throw new Error(`projectStateAt: ${e.message}`)})}async function a_(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 tu(()=>e.from("test_results").select("id, item_id").eq("project_id",t).eq("asset",n),["id"]);return[...new Set(r.map(e=>e.item_id))]}(e,t,r.asset.trim()):null;if(i&&0===i.length)return{items:[],totalCount:0};const s=()=>{let n=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${Nd(a)},data->>body.ilike.${Nd(a)},data->>summary.ilike.${Nd(a)}`);return n=void 0===r.offset?n.limit(r.limit):n.order("id",{ascending:!0}).range(r.offset,r.offset+r.limit-1),r.type&&(n=n.eq("type",r.type)),r.domain&&(n=n.filter("data->tags->>domains","ilike",Ud(r.domain))),r.level&&(n=n.filter("data->tags->>level","ilike",Pd(r.level))),n};if(i)return async function(e,t,n){const r=[];let a=0;for(let t=0;t<e.length;t+=Yd){const{data:i,error:s,count:o}=await n(e.slice(t,t+Yd));if(s)throw new Error(s.message);a+=o??0,r.push(...i??[])}return{items:r.slice(0,t),totalCount:a}}(i,r.limit,e=>s().in("id",e));const{data:o,error:l,count:c}=await zd(s());if(l)throw new Error(l.message);return{items:o??[],totalCount:c??0}}var i_=V({"src/db/queries.ts"(){eu(),io(),xu(),pu(),Hu(),Km(),zn()}}),s_={};async function o_(){try{const{projects:e,viewerOrgs:t}=await Ql(async()=>{const e=await Bl(),t=me(await ue(e,Kl()));return{projects:await Ym(e),viewerOrgs:t}}),n=Oe(),r=Re(),a=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??G).project_scope;return t.filter(e=>n(r,e.id))}return t.filter(t=>{const r="string"==typeof t.org_id?je(e,t.org_id):ke(e);return n(r.project_scope,t.id)})}(Ve(),function(e,t){return 0===t.size?e:e.filter(e=>!("string"==typeof e.org_id&&t.has(e.org_id)))}(e,t)).filter(e=>!r||e.org_id===r).filter(e=>!n||e.id===n).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}));return $l(Xo(a))}catch(e){return ql(vl(e))}}B(s_,{listProjectsHandler:()=>o_});var l_=V({"src/tools/list-projects.ts"(){ic(),ve(),i_(),Me(),Ge(),Ee(),Ml()}}),c_={};async function d_(e){try{const t=await Bl();let n,r,a=null;try{a=await e_(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return ql(vl(e))}let i=null;if(a){const i=(await r_(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=>xs(t)===xs(e.domain)))return!1}return!e.level||ls(n?.tags?.level)===ls(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 Zm(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 Uu(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:qd(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=el(r,e.limit,void 0!==e.after?0:e.offset);return i&&"boolean"==typeof i.hasMore&&(c.has_more=i.hasMore,i.nextCursor&&(c.next_cursor=i.nextCursor)),s?.scope&&(c.rerun_scope=s.scope.label),$l(Xo(l,c))}catch(e){return e instanceof Xd?ql(sl(e.message)):e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(c_,{listItemsHandler:()=>d_});var u_=V({"src/tools/list-items.ts"(){ic(),i_(),Ml(),pu(),io(),Dd(),Bu()}});function p_(e,t){return Yr(e,t)}function m_(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 __(e,t){if(t&&Xr(e,t))throw m_(t)}async function f_(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 Zl(e)}catch{t=null}return function(e){const t=function(e){const t=Vt(e);return"mcp_cursor"===t?"Cursor":"mcp_copilot"===t?"Copilot":"Claude"}(e.clientName);return{kind:"agent",user_id:e.userId,session_id:e.sessionId,label:ta(t,e.name,e.email),client:t}}({userId:Kl(),sessionId:ib(),name:t,email:Yl(),clientName:ob()})}(e),l=async n=>{const a=function(e,t){return function(e,t,n,r){const a={surface:"mcp",delivery:"npm",package_version:Nv,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 m_(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??Qr,n=function(e,t=Dn,n=Hn){return Jr(Br(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=Br(u);if(t(e)&&a.length>1){const e=Math.ceil(a.length/2),t=[Jr(a.slice(0,e),1/0,1/0)[0],Jr(a.slice(e),1/0,1/0)[0]];n.splice(d,1,...t),r+=1;continue}s=e,c=n.slice(d).flat();break}}const u=[];for(const t of e.ops){const e=i.get(t.op_id);e&&u.push(e)}return{answers:u,results:a,...r>1?{chunks:{total:r,committed:o}}:{},notSent:c,...void 0!==s?{error:s}:{}}}({ops:n,send:e=>l(e)});return void 0!==c.error&&0===c.results.length&&__("ops",c.error),c}function h_(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 y_(e){const t=e.relooked?[...e.answers]:await ra(e.client,e.projectId,e.answers),n=[...new Set(t.filter(e=>"skipped"===e.status&&"chunk_not_sent"!==e.reason&&"string"==typeof e.item_id).map(e=>e.item_id))];let r;return n.length>0&&(r=await _r(e.client,e.projectId,n)),Sr({answers:t,ops:e.ops,skippedItems:h_(e.results??[]),openRevisions:r,labels:e.labels})}function g_(e){const t=e.suggestion;return"number"==typeof t?.sg_number?t.sg_number:null}function w_(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!==g_(e)?{change:{sg_number:g_(e)}}:{}})),r={...e,applied:[...e.applied,...n]},{isError:a,result:i}=Tr(r,t);return a?ql(i):$l(i)}async function v_(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:Kl(),event_type:a,old_data:null,new_data:aa(n,r,e),actor:sb(),session_id:ib(),...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 b_(e){return e&&0!==e.length?"tags"===e[0]?"level"===e[1]?"level":"domains"===e[1]?"domains":"tags":e[0]:null}function j_(e){return"set"===e.kind?e.path:[...e.path,e.kind,String(e.row_id??er(e.value??null))]}function k_(e){return null==e?[]:"string"==typeof e?[e]:[...e]}var S_,A_=V({"src/tools/_agent-ops.ts"(){ic(),lb(),da(),Ml()}}),I_={};function x_(e,t){if(!t)return e;const n={...e};for(const e of S_){const r=t[e];null!=r&&("evidence_url"===e&&"string"==typeof r&&""===r.trim()||(n[e]=r))}return n}async function $_(e){try{const r=await Bl();let a=null;try{a=await e_(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return ql(vl(e))}let i=null;if(!a&&!0===await p_(r,e.project_id)){i={head:await hr(r,e.project_id),revision:(await _r(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?n_(e):null):await Xm(r,e.project_id,e.item_id);if(!s)return ql(nl("Item",e.item_id));const o={parents:[],children:[],related:[],verified_by:[],verifies:[],mitigated_by:[],mitigates:[],affects:[],affected_by:[]};if(a){const e=s.data?.relationships??{};for(const t of Object.keys(o)){const n=e[t];Array.isArray(n)&&(o[t]=n.slice())}}else{const t=await async function(e,t,n){const{data:r,error:a}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${n},to_id.eq.${n}`);if(a)throw new Error(a.message);return r??[]}(r,e.project_id,e.item_id),n={parent:"parents",child:"children",related:"related",verifies:"verifies",verified_by:"verified_by",mitigated_by:"mitigated_by",mitigates:"mitigates",affects:"affects",affected_by:"affected_by"},a={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",mitigated_by:"mitigates",mitigates:"mitigated_by",related:"related",affects:"affected_by",affected_by:"affects"},i=(e,t)=>{if(!(e in o))return;const n=o[e];n.includes(t)||n.push(t)},l=new Set([e.item_id]);for(const e of t)l.add(e.from_id),l.add(e.to_id);const c=s.data?.relationships??{};for(const e of Object.keys(o)){const t=c[e];if(Array.isArray(t))for(const e of t)"string"==typeof e&&l.add(e)}let d=new Set([e.item_id]);const u=Array.from(l);if(u.length>0){const{data:t,error:n}=await r.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",u);if(n)throw new Error(n.message);d=new Set((t??[]).map(e=>e.id)),d.add(e.item_id)}const p=e=>d.has(e);for(const r of t)if(r.from_id===e.item_id){if(!p(r.to_id))continue;i(n[r.type]??r.type,r.to_id)}else{if(!p(r.from_id))continue;i(a[r.type]??r.type,r.from_id)}for(const t of Object.keys(o)){const n=c[t];if(Array.isArray(n))for(const r of n)"string"==typeof r&&r!==e.item_id&&p(r)&&i(t,r)}}const l=s.data?.relationships??{},c={};for(const e of Qp){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=(Cd(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)=>wd(String(e.base.run_at),String(t.base.run_at))).slice(0,20).map(e=>x_(e.base,e.canonical));else{const{data:t,error:n}=await r.from("test_results").select("result, run_by, run_at, note, asset").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);if(!n&&t){const e=new Map;for(const t of s.data?.runs??[])"string"==typeof t?.date&&e.set(t.date,t);d=t.map(t=>x_(t,e.get(String(t.run_at))))}}const u=i&&function(e){return"requirement"===e.type&&null!==hc(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 Uu(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:{...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:qd(s),...zu(p,s.id),...yc(s,{live:null!==i,since:u}),..."test-case"===s.type?{...Ad(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 _;if(!a&&im(s.type)){const t=await xm(r,e.project_id),n=Im(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=new Map(n.map(e=>[e.id,e])),a=[...e.rowsOfGoal(t)],i=a.filter(e=>qs((r.get(e)?.data??{}).analysis_props??null)!==ci),s=[...e.satisfiers(t)],o=e.goalCoverage(t);return{asil:e.goalAsil(t),source_rows:i,events:a,functions:[...e.goalFunctions(t)],satisfied_by:s,verified_satisfiers:s.filter(t=>e.requirementVerified(t)).length,row_mitigators:[...o.rowMitigators],uncovered_rows:[...o.uncoveredRows],untested_rows:[...o.untestedRows]}}(n,s.id,t)}if(_&&Object.assign(m,{safety:_}),a||Object.assign(m,await async function(t){if(!jm(t))return{};const n=Xa(t.data);return km(t,n?await(a=n,Xm(r,e.project_id,a)):null)?bm(t.id):{};var a}(s)),i){const n=s.data?.steps,a=Array.isArray(n)?n:[],o=(await yr(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 $l(Xo({...m,...i.revision?{base_token:await cr(i.revision,"item")}:{},seq:i.head,editing_now:o,...l?{presence:l}:{}}))}return $l(Xo(m))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}var t,n}B(I_,{getItemHandler:()=>$_});var q_,E_,O_=V({"src/tools/get-item.ts"(){jc(),ic(),Dd(),Bu(),i_(),Ml(),da(),A_(),Nm(),S_=["point","release_id","build","environment","tooling","evidence_url","step_results"]}}),R_={};function M_(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:gr(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 T_(e){try{const t=await Bl(),n=await p_(t,e.project_id);if(null===n)return ql(Zr());if(!n)return ql(sl(E_));if(void 0===e.since_seq){const n=await hr(t,e.project_id);return $l(Xo({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??q_});if(a)throw a;const i=r??{};return $l(Xo({project_id:e.project_id,changes:(i.changes??[]).map(M_),last_seq:Number(i.last_seq??e.since_seq),has_more:!0===i.more}))}catch(e){return ql(vl(e))}}B(R_,{LIST_CHANGES_DEFAULT_LIMIT:()=>q_,LIST_CHANGES_NOT_NUMBERED:()=>E_,listChangesHandler:()=>T_,listedChange:()=>M_});var C_=V({"src/tools/list-changes.ts"(){ic(),da(),Ml(),A_(),q_=100,E_="This project does not number its changes yet. Use atoms_get_history for one item."}}),D_=V({"src/core/snapshot-search.ts"(){}}),H_={};async function F_(e){try{const t=await Bl();let n,r,a=null;try{a=await e_(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return ql(vl(e))}if(a){const i=function(e,t,n){const r=t.trim().toLowerCase(),a=0===r.length?[]:e.filter(e=>{if(n.type&&e.type!==n.type)return!1;const t=e.data??{};return[e.title,t.body,t.summary].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(r))});return{totalCount:a.length,items:a.slice(0,n.limit).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data}))}}(await r_(t,e.project_id,a),e.query,{type:e.type,limit:e.limit});r=i.totalCount,n=i.items}else{const a=await a_(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});n=a.items,r=a.totalCount}return $l(Xo(n.map(e=>({id:e.id,title:e.title,type:e.type,status:qd(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),el(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(H_,{searchHandler:()=>F_});var N_=V({"src/tools/search.ts"(){ic(),i_(),D_(),Ml(),Dd()}}),P_={};async function U_(e){try{const t=await Bl(),{access_token:n}=await Pt(),{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(()=>(Rt(),At)),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 $l(Xo(r.map(e=>({id:e.id,title:e.title,type:e.type,status:qd(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),el(a,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(P_,{semanticSearchHandler:()=>U_});var z_=V({"src/tools/semantic-search.ts"(){ic(),Lt(),i_(),Ml(),Dd()}}),L_={};async function W_(e){try{if(e.baseline_id&&e.as_of)return ql(sl("baseline_id and as_of are mutually exclusive"));const t=await Bl();let n;if(e.baseline_id){const r=await t_(t,e.baseline_id);if(!r)return ql(sl("Baseline not found"));if(r.project_id!==e.project_id)return ql(sl("Baseline does not belong to this project"));n=Kd(e.baseline_id)}else e.as_of&&(n=Qd(Qm(e.as_of)));const{covered:r,uncovered:a,total:i,mitigators:s}=await async function(e,t,n){let r,a,i;if(n.moment){const s=(await r_(e,t,n.moment)).map(n_);r=s.filter(e=>"requirement"===e.type),a=s.map(e=>({id:e.id,type:e.type,data:e.data})),i=[]}else r=await tu(()=>e.from("items").select("*").eq("project_id",t).eq("type","requirement").is("deleted_at",null),Ld),a=await tu(()=>e.from("items").select("id, type, data").eq("project_id",t).is("deleted_at",null),Ld),i=await tu(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t),Wd);const s=r.filter(e=>!(n.domain&&!(e.data?.tags?.domains??[]).some(e=>xs(e)===xs(n.domain))||n.level&&ls(e.data?.tags?.level)!==ls(n.level))),o=Ou(a,i),l=_u(a,o),c=s.filter(e=>l.has(e.id)),d=s.filter(e=>!l.has(e.id)),u=hu(a,o);return{covered:c,uncovered:d,total:s.length,mitigators:u}}(t,e.project_id,{domain:e.domain,level:e.level,moment:n}),o=a.map(e=>{const t=function(e,t){if(mu(e))return[...t?.get(e.id)??[]]}(e,s);return{id:e.id,title:e.title,type:e.type,status:qd(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,...t?{mitigated_by:t}:{}}});return $l(Xo({covered:r.length,uncovered:a.length,total:i,coverage_percent:$u(r.length,i),covered_via_mitigation:ku(a,s),uncovered_items:o}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(L_,{getCoverageHandler:()=>W_});var V_,B_,J_=V({"src/tools/get-coverage.ts"(){ic(),i_(),Km(),pu(),Ml(),Dd(),Eu(),xu()}}),G_={};async function Q_(e,t,n){const r=await tu(()=>e.from("items").select("id").eq("project_id",t).eq("type","requirement").is("deleted_at",null),Ld);return(await su(r.map(e=>e.id),r=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:n,p_requirement_ids:r}))).sort(B_)}async function K_(e){try{const t=await Bl();let n=null;if(e.release_id){const r=await t_(t,e.release_id);if(!r)return ql(sl(`Release ${e.release_id} not found`));if(r.project_id!==e.project_id)return ql(sl("Release does not belong to this project"));if(null===r.release_version)return ql(tl(`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 ql(kl(a.message));n=r}if(!n)return $l(Xo({release:null,rerun:await Q_(t,e.project_id,null),hint:V_}),{complete:!0});const{data:r,error:a}=await t.rpc("verification_readiness",{p_project_id:e.project_id,p_release_id:n.id});if(a)return ql(vl(a));const i=n.id,s=(await tu(()=>t.from("verification_status").select("requirement_id, state, stale, points_total, points_run").eq("project_id",e.project_id).eq("release_id",i),["requirement_id"])).slice().sort(B_),o={release:{id:n.id,version:n.release_version,status:n.release_status},readiness:r??{},requirements:s,rerun:await Q_(t,e.project_id,i),...0===s.length?{hint:"projection empty; an admin may need to run rebuild_verification_from_runs for this project"}:{}};return e.include_gaps&&(o.gaps=await tu(()=>t.rpc("verification_notrun_points",{p_project_id:e.project_id,p_release_id:i}),["tc_id","asset","point_key"])),$l(Xo(o),{complete:!0})}catch(e){return ql(vl(e))}}B(G_,{verificationStatusHandler:()=>K_});var Y_,Z_,X_,ef=V({"src/tools/verification-status.ts"(){ic(),i_(),pu(),Ml(),V_="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).",B_=(e,t)=>e.requirement_id<t.requirement_id?-1:e.requirement_id>t.requirement_id?1:0}});function tf(e){return"string"==typeof e&&""!==e.trim()?e:null}function nf(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 rf(e){return e.map((t,n)=>{const r=e[n+1]??null,a=1===t.revision_number||null===r,i="system"===t.event_source?"system_normalization":1===t.revision_number?"created":"updated",s=a?["(created)"]:function(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]),r=[];for(const a of n)JSON.stringify(e[a])!==JSON.stringify(t[a])&&r.push(a);return r}(nf(r?.fields_snapshot),nf(t.fields_snapshot)),o=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=tf(t.from_tag),r=tf(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?Z_:"hazard_goal_model_revert"===t.kind?X_:tf(e.history)??Y_}(t.diff_summary);return{id:t.id,event_type:i,changed_by:null===o?t.changed_by??null:null,changed_at:t.valid_from,actor:null!==o?"system":"mcp"===t.event_source?"mcp_claude":"user",session_id:t.event_session_id??null,fields_changed:s,...null!==o?{summary:o}:{}}})}var af=V({"src/core/history.ts"(){Y_="Changed by a data migration run",Z_="Moved to the Hazard and Safety goal model by conversion",X_="Moved back from the Hazard and Safety goal model by revert"}}),sf={};async function of(e){try{const t=await Bl(),n=await async function(e,t,n,r){const{data:a,error:i}=await e.from("item_revisions").select("id, revision_number, fields_snapshot, valid_from, changed_by, event_source, event_session_id, diff_summary").eq("item_id",n).eq("project_id",t).order("revision_number",{ascending:!1}).limit(r);if(i)throw new Error(i.message);return a??[]}(t,e.project_id,e.item_id,e.limit);if(n.length>0){const t=rf(n);return $l(Xo(t,el(t.length,e.limit,0)))}const r=await async function(e,t,n,r){const{data:a,error:i}=await e.from("change_history").select("*").eq("item_id",n).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r);if(i)throw new Error(i.message);return a??[]}(t,e.project_id,e.item_id,e.limit),a=r.map(e=>{const t=[],n=e.old_data,r=e.new_data;if(n&&r){const e=new Set([...Object.keys(n),...Object.keys(r)]);for(const a of e)JSON.stringify(n[a])!==JSON.stringify(r[a])&&t.push(a)}else r?t.push("(created)"):n&&t.push("(deleted)");return{id:e.id,event_type:e.event_type,changed_by:e.changed_by??null,changed_at:e.changed_at,actor:e.actor??"user",session_id:e.session_id??null,fields_changed:t}});return $l(Xo(a,el(a.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(sf,{getHistoryHandler:()=>of});var lf=V({"src/tools/get-history.ts"(){ic(),i_(),af(),Ml()}});function cf(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function df(e){const t=mf(`${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 uf(e){const t=cf(e.from_id),n=cf(e.to_id);return"child"===e.type?`${t} --\x3e ${n}`:"verified_by"===e.type?`${t} -.-> ${n}`:"related"===e.type?`${t} -.- ${n}`:"allocated_to"===e.type?`${t} -- allocated to --\x3e ${n}`:"allocated_from"===e.type?`${n} -- allocated to --\x3e ${t}`:"event_hazard"===e.type?`${t} -- hazard --\x3e ${n}`:"hazard_events"===e.type?`${n} -- hazard --\x3e ${t}`:"event_goal"===e.type?`${t} -- goal --\x3e ${n}`:"goal_events"===e.type?`${n} -- goal --\x3e ${t}`:null}function pf(e){return"allocated_from"===e.type?`${e.to_id}:allocated_to:${e.from_id}`:"hazard_events"===e.type?`${e.to_id}:event_hazard:${e.from_id}`:"goal_events"===e.type?`${e.to_id}:event_goal:${e.from_id}`:`${e.from_id}:${e.type}:${e.to_id}`}function mf(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var _f=V({"src/core/mermaid.ts"(){}}),ff={};async function hf(e){try{if(e.baseline_id&&e.as_of)return ql(sl("baseline_id and as_of are mutually exclusive"));const t=await Bl();let n,r,a;if(e.baseline_id){const r=await t_(t,e.baseline_id);if(!r)return ql(sl("Baseline not found"));if(r.project_id!==e.project_id)return ql(sl("Baseline does not belong to this project"));n=Kd(e.baseline_id)}else e.as_of&&(n=Qd(Qm(e.as_of)));if(n){r=(await r_(t,e.project_id,n)).map(n_).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),a=Ou(r,[])}else r=await tu(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),Ld),a=Ou(r,await tu(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),Wd));return $l(Xo(function(e){const t=e.items,n=e.relationships??[],r=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${mf(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(` ${cf(t)}${df(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=uf(c);if(!u)continue;const p=pf(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")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(ff,{exportMermaidHandler:()=>hf});var yf,gf,wf=V({"src/tools/export-mermaid.ts"(){ic(),i_(),Ml(),_f(),Km(),pu()}}),vf=V({"src/core/item-types.ts"(){yf={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 bf(e){const t=function(e){return Object.prototype.hasOwnProperty.call(yf,e)?yf[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 jf(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 kf(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>gf)throw new Error(`ID generation failed: at most ${gf} 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 Sf=V({"src/core/item-id-reservation.ts"(){vf(),gf=1e3}});async function Af(e,t){const n=await Yr(e,t);return null===n?"unreadable":n?"ops":"main"}function If(){return ql(Zr())}async function xf(e){const t=[...e.ops];let n=e.preFound??new Map;!e.preFound&&e.deterministic&&t.length>0&&(n=await na(e.client,e.projectId,t.map(e=>e.op_id)));const r=t.filter(e=>!n.has(e.op_id));let a={answers:[],results:[],notSent:[]};if(r.length>0&&(a=await async function(e,t,n,r={}){return f_(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 ra(e.client,e.projectId,a.answers),s=function(e,t,n){const r=new Map(t.map(e=>[e.op_id,e]));return e.map(e=>{if(null!==e.item_id&&void 0!==e.item_id)return e;if("string"==typeof e.name&&e.name.length>0)return e;const t=r.get(e.op_id);if(!t||null!==t.item_id)return e;let a;if("taxonomy"===t.path[0])a="rename"===t.kind?String(t.base??""):"move_row"===t.kind?String(t.row_id??""):t.path[2]&&"is_function"===t.path[3]?t.path[2]:"string"==typeof t.value?t.value:void 0;else if("variables"===t.path[0]){const e=t.path[1]??("string"==typeof t.row_id?t.row_id:void 0);a="add"===t.kind?String(t.value?.name??""):e?n?.get(e):void 0}return a?{...e,name:a}:e})}([...e.refusals??[],...n.values(),...i,...Kr(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 _r(e.client,e.projectId,l)),{outcome:await Sr({answers:s,ops:t,skippedItems:o,...c?{openRevisions:c}:{},...e.labels?{labels:e.labels}:{}}),answers:s,results:a.results,chunks:a.chunks,found:n}}function $f(e,t,n,r){if(0===e.not_applied.length)return $l(Xo({...t,...r??{},...Cr(e),...n?{chunks:n}:{}}));const{isError:a,result:i}=Tr(e,{...r??{},...n?{chunks:n}:{}});return a?ql(i):$l(i)}function qf(e,t,n){return e&&!t?Xr(e,n):null}function Ef(e){return null==e?[]:(Array.isArray(e)?[...e]:[e]).filter(e=>"string"==typeof e&&e.length>0)}function Of(e){return e.some(e=>void 0!==e.acceptance_revoked&&null!==e.acceptance_revoked&&!1!==e.acceptance_revoked)}async function Rf(e){const t=await vr({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(wr(t.path));a&&r.push(jr({op_id:Hr(),kind:"set",item_id:e.itemId,path:[...t.path],value:t.value},a))}return{ops:r,refusals:t.refusals}}async function Mf(e){const t=Kl(),n=ib(),r=Lr(e.contents),a=[],i=[];for(let s=0;s<e.contents.length;s+=1)a.push(await Dr(e.key?Nr({userId:t,projectId:e.projectId,family:zr(e.tool),key:e.key,itemIdOrK:s}):Fr({userId:t,projectId:e.projectId,content:e.contents[s],k:r[s],sessionId:n}))),i.push(await Dr(e.key?Nr({userId:t,projectId:e.projectId,family:zr(e.tool),key:e.key,itemIdOrK:`link:${s}`,path:["relationships","children"]}):[t,e.projectId,"create_link",a[s]]));return{create:a,link:i}}async function Tf(e,t,n){const r=n.filter(e=>e.item_id&&"string"==typeof e.revision_id&&e.revision_id.length>0),a=new Map;if(0===r.length)return a;const i=await fr(e,t,r.map(e=>e.revision_id));for(const e of r){const t=i.get(e.revision_id);t&&a.set(e.item_id,await cr(t,"all"))}return a}async function Cf(e){let t=0,n=0;for(;;){let r;try{r=await xf({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 Df(e,t,n){return e.answers.find(e=>e.status===t&&(void 0===n||e.reason===n))}var Hf,Ff,Nf=V({"src/tools/_ops.ts"(){ic(),lb(),da(),Ml(),A_()}});function Pf(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!!xe(Ve(),t).require_confirmation_for.includes(e)}function Uf(e,t=Hf){const n=Date.now()+t,r={...e,exp:n},a=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${a}.${p.createHmac("sha256",Ff).update(a).digest("base64url")}`,expires_at:new Date(n).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function zf(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=p.createHmac("sha256",Ff).update(n).digest("base64url"),i=Buffer.from(r,"utf8"),s=Buffer.from(a,"utf8");if(i.length!==s.length||!p.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 Lf(e){if(Array.isArray(e))return e.map(Lf);if(null!==e&&"object"==typeof e){const t={};for(const n of Object.keys(e).sort())t[n]=Lf(e[n]);return t}return e}function Wf(e){const t=JSON.stringify(Lf(e));return p.createHash("sha256").update(t).digest("base64url").slice(0,16)}var Vf,Bf=V({"src/middleware/confirmation.ts"(){Ge(),Ee(),Hf=6e4,Ff=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:p.randomBytes(32).toString("base64url")})()}});function Jf(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=>ls(e)===ls(i))??s.find(e=>r(e)===a)??t}function Gf(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 Qf=V({"src/core/levels.ts"(){io(),go(),Vf="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."}}),Kf={};function Yf(e){const t=Zo(e??"");return"sub-system"===t?"subsystem":t}async function Zf(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 Xf(e,t){return{levels:await Zf(e,t)}}async function eh(e,t){return(await tu(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),Ld)).map(e=>e.data?.tags?.level)}async function th(e,t,n){const r=Zo(n);return r?Jf(n,r,await Zf(e,t),Yf):r}async function nh(e,t,n){const r=Zo(n??""),a=Yf(r);if(!r)return"none";try{const{levels:n}=await Xf(e,t);if(n.some(e=>Yf(e)===a))return"present";if(!te(xe(Ve(),t),"atoms_create_level").allowed)return"locked";if(!0===await Yr(e,t)){const n={op_id:Hr(),kind:"add",item_id:null,path:["taxonomy","levels"],value:r},{run:a}=await Cf({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 rh(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 ah(e){try{const t=await Bl(),{levels:n}=await Xf(t,e.project_id),r=function(e,t,n){const r=new Set(e.map(e=>ls(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(ls(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 eh(t,e.project_id),Yf),a=r.some(e=>void 0!==e.items_not_shown);return $l(Xo({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?` ${Vf}`:"")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}async function ih(e,t){let n;try{const r=await Bl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const a=t??await Af(r,e.project_id);if("unreadable"===a)return If();n=a;const{levels:i}=await Xf(r,e.project_id),s=Zo(e.name),o=Yf(s);if(!s)return ql(sl("Level name cannot be empty."));if(i.some(e=>Yf(e)===o))return ql(sl(`Level "${s}" already exists in this project.`));if("ops"===a){const t={op_id:Hr(),kind:"add",item_id:null,path:["taxonomy","levels"],value:s},{run:n}=await Cf({client:r,projectId:e.project_id,op:t});if(n.answers.some(e=>"noop"===e.status))return ql(sl(`Level "${s}" already exists in this project.`));if(n.outcome.not_applied.length>0)return $f(n.outcome,{},n.chunks);const a=(await Zf(r,e.project_id)).findIndex(e=>Yf(e)===o),l=`L${a>=0?a:i.length}`;return $f(n.outcome,{level:{name:s,prefix:l},message:`Level "${s}" registered as ${l}. Tag items with level="${s}".`},n.chunks)}const l=async()=>{const{data:t,error:n}=await r.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"add",p_values:[s]});if(n)throw new Error(n.message);const a=t?.levels??[...i,s],l=a.includes(s)?void 0:a.find(e=>Yf(e)===o);if(void 0!==l){const e=`L${a.indexOf(l)}`;return $l(Xo({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 $l(Xo({level:{name:s,prefix:d},message:`Level "${s}" registered as ${d}. Tag items with level="${s}".`}))};return await l()}catch(r){const a=qf(n,t,r);return a?ih(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}async function sh(e,t){let n;try{const r=await Bl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const a=t??await Af(r,e.project_id);if("unreadable"===a)return If();n=a;const i=Yf(Al(e.name));if(!i)return ql(sl("Level name cannot be empty."));const{levels:s}=await Xf(r,e.project_id),o=s.filter(e=>Yf(e)===i),l="ops"===a?0:(await eh(r,e.project_id)).filter(e=>Yf(e)===i).length;if(0===o.length&&0===l&&"ops"!==a)return ql(nl("Level",e.name));const c=o[0]??e.name;if(l>0)return ql(sl(`Level "${c}" is used by ${l} item${l>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`));if(Pf("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=Uf(t);return $l(Xo({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=zf(e.confirmation_token,t);if(!n.valid)return ql(sl(`confirmation_token rejected: ${n.reason}`))}if("ops"===a){const t={op_id:Hr(),kind:"remove",item_id:null,path:["taxonomy","levels"],value:c},{run:n}=await Cf({client:r,projectId:e.project_id,op:t}),a=Df(n,"invalid","level_in_use");if(a){const e="number"==typeof a.count?a.count:1;return ql(sl(`Level "${c}" is used by ${e} item${e>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`))}if(Df(n,"deleted"))return ql(nl("Level",e.name));if(n.outcome.not_applied.length>0)return $f(n.outcome,{},n.chunks);const i=await Zf(r,e.project_id),o=cs(s,i);return $f(n.outcome,{level:{name:c},remaining_levels:i,message:`Level "${c}" deleted. Every later level's L# shifts down by one.`+(o?" "+o:"")},n.chunks)}const d=async()=>{const{data:t,error:n}=await r.rpc("mutate_project_levels",{p_project_id:e.project_id,p_action:"remove",p_values:o});if(n)throw new Error(n.message);const a=t?.levels??[],i=cs(s,a);return $l(Xo({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=qf(n,t,r);return a?sh(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}async function oh(e,t){let n;try{const r=await Bl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const a=t??await Af(r,e.project_id);if("unreadable"===a)return If();n=a;const i=Array.isArray(e.names)?e.names.map(e=>Al(String(e??"")).trim()).filter(e=>e.length>0):[];if(0===i.length)return ql(sl("names must be a non-empty array of the project's existing levels, in the order you want them."));const{levels:s}=await Xf(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=>ls(t)===ls(e))??a(t=>""!==n(t)&&n(t)===n(e));if(null===t)return null;i.push(t)}return i}(s,i,Yf);if(!o)return ql(sl(`names must list every existing level exactly once. Levels: ${s.length>0?s.join(", "):"(none)"}`));if("ops"===a){const t=rh(s,o);if(t.length>0){const n=t.map(e=>({op_id:Hr(),kind:"move_row",item_id:null,path:["taxonomy","levels"],row_id:e.level,value:{after:e.after}})),a=await xf({client:r,projectId:e.project_id,ops:n});if(Df(a,"deleted"))return ql(nl("Level",e.names.join(", ")));if(a.outcome.not_applied.length>0)return $f(a.outcome,{},a.chunks)}const n=await Zf(r,e.project_id),a=cs(s,n);return $l(Xo({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=cs(s,a);return $l(Xo({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=qf(n,t,r);return a?oh(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}B(Kf,{createLevelHandler:()=>ih,deleteLevelHandler:()=>sh,ensureLevelRegistered:()=>nh,getProjectLevels:()=>Zf,levelKey:()=>Yf,levelMoves:()=>rh,listLevelsHandler:()=>ah,reorderLevelsHandler:()=>oh,storedLevelSpelling:()=>th});var lh,ch,dh,uh,ph,mh,_h,fh,hh=V({"src/tools/levels.ts"(){ic(),da(),Nf(),Bf(),Ml(),io(),de(),Ee(),Ge(),pu(),Qf()}});function yh(e,t,n){const[r,a]="affects"===n?[e,t]:[t,e];return r.startsWith(uh)&&a.startsWith(ph)?null:`affects/affected_by links a security risk analysis row (${uh}n) to an ISO 14971 risk row (${ph}n) only: "${e}" -> "${t}" is not that pair.`}function gh(e,t,n){const r=[t,n].filter(mh);if(0===r.length)return null;const a=`"${t.id}" -> "${n.id}"`;if(_h(e)){const r=mh(t)?n:t;return mh(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(mh(t)&&mh(n))return null;const r=mh(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 fh(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 wh(e,t,n,r){return gh("parent",{id:e,type:t},{id:n,type:r})}async function vh(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 bh(e,t,n,r){const a=n.filter(e=>"add"===e.action),i=a.filter(e=>_h(e.type)||fh(e.type)||"parent"===e.type||"child"===e.type);if(0===i.length)return null;const s=e=>e.startsWith(lh),o=a.some(e=>_h(e.type));if(!o&&!i.some(e=>s(e.from_id)||s(e.to_id)))return null;if(o){const n=Qu(await Ju(e,t));if(n)return{toolError:n}}const l=await async function(e,t,n,r){const a=n.filter(e=>"add"===e.action&&(_h(e.type)||fh(e.type)||"parent"===e.type||"child"===e.type));if(0===a.length)return null;const i=await vh(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=gh(e.type,t,n);if(r)return r}return null}(e,t,n,r);return l?{validation:l}:null}var jh,kh,Sh,Ah,Ih=V({"src/core/link-pairs.ts"(){op(),io(),lh="FN-",ch=["allocated_to","allocated_from"],dh=["verifies","verified_by","mitigated_by","mitigates","affects","affected_by"],uh=`${qi.security_tir57}-`,ph=`${qi.hazard_iso14971}-`,mh=e=>"function"===e.type,_h=e=>ch.includes(e),fh=e=>dh.includes(e)}}),xh=V({"src/core/project-field-counts.ts"(){pu()}});function $h(e){if(!Array.isArray(e))return;const t=new Set(e.filter(e=>"string"==typeof e&&Sh.has(e)));return 0!==t.size?jh.filter(e=>t.has(e)):void 0}var qh,Eh,Oh=V({"src/core/field-scope.ts"(){jh=["requirement","test-case","note","table","function"],kh=["requirement","test-case","note","table"],Sh=new Set(jh),Ah=e=>JSON.stringify({type:e.type,options:e.options??[],appliesTo:e.appliesTo??null})}}),Rh={};async function Mh(e,t){const{data:n,error:r}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(r)throw r;return Th(n?.fields)}function Th(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&&Eh.has(e.type)?e.type:"text",o=Array.isArray(e.options)?Wh(e.options):[],l=$h(e.appliesTo??e.applies_to);t.push({name:a,type:s,..."select"===s?{options:o}:{},...l?{appliesTo:l}:{}})}return t}function Ch(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(!Eh.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=Wh(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 Dh(e,t){const n=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!n.has(e.toLowerCase()))}function Hh(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 Fh(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 Nh(e,t,n=new Set,r){const a=Dh(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(Fh(r,e,a)){a.trim()&&(i[t.name]=a);continue}const o=Ph(t,a,n);if(o.error)return{error:o.error};o.value&&(i[t.name]=o.value)}return{fields:i}}function Ph(e,t,n){const r=t.trim();if(!r)return{value:""};if(r.length>1e4)return{error:`${e.name} is too long.`};switch(e.type){case"text":case"long":return{value:r};case"bool":{const t=r.toLowerCase();return"yes"===t?{value:"yes"}:"no"===t?{value:"no"}:{error:`${e.name} must be yes or no.`}}case"date":return function(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;const t=new Date(`${e}T00:00:00.000Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}(r)?{value:r}:{error:`${e.name} must be an ISO date.`};case"person":return Lh(r)&&n.has(r)?{value:r}:{error:`${e.name} must be an active project member ID.`};case"select":return(e.options??[]).includes(r)?{value:r}:{error:`${e.name} must be one of: ${(e.options??[]).join(", ")}.`};case"number":return Number.isFinite(Number(r))?{value:r}:{error:`${e.name} must be numeric.`};case"link":{const t=function(e){if(!e)return{label:"",url:""};try{const t=JSON.parse(e);if(t&&"object"==typeof t&&"string"==typeof t.url){const e=t.label;return{label:"string"==typeof e?e:"",url:t.url}}}catch{}return{label:"",url:e}}(r);return function(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}(t.url)?{value:Uh(t.label,t.url)}:{error:`${e.name} must be an http(s) URL.`}}}}function Uh(e,t){const n=t.trim();return n?JSON.stringify({label:e.trim(),url:n}):""}async function zh(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(Fh(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(!Lh(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:Kl()});if(i)return{error:i.message};!0===a&&o.add(n)}return Nh(n,r,o,a)}function Lh(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 Wh(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 Vh(e){try{const t=await Bl(),n=await Mh(t,e.project_id),r=await async function(e,t,n){const r=Object.fromEntries(n.map(e=>[e.name,0])),a=new Map(n.map(e=>[e.name.toLowerCase(),e.name])),i=await tu(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),Ld);for(const e of i){const t=e.data?.fields;if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,n]of Object.entries(t)){const t=a.get(e.toLowerCase());t&&"string"==typeof n&&n.length>0&&(r[t]+=1)}}return r}(t,e.project_id,n);return $l(Xo({fields:n.map(e=>({name:e.name,type:e.type,options:e.options??[],...e.appliesTo?{appliesTo:e.appliesTo}:{},item_count:r[e.name]??0})),total:n.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(vl(e))}}async function Bh(e,t){let n;try{const r=await Bl();try{await nc(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return ql(nn("project"));throw e}const a=t??await Af(r,e.project_id);if("unreadable"===a)return If();n=a;const{data:i}=await r.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),s=Th(i?.fields),o=$h(e.appliesTo),l={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:Wh(e.options??[])}:{},...o?{appliesTo:o}:{}},c=Ch(l,function(e,t,n){if(!n)return e;const r=t.name.toLowerCase();return e.some(e=>e.name.toLowerCase()===r&&Ah(e)===Ah(t))?e.filter(e=>e.name.toLowerCase()!==r):e}(s,l,"ops"===a));if(c)return ql(sl(c));const d=function(e,t){return"organization"!==e?null:t&&0!==t.length?kh.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 ql(sl(d));if(o?.includes("function")){const t=Qu(await Ju(r,e.project_id));if(t)return ql(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:Kl()}):await r.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"create",p_field:"ops"===a?{...l,op_id:Hr()}:l,p_field_name:null,p_actor_user_id:Kl()});if(p)throw p;return $l(Xo({field:u?.field??l,..."organization"===e.scope?{created_projects:u?.created_projects??[],skipped_projects:u?.skipped_projects??[]}:{},message:`Field "${l.name}" defined. Set values with atoms_update_item fields={"${l.name}": "<value>"}.`}))}catch(r){const a=qf(n,t,r);return a?Bh(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(vl(r))}}async function Jh(e,t){let n;try{const r=await Bl();try{await nc(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return ql(nn("project"));throw e}const a=t??await Af(r,e.project_id);if("unreadable"===a)return If();n=a;const i=e.name.trim(),{data:s,error:o}=await r.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"delete",p_field:"ops"===a?{op_id:Hr()}:null,p_field_name:i,p_actor_user_id:Kl()});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),$l(Xo({deleted:s?.deleted??i}))}catch(r){const a=qf(n,t,r);return a?Jh(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(vl(r))}}async function Gh(e){try{const t=await Bl();try{await nc(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return ql(nn("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 ql(sl("names must be a non-empty array of existing field names, in the order you want them"));const r=await Mh(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 ql(sl(`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:Kl()});if(o)throw o;return $l(Xo({fields:Th(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(vl(e))}}B(Rh,{PROJECT_FIELD_TYPES:()=>qh,canonicalizeFieldKeys:()=>Hh,createFieldHandler:()=>Bh,deleteFieldHandler:()=>Jh,findUnknownFieldNames:()=>Dh,getProjectFields:()=>Mh,isStoredFieldValue:()=>Fh,listFieldsHandler:()=>Vh,normalizeProjectFields:()=>Th,reorderFieldsHandler:()=>Gh,validateAndCanonicalizeFieldValues:()=>Nh,validateProjectFieldDefinition:()=>Ch,validateProjectFieldValuesForWrite:()=>zh});var Qh=V({"src/tools/fields.ts"(){ic(),Ml(),xh(),zn(),da(),Nf(),op(),Oh(),qh=["text","long","bool","date","person","select","number","link"],Eh=new Set(qh)}}),Kh={};async function Yh(e){try{const t=await Bl();try{await tc(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const n=await p_(t,e.project_id);if(null===n)return ql(Zr());if(e.type=am(e.type),im(e.type)){const n=await lm(t,e.project_id);if(n)return ql(n);const r="goal"===e.type?ym(Object.keys(e.fields??{})):[];if(r.length>0)return ql(sl(gm("A Safety goal",r),Lo))}e.title=Al(e.title),void 0!==e.body&&(e.body=Al(e.body)),void 0!==e.summary&&(e.summary=Al(e.summary)),void 0!==e.level&&(e.level=Al(e.level)),e.domains&&(e.domains=e.domains.map(e=>Al(e)));const r=(e.domains??[]).map(Zo).filter(e=>e.length>0),a=void 0!==e.level?await th(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=eo(r,Xs(n?.function_tags),Zo);if(s.length>0)return ql(sl(to(s),Lo));if(i.length>0){const e=new Set(i.map(Zo).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return ql(sl(`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(()=>(Qh(),Rh)),a=await n(t,e.project_id),s=await r(t,e.project_id,a,e.fields);if(s.error)return ql(sl(s.error));i=s.fields}if(void 0!==e.req_type){const t=Sc(e.req_type,e.type);if(t)return ql(sl(t,Lo))}if("function"===e.type){const n=Qu(await Ju(t,e.project_id));if(n)return ql(n);const r=await async function(e,t,n,r,a){if(0===r.length)return null;const i=await vh(e,t,r,a);for(const e of r){const t=i.get(e);if(!t)continue;const r=wh("the new item",n,t.id,t.type);if(r)return r}return null}(t,e.project_id,e.type,e.parent_ids??[],su);if(r)return ql(sl(r))}const s={sanitizedDomains:r,sanitizedLevel:a,canonicalFields:i};return await ea(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=Kl(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n,o=[...new Set(t.parent_ids??[])],l=Vr({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=zr("atoms_create_item"),u=await Dr(c?Nr({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:[]}):Fr({userId:r,projectId:t.project_id,content:l,k:0,sessionId:ib()})),p=(await na(e,t.project_id,[u])).get(u);if(p&&("applied"===p.status||"noop"===p.status)&&p.item_id)return $l(Xo({id:p.item_id,type:t.type,title:t.title,project_id:t.project_id,replayed:!0,message:Pn,seq:p.seq??null}));const m=(await kf(e,t.project_id,{[bf(t.type)]:1}))[bf(t.type)][0],_={summary:t.summary,body:t.body,...t.req_type?{req_type:t.req_type}:{},tags:{domains:a,level:i??""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],...s?{fields:s}:{}},f=[{op_id:u,kind:"create_item",item_id:m,path:[],value:{type:t.type,title:t.title,data:_}}];for(const e of o)f.push({op_id:c?await Dr(Nr({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:["relationships","parents","add",e]})):Hr(),kind:"add",item_id:m,path:["relationships","parents"],value:e});const h=await f_(e,t.project_id,f,{mode:"single"});if(void 0!==h.error&&0===h.results.length)throw h.error;const y=await ra(e,t.project_id,h.answers),g=await y_({client:e,projectId:t.project_id,answers:y,ops:f,results:h.results,relooked:!0});await v_(e,t.project_id,f,y,"created");const w=y.find(e=>e.op_id===u);if("invalid"===w?.status&&"op_id_reused"===w.reason)return ql(tl(Nn,["Send the call again with a new idempotency_key, or without one"],{code:"op_id_reused",retryable:!1}));if(g.not_applied.length>0)return w_(g,{id:m,type:t.type});const v=w?.item_id??m,b=!0===w?.replayed,j=w?.revision_id??null;let k;if(j){const n=(await fr(e,t.project_id,[j])).get(j);n&&(k=await cr(n,"all"))}const S={id:v,type:t.type},A={...k?{base_token:k}:{},...Cr(g),...b?{replayed:!0,message:Pn}:{}};return!1===t.echo?$l(Xo({...S,...A})):$l(Xo({...S,title:t.title,summary:t.summary??"",body:t.body??"",...t.req_type?{req_type:t.req_type}:{},domains:a,level:i??"",project_id:t.project_id,...A}))}(t,e,s):async function(e,t,n){const r=Kl(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n;{const n=bf(t.type),l=async()=>(await kf(e,t.project_id,{[n]:1}))[n][0],c=(new Date).toISOString(),d=e=>({id:e,type:t.type,title:t.title,summary:t.summary,body:t.body,...t.req_type?{req_type:t.req_type}:{},tags:{domains:a,level:i??""},ownership:{primary:null,additional:[]},relationships:{parents:t.parent_ids??[],children:[],related:[],verifies:[],verified_by:[]},links:[],...s?{fields:s}:{},metadata:{created_at:c,created_by:r,updated_at:c,updated_by:r}}),u=n=>e.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:t.project_id,p_type:t.type,p_title:t.title,p_data:n,p_user_id:r,p_event_source:"mcp",p_event_session_id:ib()??null,p_diff_summary:null});let p=await l(),m=d(p),{error:_}=await u(m);if(_&&(o=_)&&/^item_exists\b/.test(String(o.message??"").trim())&&(p=await l(),m=d(p),({error:_}=await u(m))),__("main",_),_)throw new Error(_.message);const f=i?Gf(i,await nh(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 Io(()=>e.rpc("apply_link_change",{p_project_id:t.project_id,p_from_id:p,p_to_id:n,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"}));a&&(process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${n}: ${a.message}\n`),h.push({parent_id:n,message:a.message}))}const y=h.length>0?{link_warnings:h,warning:`${p} was created but could not be attached to ${h.map(e=>e.parent_id).join(", ")}. Repair: call atoms_link_items with type 'parent', from_id=${p}, to_id=<parent id>. Do not create the item again.`}:{};return await e.from("change_history").insert({item_id:p,project_id:t.project_id,changed_by:r,event_type:"created",old_data:null,new_data:m,actor:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===t.echo?$l(Xo({id:p,type:t.type,...f?{level_note:f}:{},...y})):$l(Xo({id:p,type:t.type,title:t.title,summary:t.summary??"",body:t.body??"",...t.req_type?{req_type:t.req_type}:{},domains:a,level:i??"",project_id:t.project_id,...f?{level_note:f}:{},...y}))}var o}(t,e,s))}catch(e){const t=bl(e);return ql(t||vl(e))}}B(Kh,{createItemHandler:()=>Yh});var Zh=V({"src/tools/create-item.ts"(){ic(),Sf(),lb(),Ml(),hh(),Qf(),io(),qc(),op(),Nm(),Ih(),pu(),To(),da(),A_(),Ml()}});function Xh(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 ey(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 ty,ny=V({"src/core/change-control.ts"(){}});var ry,ay,iy=V({"src/core/content-ids.ts"(){ty={row:"r",column:"c",step:"st",param:"p"}}});function sy(e,t){const n=ry[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)+sy(e.slice(r),t.slice(r))}const r=e?ry.indexOf(e[0]):0,a=null!==t?ry.indexOf(t[0]):ry.length;return a-r>1?ry[Math.round(.5*(r+a))]:t&&t.length>1?t.slice(0,1):ry[r]+sy(e.slice(1),null)}function oy(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 ly(e){if(e.length!==oy(e[0]))throw new Error(`invalid integer part of order key: ${e}`)}function cy(e){const t=oy(e[0]);if(t>e.length)throw new Error(`invalid order key: ${e}`);return e.slice(0,t)}function dy(e){if(e===ay)throw new Error(`invalid order key: ${e}`);const t=cy(e);if(e.slice(t.length).slice(-1)===ry[0])throw new Error(`invalid order key: ${e}`)}function uy(e){ly(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=ry.indexOf(n[e])+1;t===ry.length?n[e]=ry[0]:(n[e]=ry[t],r=!1)}if(r){if("Z"===t)return`a${ry[0]}`;if("z"===t)return null;const e=String.fromCharCode(t.charCodeAt(0)+1);return e>"a"?n.push(ry[0]):n.pop(),e+n.join("")}return t+n.join("")}function py(e,t){if(null!==e&&dy(e),null!==t&&dy(t),null!==e&&null!==t&&e>=t)throw new Error(`${e} >= ${t}`);if(null===e){if(null===t)return`a${ry[0]}`;const e=cy(t),n=t.slice(e.length);if(e===ay)return e+sy("",n);if(e<t)return e;const r=function(e){ly(e);const t=e[0],n=e.slice(1).split(""),r=ry[ry.length-1];let a=!0;for(let e=n.length-1;a&&e>=0;e-=1){const t=ry.indexOf(n[e])-1;-1===t?n[e]=r:(n[e]=ry[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=cy(e),n=e.slice(t.length),r=uy(t);return null===r?t+sy(n,null):r}const n=cy(e),r=e.slice(n.length),a=cy(t),i=t.slice(a.length);if(n===a)return n+sy(r,i);const s=uy(n);if(null===s)throw new Error("cannot increment any more");return s<t?s:n+sy(r,null)}function my(e,t,n){return py(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 _y,fy,hy=V({"src/core/order-key.ts"(){iy(),ry="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ay=`A${"0".repeat(26)}`}});function yy(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gy(e,t){return e<t?-1:e>t?1:0}function wy(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)=>wy(e,t[n]));if(yy(e)&&yy(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=>wy(e[n],t[n]))}return!1}function vy(e){return yy(e)&&"string"==typeof e.id?`id:${e.id}`:`json:${by(e)}`}function by(e){return Array.isArray(e)?`[${e.map(by).join(",")}]`:yy(e)?`{${Object.keys(e).filter(t=>void 0!==e[t]).sort(gy).map(t=>`${JSON.stringify(t)}:${by(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function jy(e,t,n,r={}){if(r.skip?.(e))return[];if(1===e.length&&"relationships"===e[0]?(yy(t)||(t={}),yy(n)||(n={})):2===e.length&&"relationships"===e[0]&&(Array.isArray(t)||(t=[]),Array.isArray(n)||(n=[])),wy(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(vy)),s=new Set(a.map(vy)),o=[];for(const t of r)s.has(vy(t))||o.push({kind:"remove",path:[...e],value:t});for(const t of a)i.has(vy(t))||o.push({kind:"add",path:[...e],value:t});return o}(e,t,n);if(yy(t)&&yy(n)){const a=new Set([...Object.keys(t),...Object.keys(n)]),i=[];for(const s of[...a].sort(gy))0===e.length&&r.ignoreKeys?.has(s)||i.push(...jy([...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 ky(e){const t={};for(const n of Object.keys(e))_y.has(n)||void 0===e[n]||(t[n]=e[n]);return t}function Sy(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[py(null,t)];{let e=py(null,t);const r=[e];for(let a=0;a<n-1;a+=1)e=py(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`${ty[e]}_${n}`}(fy[e])),p.add(r),r}),_=m.map(e=>u.get(e)??-1),f=_.flatMap((e,t)=>e>=0?[t]:[]),h=new Set(function(e){const t=[],n=new Array(e.length).fill(-1);for(let r=0;r<e.length;r+=1){let a=0,i=t.length;for(;a<i;){const n=a+i>>1;e[t[n]]<e[r]?a=n+1:i=n}a>0&&(n[r]=t[a-1]),t[a]=r}const r=[];for(let e=t.length?t[t.length-1]:-1;e>=0;e=n[e])r.push(e);return r.reverse()}(f.map(e=>_[e])).map(e=>f[e])),y=[],g=new Set(m);t.forEach((t,n)=>{""===d[n]||u.get(d[n])!==n||g.has(d[n])||y.push({kind:s,path:[e],base:t,row_id:d[n]})});const w=[...l],v=new Array(n.length).fill(null);for(let e=0;e<n.length;e+=1)h.has(e)&&(v[e]=l[_[e]]);for(let t=0;t<n.length;t+=1){if(null!==v[t])continue;const r=t>0?v[t-1]:null;let s=null;for(let e=t+1;e<n.length;e+=1)if(h.has(e)){s=v[e];break}const o=my(w,r,s);w.push(o),v[t]=o,_[t]<0?y.push({kind:a,path:[e],value:ky(n[t]),row_id:m[t],order_key:o}):y.push({kind:i,path:[e],base:l[_[t]],row_id:m[t],order_key:o})}for(let a=0;a<n.length;a+=1)_[a]<0||y.push(...jy([e,m[a]],ky(t[_[a]]),ky(n[a]),{skip:r.skip}));return y}var Ay=V({"src/core/content-ops.ts"(){iy(),hy(),_y=new Set(["id","order_key","created_seq"]),fy={steps:"step",params:"param",rows:"row",columns:"column"}}}),Iy={};async function xy(e){try{const n=await Bl();try{await tc(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const r=await p_(n,e.project_id);if(null===r)return ql(Zr());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?ql({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 ea(r?"ops":"main",t=>"ops"===t?async function(e,t){const n=Kl(),r=Array.isArray(t.updates);if(!r&&!t.item_id)return ql(sl("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(gc(n));const a=await $y(e,t.project_id,n,c,s),d=k_(c.base_token??(r?t.base_token:void 0));if("entry"in a){o.push({itemId:n,tokens:d,intent:c.intent??t.intent??"edit",...a.entry});continue}const{message:u,path:p,notFound:m,long:_}=a.refusal;if(!r)return ql(m?nl("Item",n):sl(u,_?Lo:void 0));if(!i)return ql(sl(`Batch stopped at "${n}": ${u.replace(/\.$/,"")}. Nothing was saved.`,_?Lo: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 vr({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(wr(n));if(a)for(const t of qy(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 Dr(Nr({userId:n,projectId:t.project_id,family:zr("atoms_update_item"),key:t.idempotency_key,itemIdOrK:e.item_id??"",path:j_(e)})):Hr();let _={answers:[],results:[],notSent:[]};if(m.length>0&&(_=await f_(e,t.project_id,m,{mode:c}),void 0!==_.error&&0===_.results.length))throw _.error;const f=[...l,...p,..._.answers,...Kr(_.notSent)],h=new Map;for(const e of o)Array.isArray(e.steps)&&e.steps.forEach((e,t)=>{e?.id&&h.set(e.id,t+1)});const y=await y_({client:e,projectId:t.project_id,answers:f,ops:m,results:_.results,labels:{stepNumber:e=>h.get(e)}}),g=r?crypto.randomUUID():void 0;if(await v_(e,t.project_id,m,_.answers,"updated",{batch_id:g,reason:t.reason}),y.not_applied.length>0)return w_(y,r?{batch_id:g}:{id:t.item_id});const w=new Map;for(const e of[...y.applied]){if(!e.item_id)continue;const t=b_(e.path),n=w.get(e.item_id)??[];t&&!n.includes(t)&&n.push(t),w.set(e.item_id,n)}const v=new Map;for(const e of y.captured)e.item_id&&v.set(e.item_id,g_(e));const b=Of(_.answers)?{acceptance_revoked:!0}:{};if(r){const e=o.map(e=>v.has(e.itemId)?null!==v.get(e.itemId)?Xh(e.itemId,v.get(e.itemId)):ey(e.itemId):{id:e.itemId,updated_fields:w.get(e.itemId)??[]});return $l(Xo({batch_id:g,updated:e.length,results:!1===t.echo?void 0:e,errors:[],...b,...Cr(y)}))}const j=t.item_id;if(v.has(j)){const e=v.get(j);return $l(Xo(null!=e?Xh(j,e):ey(j)))}const k=w.get(j)??[];if(!1===t.echo)return $l(Xo({id:j,updated_fields:k,...b,...Cr(y)}));const S=(await _r(e,t.project_id,[j])).get(j),A=S?.fields_snapshot??{},I=A.data??{};return $l(Xo({id:j,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:k,...S?{base_token:await cr(S,"core")}:{},...b,...Cr(y)}))}(n,e):async function(e,t){{const n=Kl(),r=async(r,a,i,s)=>{const o=await Xm(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&&Ed(o))return{updated_fields:[],error:Od(r)};if(void 0!==a.status&&Rd(o,a.status))return{updated_fields:[],error:Md(r)};void 0!==a.title&&(a.title=Al(a.title)),void 0!==a.body&&(a.body=Al(a.body)),void 0!==a.summary&&(a.summary=Al(a.summary)),void 0!==a.level&&(a.level=Al(a.level)),void 0!==a.domains&&(a.domains=a.domains.map(e=>Al(e))),void 0!==a.steps&&(a.steps=Id(a.steps,e=>Al(e))),void 0!==a.params&&(a.params=$d(Id(a.params,e=>Al(e)),o.data.params));const c=void 0!==a.domains?a.domains.map(Zo).filter(e=>e.length>0):void 0,d=void 0!==a.level?await th(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=eo(c,Xs(n?.function_tags),Zo);if(i.length>0)return{updated_fields:[],error:to(i)};if(a.length>0){const e=new Set(a.map(Zo).filter(e=>e.length>0)),t=c.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const u={...o.data},p={...o.data},m=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==a.title&&_(o.data.title,a.title)&&(p.title=a.title,m.push("title")),void 0!==a.body&&_(o.data.body,a.body)&&(p.body=a.body,m.push("body")),void 0!==a.summary&&_(o.data.summary,a.summary)&&(p.summary=a.summary,m.push("summary")),void 0!==c&&_(o.data.tags?.domains??[],c)&&(p.tags={...p.tags,domains:c},m.push("domains")),void 0!==d&&_(o.data.tags?.level,d)&&(p.tags={...p.tags,level:d},m.push("level")),void 0!==a.status&&_(o.data.status,a.status)&&(p.status=a.status,m.push("status")),void 0!==a.req_type){const e=Sc(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?ym(Object.keys(a.fields)):[];if(n.length>0)return{updated_fields:[],error:gm(o.id,n)};const{getProjectFields:r,validateProjectFieldValuesForWrite:i,canonicalizeFieldKeys:s}=await Promise.resolve().then(()=>(Qh(),Rh)),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;_(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 f=a.title??o.title,{data:h,error:y}=await e.rpc("save_item_with_revision",{p_item_id:r,p_project_id:t.project_id,p_type:o.type,p_title:f,p_data:p,p_user_id:n,p_event_source:"mcp",p_event_session_id:ib()??null,p_diff_summary:null,p_expected_updated_at:a.expected_updated_at??o.updated_at});if(__("main",y),y)return{updated_fields:[],error:y};if(!h)return{updated_fields:[],error:`Update silently failed for "${r}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};const g=m.includes("level")&&d?Gf(d,await nh(e,t.project_id,d)):null,w={item_id:r,project_id:t.project_id,changed_by:n,event_type:"updated",old_data:u,new_data:p,actor:sb(),session_id:ib()};if(i&&(w.batch_id=i),s&&(w.reason=s),await e.from("change_history").insert(w).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),l&&function(e){return e.some(e=>"title"===e||"body"===e||"type"===e)}(m)){const n=await async function(e,t,n){const{data:r,error:a}=await e.from("item_suggestions").select("sg_number").eq("project_id",t).eq("item_id",n).eq("status","open").maybeSingle();return a||!r?null:"number"==typeof r.sg_number?r.sg_number:null}(e,t.project_id,r);return null!==n?{updated_fields:m,updatedData:p,itemType:o.type,capturedSg:n}:{updated_fields:m,updatedData:p,itemType:o.type,capturedUnknown:!0}}return{updated_fields:m,updatedData:p,itemType:o.type,...g?{levelNote:g}:{}}};if(t.updates&&Array.isArray(t.updates)){const e=crypto.randomUUID(),n=!0===t.continue_on_error,a=[],i=[];for(const s of t.updates){const{updated_fields:o,capturedSg:l,capturedUnknown:c,error:d,levelNote:u}=await r(s.item_id,s,e,t.reason);if(d){if(jl(d))return ql(vl(d));if(!n){const e=d instanceof Error?d.message:String("object"==typeof d&&d&&"message"in d?d.message??"":d),t=re(e);return ql(null!==t?{...t,message:`Batch stopped at "${s.item_id}": ${t.message} ${a.length} item(s) already updated.`}:sl(`Batch stopped at "${s.item_id}": ${e.replace(/\.$/,"")}. ${a.length} item(s) already updated.`,e.includes("Function-flagged tag")||kc(e)?Lo:void 0))}i.push({item_id:s.item_id,error:String(d)})}else void 0!==l?a.push(Xh(s.item_id,l)):c?a.push(ey(s.item_id)):a.push({id:s.item_id,updated_fields:o,...u?{level_note:u}:{}})}const s=[...new Set(a.flatMap(e=>"level_note"in e&&e.level_note?[e.level_note]:[]))];return $l(Xo({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 ql(sl("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:a,updatedData:i,itemType:s,capturedSg:o,capturedUnknown:l,error:c,levelNote:d}=await r(t.item_id,{title:t.title,body:t.body,summary:t.summary,domains:t.domains,level:t.level,status:t.status,req_type:t.req_type,fields:t.fields,steps:t.steps,params:t.params,expected_updated_at:t.expected_updated_at},void 0,t.reason);if(c){const e=c instanceof Error?c.message:String("object"==typeof c&&c&&"message"in c?c.message??"":c);return e.includes("not found")?ql(nl("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(pd)||e.includes(md)}(e)?ql(sl(e,e.includes("Function-flagged tag")||kc(e)?Lo:void 0)):_l(e)||jl(c)?ql(vl(c)):ql(kl(e))}if(void 0!==o)return $l(Xo(Xh(t.item_id,o)));if(l)return $l(Xo(ey(t.item_id)));if(!1===t.echo)return $l(Xo({id:t.item_id,updated_fields:a,...d?{level_note:d}:{}}));const u=i??{};return $l(Xo({id:t.item_id,type:s,title:u.title??"",summary:u.summary??"",body:u.body??"",domains:u.tags?.domains??[],level:u.tags?.level??"",...u.req_type?{req_type:u.req_type}:{},updated_fields:a,...d?{level_note:d}:{}}))}}(n,e))}catch(e){const t=bl(e);return ql(t||vl(e))}var t}async function $y(e,t,n,r,a){const i=await Xm(e,t,n);if(!i)return{refusal:{message:`Item "${n}" not found`,path:null,notFound:!0}};if(void 0!==r.status&&Ed(i))return{refusal:{message:Od(n),path:["status"]}};if(void 0!==r.status&&Rd(i,r.status))return{refusal:{message:Md(n),path:["status"]}};const s=[],o=[],l=(e,t)=>{s.push(e),o.push(t)};if(void 0!==r.title&&l(["title"],Al(r.title)),void 0!==r.summary&&l(["summary"],Al(r.summary)),void 0!==r.body&&l(["body"],Al(r.body)),void 0!==r.req_type){const e=Sc(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 th(e,t,Al(r.level))),void 0!==r.domains){const e=r.domains.map(e=>Zo(Al(e))).filter(e=>e.length>0);if(e.length>0){const t=await a.read(),n=eo(e,Xs(t.function_tags),Zo);if(n.length>0)return{refusal:{message:to(n),path:["tags","domains"],long:!0}};if(t.domains.length>0){const n=new Set(t.domains.map(Zo).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?ym(Object.keys(r.fields)):[];if(a.length>0)return{refusal:{message:gm(n,a),path:["fields"],long:!0}};const{getProjectFields:s,validateProjectFieldValuesForWrite:o,canonicalizeFieldKeys:c}=await Promise.resolve().then(()=>(Qh(),Rh)),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"],Id(r.steps,e=>Al(e))),void 0!==r.params&&l(["params"],Id(r.params,e=>Al(e))),{entry:{paths:s,values:o,type:i.type,steps:i.data.steps}}}function qy(e,t,n){const r=e=>Array.isArray(e)?e:[];return 1===e.length&&"steps"===e[0]?function(e,t){return Sy("steps",e??[],t??[])}(r(t),r(n)):1===e.length&&"params"===e[0]?function(e,t){return Sy("params",e??[],t??[],{implicitIds:!0})}(r(t),r($d(n,t))):jy([...e],void 0===t?null:t,n)}B(Iy,{updateItemHandler:()=>xy});var Ey,Oy=V({"src/tools/update-item.ts"(){jc(),ic(),i_(),lb(),qc(),de(),Dd(),Ml(),hh(),Qf(),ny(),io(),da(),Ay(),A_(),Ml(),Nm(),Nf()}}),Ry={};async function My(e){try{const t=await Bl();Kl();try{await tc(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const n=await p_(t,e.project_id);if(null===n)return ql(Zr());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 ql(nl("Item",e.item_id));if(r.deleted_at)return ql(sl(`Item ${e.item_id} is already deleted`));if(Pf(Ey,e.project_id)){const t={tool:Ey,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const n=Uf(t);return $l(Xo({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=zf(e.confirmation_token,t);if(!n.valid)return ql(sl(`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 ea(n?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:Hr(),kind:"trash_item",item_id:t.item_id,path:[]}],a=await f_(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await y_({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await v_(e,t.project_id,r,a.answers,"deleted"),i.not_applied.length>0?w_(i,{id:t.item_id}):$l(Xo({...n,...Cr(i)}))}(t,e,a):async function(e,t,n,r){const a=Kl(),{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:sb(),p_session_id:ib()});if(__("main",i),i)throw new Error(i.message);return $l(Xo(r))}(t,e,r,a))}catch(e){const t=bl(e);return ql(t||vl(e))}}B(Ry,{deleteItemHandler:()=>My});var Ty=V({"src/tools/delete-item.ts"(){ic(),i_(),lb(),Bf(),Ml(),da(),A_(),Ml(),Ey="atoms_delete_item"}}),Cy={};async function Dy(e){try{const t=await Bl(),n=Kl();try{await tc(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const r=await p_(t,e.project_id);if(null===r)return ql(Zr());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 ql(nl("Item",e.item_id));if(!a.deleted_at){if(!r){const n=await Hy(t,e.project_id,e.item_id);if(n.error)return ql(Do(e.item_id,Fy(n)))}return ql({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 ql(Co());if(!0!==e.confirm)return $l(function(e){const t=e.days_in_trash??0;return{status:"needs_confirmation",message:`${e.item_id} "${e.title??""}" is in Trash. ${Ho(e)} moved it there on ${Fo(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:[...Oo],id:e.item_id,title:e.title??"",restored:!1,trashed_by:Ho(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:No(l,n)};return await ea(r?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:Hr(),kind:"restore_item",item_id:t.item_id,path:[]}],a=await f_(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await y_({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await v_(e,t.project_id,r,a.answers,"restored"),i.not_applied.length>0?w_(i,{id:t.item_id}):$l(Xo({...n,...Cr(i)}))}(t,e,c):async function(e,t,n,r){const a=Kl(),{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:ib()??null});if(__("main",i),i)throw i;const s=await Hy(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:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),s.error?ql(Do(t.item_id,Fy(s))):$l(Xo(r))}(t,e,a,c))}catch(e){const t=bl(e);return ql(t||vl(e))}}function Hy(e,t,n){return xo(()=>e.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:t,p_item_id:n}))}function Fy(e){return{message:e.error?.message??"",code:e.error?.code??null,status:e.status}}B(Cy,{restoreItemHandler:()=>Dy});var Ny,Py=V({"src/tools/restore-item.ts"(){ic(),lb(),Qo(),To(),Ml(),da(),A_(),Ml()}}),Uy={};async function zy(e){try{const t=await Bl(),n=Kl();try{await tc(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}let r;const a=async()=>void 0===r?r=await p_(t,e.project_id):r,i=async(r,a,i)=>{const s=await Xm(t,e.project_id,r.from_id);if(!s)throw new Error(`Item "${r.from_id}" not found`);const o=await Xm(t,e.project_id,r.to_id);if(!o)throw new Error(`Item "${r.to_id}" not found`);const{error:l}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r.from_id,p_to_id:r.to_id,p_type:r.type,p_action:r.action,p_user_id:n,p_event_source:"mcp",p_expected_from_updated_at:r.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:r.expected_to_updated_at??o.updated_at});if(__("main",l),l)throw new Error(l.message);if("affects"===r.type||"affected_by"===r.type)for(const r of[s,o]){const a=Xa(r.data);if(!a)continue;const i=await Xm(t,e.project_id,a);if(!i)continue;const{revoked:s,parentProps:o}=ei(i.data);if(!s)continue;const l={...i.data,analysis_props:o},{error:c}=await t.rpc("save_item_with_revision",{p_item_id:i.id,p_project_id:e.project_id,p_type:i.type,p_title:i.title,p_data:l,p_user_id:n,p_event_source:"mcp",p_event_session_id:ib()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});c&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${i.id}': ${c.message}\n`)}const c={item_id:r.from_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:null,new_data:{relationship_change:{action:r.action,type:r.type,from:r.from_id,to:r.to_id}},actor:sb(),session_id:ib()};a&&(c.batch_id=a),i&&(c.reason=i),await t.from("change_history").insert(c).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})};if(e.operations&&Array.isArray(e.operations)){for(const t of e.operations){if(t.from_id===t.to_id)return ql(sl(`Self-reference in batch: "${t.from_id}"`));if("affects"===t.type||"affected_by"===t.type){const e=yh(t.from_id,t.to_id,t.type);if(e)return ql(sl(e))}}const n=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],r=await su(n,n=>t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",n)),s=new Set(r.map(e=>e.id)),o=n.filter(e=>!s.has(e));if(o.length>0)return ql(nl("Items",o.join(", ")));const l=await bh(t,e.project_id,e.operations,su);if(l)return ql("toolError"in l?l.toolError:sl(`${l.validation} No changes applied.`));const c=await tu(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id).eq("type","parent"),Wd),d=new Map;for(const e of c)"parent"===e.type&&(d.has(e.from_id)||d.set(e.from_id,new Set),d.get(e.from_id).add(e.to_id));for(const t of e.operations){if("parent"!==t.type&&"child"!==t.type)continue;const[e,n]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?d.get(e)?.delete(n):(d.has(e)||d.set(e,new Set),d.get(e).add(n))}const u=0,p=1,m=2,_=new Map,f=new Set;for(const[e,t]of d){f.add(e);for(const e of t)f.add(e)}const h=e=>{if((_.get(e)??u)!==u)return null;const t=[],n=[],r=e=>{_.set(e,p),n.push(e),t.push({node:e,parents:[...d.get(e)??[]],idx:0})};for(r(e);t.length>0;){const e=t[t.length-1];if(e.idx>=e.parents.length){_.set(e.node,m),n.pop(),t.pop();continue}const a=e.parents[e.idx];e.idx++;const i=_.get(a)??u;if(i===p){const e=n.indexOf(a);return[...n.slice(e),a]}i!==m&&r(a)}return null};for(const e of f){const t=h(e);if(t)return ql(sl(`Batch would create a cycle: ${t.join(" -> ")}. No changes applied.`))}const y=e.operations,g=await a();return null===g?ql(Zr()):await ea(g?"ops":"main",async n=>{if("ops"===n)return Ly(t,e,y,!0);const r=crypto.randomUUID(),a=[...y.filter(e=>"remove"===e.action),...y.filter(e=>"add"===e.action)],s=[],o=e=>`${e.action} ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`;for(const t of a){try{await i(t,r,e.reason)}catch(e){if(Xr("main",e))throw e;const n=vl(e);return ql({...n,message:`${n.message}\n\nThis batch is not atomic: its operations are applied one at a time. ${s.length} of ${a.length} operation(s) committed before this one failed and were NOT rolled back (batch ${r}). Committed: ${s.length?s.map(o).join("; "):"none"}. Failed: ${o(t)}.`,next_steps:rn(s.length,n)})}s.push(t)}return $l(Xo({batch_id:r,processed:y.length,operations:!1===e.echo?void 0:y}))})}if(!(e.from_id&&e.to_id&&e.type&&e.action))return ql(sl("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."));if(e.from_id===e.to_id)return ql(sl("Cannot create a relationship between an item and itself"));if("affects"===e.type||"affected_by"===e.type){const t=yh(e.from_id,e.to_id,e.type);if(t)return ql(sl(t))}const s=await bh(t,e.project_id,[{action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type}],su);if(s)return ql("toolError"in s?s.toolError:sl(s.validation));const o={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},l=await a();return null===l?ql(Zr()):await ea(l?"ops":"main",async n=>"ops"===n?Ly(t,e,[o],!1):(await i(o,void 0,e.reason),!1===e.echo?$l(Xo({action:o.action,from_id:o.from_id,to_id:o.to_id})):$l(Xo({action:o.action,type:o.type,from_id:o.from_id,to_id:o.to_id,message:`Relationship ${"add"===o.action?"added":"removed"}: ${o.from_id} --[${o.type}]--\x3e ${o.to_id}`}))))}catch(e){const t=bl(e);return ql(t||vl(e))}}async function Ly(e,t,n,r){const a=Kl(),i=[];for(const e of n){const n={op_id:"",kind:e.action,item_id:e.from_id,path:["relationships",Ny[e.type]],value:e.to_id};n.op_id=t.idempotency_key?await Dr(Nr({userId:a,projectId:t.project_id,family:zr("atoms_link_items"),key:t.idempotency_key,itemIdOrK:e.from_id,path:j_(n)})):Hr(),i.push(n)}const s=await f_(e,t.project_id,i);if(void 0!==s.error&&0===s.results.length)throw s.error;const o=await y_({client:e,projectId:t.project_id,answers:[...s.answers,...Kr(s.notSent)],ops:i,results:s.results}),l=r?crypto.randomUUID():void 0;if(await v_(e,t.project_id,i,s.answers,"updated",{batch_id:l,reason:t.reason}),o.not_applied.length>0)return w_(o,r?{batch_id:l}:{});if(r)return $l(Xo({batch_id:l,processed:n.length,operations:!1===t.echo?void 0:n,...Cr(o)}));const c=n[0];return!1===t.echo?$l(Xo({action:c.action,from_id:c.from_id,to_id:c.to_id,...Cr(o)})):$l(Xo({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}`,...Cr(o)}))}B(Uy,{linkItemsHandler:()=>zy});var Wy,Vy,By=V({"src/tools/link-items.ts"(){ic(),i_(),pu(),lb(),ns(),zn(),Ml(),da(),A_(),Ml(),Ih(),Ny={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"}}}),Jy=V({"src/core/bulk-parent-links.ts"(){To()}}),Gy={};function Qy(e){return new Set(["22023","23503","23505","23514"]).has(e.code??"")}function Ky(e,t){return e.items.length>t?ql(sl(`Maximum ${t} items per call (received ${e.items.length}). Split into multiple calls.`)):null}async function Yy(e){try{if(!e.items||0===e.items.length)return ql(sl("items array must contain at least 1 item"));const t=Ky(e,Wy);if(t)return t;const n=await Bl();try{await tc(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const r=await p_(n,e.project_id);if(null===r)return ql(Zr());if(!r){const t=Ky(e,Vy);if(t)return t}if(e.items.some(e=>"function"===e.type)){const t=Qu(await Ju(n,e.project_id));if(t)return ql(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 vh(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=wh("the new item",e.type,n.id,n.type);if(r)return{index:t,message:r}}return null}(n,e.project_id,e.items,su);if(r)return ql(sl(`Nothing was imported. items[${r.index}]: ${r.message}`))}if(e.items=e.items.map(e=>({...e,type:am(e.type)})),e.items.some(e=>im(e.type))){const t=await lm(n,e.project_id);if(t)return ql(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=Xs(r?.function_tags),o=i.length>0?new Set(i.map(Zo).filter(e=>e.length>0)):null,l=Wf(i.map(Zo).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(Zo).filter(e=>e.length>0);if(0===r.length)continue;const a=eo(r,s,Zo);if(a.length>0){d.add(e),c.push({index:e,title:t.title,error:to(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(Pf("atoms_bulk_import",e.project_id)){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:Wf({items:e.items,registered_domain_hash:a.registeredDomainHash})};if(!e.confirmation_token){const n=Uf(t);return $l(Xo({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=zf(e.confirmation_token,t);if(!n.valid)return ql(sl(`confirmation_token rejected: ${n.reason}`))}return await ea(r?"ops":"main",t=>"ops"===t?async function(e,t,n){const r=Kl(),a=t.idempotency_key,i=zr("atoms_bulk_import"),s=t.items.some(e=>void 0!==e.level)?await Zf(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(Zo).filter(e=>e.length>0),r=void 0!==e.level?Jf(e.level,Zo(e.level),s,Yf):void 0;return{input:e,index:t,domains:n,level:r,content:Vr({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=Lr(o.map(e=>e.content)),c=[];for(let e=0;e<o.length;e+=1)c.push(await Dr(a?Nr({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:o[e].index,path:[]}):Fr({userId:r,projectId:t.project_id,content:o[e].content,k:l[e],sessionId:ib()})));const d=await na(e,t.project_id,c),u=[],p=[];o.forEach((e,t)=>{const n=d.get(c[t]);n&&("applied"===n.status||"noop"===n.status)&&n.item_id?u.push({id:n.item_id,title:e.input.title,type:e.input.type,replayed:!0}):p.push({v:e,createId:c[t]})});const m=[...n.errors],_=[],f=new Map;if(p.length>0){const n={};for(const{v:e}of p){const t=bf(e.input.type);n[t]=(n[t]??0)+1}const s=jf(await kf(e,t.project_id,n));for(const{v:e,createId:n}of p){const o=s(bf(e.input.type));f.set(o,{title:e.input.title,type:e.input.type});const l={summary:e.input.summary,body:e.input.body,tags:{domains:e.domains,level:e.level??""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[]},links:[]};_.push({op_id:n,kind:"create_item",item_id:o,path:[],value:{type:e.input.type,title:e.input.title,data:l}}),e.input.parent_id&&_.push({op_id:a?await Dr(Nr({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:e.index,path:["relationships","parents","add",e.input.parent_id]})):Hr(),kind:"add",item_id:o,path:["relationships","parents"],value:e.input.parent_id})}}let h={answers:[],results:[],notSent:[]};if(_.length>0&&(h=await f_(e,t.project_id,_,{mode:"bulk"}),void 0!==h.error&&0===h.results.length))throw h.error;const y=[...await ra(e,t.project_id,h.answers),...Kr(h.notSent)],g=await y_({client:e,projectId:t.project_id,answers:y,ops:_,results:h.results,relooked:!0});await v_(e,t.project_id,_,y,"created");const w=[...u];for(const e of y){if(!e.item_id||!e.path||0!==e.path.length)continue;if("applied"!==e.status&&"noop"!==e.status)continue;const t=f.get(e.item_id);t&&w.push({id:e.item_id,title:t.title,type:t.type,...e.replayed?{replayed:!0}:{}})}const v=w.length>0&&w.every(e=>e.replayed),b={created:w.length,items:w,errors:m,project_id:t.project_id,...h.chunks?{chunks:h.chunks}:{},...void 0!==h.error?{error:vl(h.error).message}:{},...v?{replayed:!0,message:Pn}:{}};return g.not_applied.length>0?w_(w.length>0&&0===g.applied.length?{...g,applied:w.map(e=>({item_id:e.id,path:[],status:"applied",seq:null,replayed:!0}))}:g,b):$l(Xo({...b,...Cr(g)}))}(n,e,a):async function(e,t,n){const r=Kl();{const a=(new Date).toISOString(),i=ib(),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=bf(e.type);d[t]=(d[t]??0)+1}let u=null,p=null;try{u=jf(await kf(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(bf(e))},_=t.items.some(e=>void 0!==e.level)?await Zf(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(Zo).filter(e=>e.length>0),i=void 0!==r.level?Jf(r.level,Zo(r.level),_,Yf):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 $l(Xo({created:0,items:[],errors:o}));const f=[],h=new Map;for(const{itemId:e,input:n,sanitizedDomains:i,sanitizedLevel:s}of l){const o={id:e,type:n.type,title:n.title,summary:n.summary,body:n.body,tags:{domains:i,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:n.parent_id?[n.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:a,created_by:r,updated_at:a,updated_by:r}};h.set(e,o),f.push({id:e,project_id:t.project_id,type:n.type,title:n.title,data:o,created_by:r,updated_by:r})}const y=f.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:g}=await e.rpc("bulk_save_items_with_revisions",{p_project_id:t.project_id,p_items:y,p_user_id:r,p_event_source:"mcp"});if(__("main",g),g&&Qy(g))for(const{itemId:n,input:a,index:c}of l){const l=f.find(e=>e.id===n);if(!l)continue;const{error:d}=await e.rpc("save_item_with_revision",{p_item_id:l.id,p_project_id:t.project_id,p_type:l.type,p_title:l.title,p_data:l.data,p_user_id:r,p_event_source:"mcp",p_event_session_id:i,p_diff_summary:null});d?o.push({index:c,title:a.title,error:d.message}):s.push({id:n,title:a.title,type:a.type})}else{if(g)throw g;for(const{itemId:e,input:t}of l)s.push({id:e,title:t.title,type:t.type})}const w=l.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:e,input:n})=>({from_id:e,to_id:n.parent_id,type:"parent",project_id:t.project_id}));await async function(e){for(const t of e.links){const{error:n}=await e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:t.from,p_to_id:t.to,p_type:"parent",p_action:"add",p_user_id:e.userId,p_event_source:"mcp"});n&&e.warn(`bulk parent link sync failed for ${t.to}: ${n.message??"unknown error"}`)}}({client:e,projectId:t.project_id,links:w.map(e=>({from:e.from_id,to:e.to_id})),userId:r,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}),s.length>0&&await async function(e){try{const{data:t,error:n}=await xo(()=>e.client.rpc("repair_project_link_rows_unless_busy",{p_project_id:e.projectId}));n?e.warn(`link repair after the import failed: ${n.message??"unknown error"}`):null==t&&e.warn("link repair after the import skipped: the project is being restored, moved to the Trash or relinked")}catch(t){e.warn(`link repair after the import failed: ${t instanceof Error?t.message:String(t)}`)}}({client:e,projectId:t.project_id,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const v=s.map(e=>({item_id:e.id,project_id:t.project_id,changed_by:r,event_type:"created",old_data:null,new_data:h.get(e.id)??null,actor:sb(),session_id:i}));v.length>0&&await e.from("change_history").insert(v).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const b=new Set(s.map(e=>e.id)),j=new Set(l.filter(({itemId:e,sanitizedLevel:t})=>t&&b.has(e)).map(({sanitizedLevel:e})=>e)),k=[];for(const n of j){const r=Gf(n,await nh(e,t.project_id,n));r&&k.push(r)}return $l(Xo({created:s.length,items:s,errors:o.length>0?o:[],project_id:t.project_id,...k.length>0?{level_notes:k}:{}}))}}(n,e,a))}catch(e){const t=bl(e);return ql(t||vl(e))}}B(Gy,{BULK_IMPORT_MAIN_MAX:()=>Vy,BULK_IMPORT_MAX:()=>Wy,bulkImportHandler:()=>Yy,canRetryBulkImportPerItem:()=>Qy});var Zy=V({"src/tools/bulk-import.ts"(){ic(),Sf(),lb(),Bf(),Ml(),Jy(),hh(),Qf(),io(),da(),A_(),Ml(),op(),Nm(),Ih(),pu(),Wy=500,Vy=100}}),Xy={};async function eg(e){const t=Kl(),n=e.idempotencyKey??e.requestId??crypto.randomUUID(),r=await Promise.all(e.entries.map(e=>async function(e){return tr(er(Wr(e)))}(e))),a=Lr(r),i=[];for(let s=0;s<e.entries.length;s+=1){const o=await Dr(e.idempotencyKey?Nr({userId:t,projectId:e.projectId,family:zr(e.tool),key:e.idempotencyKey,itemIdOrK:e.itemId,path:["runs"],runHash:r[s],runK:a[s]}):Pr({userId:t,projectId:e.projectId,itemId:e.itemId,runHash:r[s],k:a[s],effectiveKey:n}));i.push({op_id:o,kind:"append_run",item_id:e.itemId,path:["runs"],value:e.entries[s]})}const s=await xf({client:e.client,projectId:e.projectId,ops:i,deterministic:!0}),o=s.answers.find(e=>"invalid"===e.status&&"run_refused"===e.reason),l=new Map(s.answers.map(e=>[e.op_id,e]));return{run:s,runs:i.map((t,n)=>{const r=l.get(t.op_id);return{result:String(e.entries[n]?.result??""),run_at:"string"==typeof r?.run_at?r.run_at:null,asset_id:"string"==typeof r?.asset_id?r.asset_id:null,asset_created:!0===r?.asset_created}}),keyUsed:n,refusal:o?String(o.message??o.reason??"run refused"):null}}async function tg(e,t){let n;try{const r=await Bl(),a=Kl(),i=Yl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const s=t??await Af(r,e.project_id);if("unreadable"===s)return If();n=s;const o=await Xm(r,e.project_id,e.item_id);if(!o)return ql(nl("Item",e.item_id));if("test-case"!==o.type)return ql(sl(`Item '${e.item_id}' is a ${o.type}, not a test-case`));const l=(e.asset??"").trim(),c=xd({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=>Al(e)),d=kd([e]).length>0?{release_note:Xc}:{};if("ops"===s){const t=await eg({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 ql(sl(t.refusal,Lo));const n=t.runs[0],s=l?` (asset: ${l})`:"";return $f(t.run.outcome,{item_id:e.item_id,result:e.result,run_at:n.run_at,run_by:i||a,note:c.note??null,asset:l||null,asset_id:n.asset_id,asset_created:n.asset_created,message:t.run.outcome.replayed?Pn:`Test result '${e.result}' recorded for ${e.item_id}${s}`,...void 0!==e.date&&null!==e.date?{warning:ed}:{},...d},t.run.chunks,{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;await r.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:a,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:o,note:c.note,asset:l||null},actor:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const u=l?` (asset: ${l})`:"";return $l(Xo({item_id:e.item_id,result:e.result,run_at:o,run_by:i||a,note:c.note??null,asset:l||null,asset_id:s?.asset_id??null,asset_created:s?.asset_created??!1,message:`Test result '${e.result}' recorded for ${e.item_id}${u}`,...void 0!==e.date&&null!==e.date?{warning:ed}:{},...d}))};return await u()}catch(r){const a=qf(n,t,r);return a?tg(e,a):ql(vl(r))}}B(Xy,{recordRunsByOps:()=>eg,recordTestResultHandler:()=>tg});var ng=V({"src/tools/record-test-result.ts"(){ic(),i_(),lb(),Ml(),Dd(),da(),Nf(),da()}}),rg={};async function ag(e,t){let n;try{const r=await Bl(),a=Kl(),i=Yl();if(!Array.isArray(e.results)||0===e.results.length)return ql(sl("results must be a non-empty array"));if(e.results.length>100)return ql(sl(`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?gd(e.date):NaN;Number.isNaN(a)||(a<n?t.push(r):n=a)}),t}(e.results);if(s.length>0)return ql(sl(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),Lo));try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const o=t??await Af(r,e.project_id);if("unreadable"===o)return If();n=o;const l=await Xm(r,e.project_id,e.item_id);if(!l)return ql(nl("Item",e.item_id));if("test-case"!==l.type)return ql(sl(`Item '${e.item_id}' is a ${l.type}, not a test-case`));if("ops"===o){const t=e.results.map(e=>{const t=xd(e,e=>Al(e)),{date:n,...r}=t;return r}),n=await eg({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 ql(sl(n.refusal,Lo));const a=bd(e.results),i=kd(e.results);return $f(n.run.outcome,{item_id:e.item_id,count:e.results.length,results:n.runs,message:n.run.outcome.replayed?Pn:`Recorded ${e.results.length} test results for ${e.item_id}`,...a.length>0?{warning:jd(a),ignored_date_entries:a}:{},...i.length>0?{release_note:Sd(i),no_release_entries:i}:{}},n.run.chunks,{idempotency_key_used:n.keyUsed})}const c=async()=>{const{data:t,error:n}=await r.rpc("record_test_results_bulk",{p_project_id:e.project_id,p_item_id:e.item_id,p_run_by:i||a,p_actor_user_id:a,p_results:e.results.map(e=>xd(e,e=>Al(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:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const s=bd(e.results),o=kd(e.results);return $l(Xo({item_id:e.item_id,count:e.results.length,results:t,message:`Recorded ${e.results.length} test results for ${e.item_id}`,...s.length>0?{warning:jd(s),ignored_date_entries:s}:{},...o.length>0?{release_note:Sd(o),no_release_entries:o}:{}}))};return await c()}catch(r){const a=qf(n,t,r);return a?ag(e,a):ql(vl(r))}}B(rg,{recordTestResultsBulkHandler:()=>ag});var ig=V({"src/tools/record-test-results-bulk.ts"(){ic(),i_(),lb(),Ml(),ng(),da(),Nf(),Dd()}}),sg={};async function og(e){try{const t=Lm(e.depth),n=await Bl(),r=await Xm(n,e.project_id,e.item_id);if(!r)return ql(nl("Item",e.item_id));const a=await tu(()=>n.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),Ld),i=Ou(a,await tu(()=>n.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),Wd));return $l(Xo(function(e){const t=Lm(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=Um(t,s),a=r.type;if(n||!Rm.includes(a)){if(("upstream"===e.direction||"both"===e.direction)&&(!Em.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),Om.has(a))){const e=Mm[a]??a;n&&!n.has(e)||i(r.to_id,r.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!Om.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),Em.has(a))){const e=Mm[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(;d.length>0&&l.length<qm;){const{id:e,depth:n,relType:i,from:s}=d.shift();if(o.has(e)||n>t)continue;o.add(e);const u=r.get(e);if(u&&(l.push({id:e,title:Pm(u),type:u.type,relationship:i,depth:n,from:s,...zm(u,r)}),c.push({from:s,to:e,type:i}),n<t))for(const t of a.get(e)??[])o.has(t.neighbor)||d.push({id:t.neighbor,depth:n+1,relType:t.relType,from:e})}const u={id:e.rootItemId,title:Pm(e.rootItem),type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId,...zm(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,...l.length>=qm?{truncated:!0,truncation_message:`Results capped at ${qm} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown",data:r.data},items:a,relationships:i??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types})))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(sg,{traceHandler:()=>og});var lg=V({"src/tools/trace.ts"(){ic(),i_(),pu(),Bm(),Ml()}}),cg={};async function dg(e){try{const t=await Bl(),n=await tu(()=>{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)},Bd);return $l(Xo({assets:n,total:n.length}),{complete:!0})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(cg,{listAssetsHandler:()=>dg});var ug,pg=V({"src/tools/assets.ts"(){ic(),pu(),Ml()}}),mg={};async function _g(e,t,n,r){if(n&&r)throw new Jt("baseline_id and as_of are mutually exclusive");if(r)return Qd(Qm(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 Jt("Baseline not found for this project");return Kd(n)}async function fg(e,t,n){return n?iu(e,t,n):tu(()=>e.from("project_variables").select("*").eq("project_id",t),Jd)}async function hg(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 yg(e,t,n){if(0===n.length||!0!==await Yr(e,t))return n;const r=await _r(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 cr(t,"variable","variable")}:e}))}async function gg(e,t,n,r){const a=Kl(),i=zr("atoms_create_variable");return n?{rowId:await Dr(Nr({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables","row_id"]})),opId:await Dr(Nr({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables"]}))}:{rowId:await Dr(Ur({userId:a,projectId:e,name:t,what:"variable"})),opId:await Dr(Ur({userId:a,projectId:e,name:t,what:"create_variable"}))}}async function wg(e){try{const t=await Bl(),n=await _g(t,e.project_id,e.baseline_id,e.as_of),r=await fg(t,e.project_id,n),a=e.limit??50,i=e.offset??0,s=r.slice(i,i+a);return $l(Xo({variables:null===n?await yg(t,e.project_id,s):s,total:r.length},el(r.length,a,i)))}catch(e){return ql(vl(e))}}async function vg(e){try{const t=await Bl(),n=await _g(t,e.project_id,e.baseline_id,e.as_of),r=(await fg(t,e.project_id,n)).find(t=>t.name===e.variable_name)??null;if(!r)return ql(nl("Variable",e.variable_name));const a=await tu(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),Ld),i=`{${e.variable_name}}`,s=a.filter(e=>(e.data?.body||"").includes(i)),[o]=null===n?await yg(t,e.project_id,[r]):[r];return $l(Xo({variable:o,referenced_by:s.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:s.length}))}catch(e){return ql(vl(e))}}async function bg(e,t){let n;try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();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 ql(nl("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 vr({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:t,tokens:Ef(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(wr(a[t]));n&&l.push(jr({op_id:Hr(),kind:"set",item_id:null,path:a[t],value:e},n))});const c=await xf({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 $f(c.outcome,!1===e.echo?{name:e.variable_name,updated:!0}:{variable:d},c.chunks)}const o={updated_by:a,updated_at:(new Date).toISOString()};void 0!==e.value&&(o.value=e.value),void 0!==e.unit&&(o.unit=e.unit||null),void 0!==e.description&&(o.description=e.description||null);const l=await hg(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?$l(Xo({name:e.variable_name,updated:!0})):$l(Xo({variable:l}))}catch(r){const a=qf(n,t,r);return a?bg(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}async function jg(e,t){let n;try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();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 ql(sl(`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 ql(sl(`Duplicate names in batch (case-insensitive): ${[...new Set(l)].join(", ")}`));const c=await fg(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 ql(sl(`Variable(s) already exist (case-insensitive): ${u.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));if("ops"===i){const t=e.variables,n=await Promise.all(t.map((t,n)=>gg(e.project_id,t.name,e.idempotency_key,n))),a=t.map((e,t)=>ug(n[t],e)),i=crypto.randomUUID(),s=await xf({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 $f(s.outcome,{batch_id:i,created:o.length,variables:!1===e.echo?o.map(e=>({name:e.name})):o,message:`${o.length} variable(s) created. Reference them as {name} in requirement bodies.`},s.chunks)}const p=e.variables.map(t=>({project_id:e.project_id,name:t.name,value:t.value,unit:t.unit??null,description:t.description??null,created_by:a,updated_by:a})),m=await async function(e,t,n,r){const{data:a,error:i}=await e.rpc("bulk_save_variables_with_revisions",{p_project_id:t,p_variables:n,p_user_id:r,p_event_source:"mcp"});if(i)throw new Error(i.message);return a??[]}(r,e.project_id,p,a);return $l(Xo({batch_id:crypto.randomUUID(),created:(m??[]).length,variables:!1===e.echo?(m??[]).map(e=>({name:e.name})):m??[],message:`${(m??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`}))}if(!e.name||!e.value)return ql(sl("Provide either (name, value) for single variable or variables[] for batch."));if(!s.test(e.name))return ql(sl(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const o=(await fg(r,e.project_id,null)).find(t=>t.name.toLowerCase()===e.name.toLowerCase());if(o)return ql(sl(`Variable "${o.name}" already exists in this project (names are unique regardless of case).`));if("ops"===i){const t=await gg(e.project_id,e.name,e.idempotency_key,0),n=await xf({client:r,projectId:e.project_id,ops:[ug(t,e)],deterministic:!0}),a={id:t.rowId,project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null};return $f(n.outcome,!1===e.echo?{name:e.name}:{variable:a,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`},n.chunks)}const l=await hg(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?$l(Xo({name:e.name})):$l(Xo({variable:l,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(r){const a=qf(n,t,r);return a?jg(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}async function kg(e,t){let n;try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();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 ql(nl("Variable",e.name));const{count:o,error:l}=await r.from("items").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).is("deleted_at",null).filter("data->>body","ilike",`%{${e.name}}%`);if(l)throw new Error(l.message);const c=o??0;if(c>0&&!e.force)return ql(sl(`Variable "${e.name}" is referenced in ${c} item${c>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));if(Pf("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=Uf(t);return $l(Xo({status:"confirmation_required",preview:{variable_name:e.name,referenced_by_items:c,would_orphan_references:c>0},confirmation_token:n.token,expires_at:n.expires_at,expires_in_seconds:n.expires_in_seconds,message:`Re-call atoms_delete_variable with the same project_id, name, and confirmation_token within ${n.expires_in_seconds}s to execute.`}))}const n=zf(e.confirmation_token,t);if(!n.valid)return ql(sl(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t=["variables",String(s.id)],n=await vr({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:String(s.id),tokens:Ef(e.base_token),paths:[t],values:[null],name:e.name}]}),a=n.items.get(String(s.id))?.bases.get(wr(t)),i=a?[jr({op_id:Hr(),kind:"remove",item_id:null,path:["variables"],row_id:String(s.id),value:null},a)]:[],o=await xf({client:r,projectId:e.project_id,ops:i,refusals:n.refusals});return $f(o.outcome,{deleted:!0,name:e.name,referenced_by_items:c,warning:c>0?`${c} item${c>1?"s":""} still contain {${e.name}}. Those references are now unresolved.`:void 0},o.chunks)}const d=await async function(e,t,n,r){const{data:a,error:i}=await e.rpc("delete_variable_with_revision",{p_project_id:t,p_variable_id:n,p_user_id:r,p_event_source:"mcp"});if(i)throw new Error(i.message);return Boolean(a)}(r,e.project_id,s.id,a);return d?$l(Xo({deleted:!0,name:e.name,referenced_by_items:c,warning:c>0?`${c} item${c>1?"s":""} still contain {${e.name}} — those references are now unresolved.`:void 0})):ql(nl("Variable",e.name))}catch(r){const a=qf(n,t,r);return a?kg(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}B(mg,{createVariableHandler:()=>jg,deleteVariableHandler:()=>kg,getVariableHandler:()=>vg,listVariablesHandler:()=>wg,updateVariableHandler:()=>bg});var Sg,Ag=V({"src/tools/variables.ts"(){ic(),da(),Nf(),pu(),Km(),zn(),Bf(),Ml(),ug=(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}})}}),Ig={};async function xg(e,t,n,r,a){let i=0;for(;;){const{data:s,error:o}=await e.rpc("apply_domain_change",{p_project_id:t,p_old_domain:n,p_new_domain:r,p_user_id:a,p_event_source:"mcp",p_limit:Sg});if(o)throw new Error(i>0?`${o.message} (${i} items were already updated and the registry is unchanged: call again to finish)`:o.message);const l="number"==typeof s?s:0;if(i+=l,l<Sg)return i}}async function $g(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 qg(e){try{const t=await Bl(),{domains:n,functionTags:r}=await $g(t,e.project_id),a=eo(n,r),i=new Set(a.map(xs)),s=new Set(r.map(xs)),o=n.filter(e=>!i.has(xs(e))),{counts:l,orphans:c}=await async function(e,t,n){const r=await tu(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),Ld),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(xs(e))).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),p=[...d,...u];return $l(Xo({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")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}async function Eg(e,t){let n;try{const r=await Bl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const a=t??await Af(r,e.project_id);if("unreadable"===a)return If();n=a;const i=Al(e.name).trim().toLowerCase();if(!i)return ql(sl("Domain name cannot be empty."));const s=await $g(r,e.project_id);if(null!==$s(i,s.functionTags))return ql(sl(co(i,!0),Lo));const o=$s(i,s.domains);if(null!==o)return ql(sl(co(o,!1),Lo));if("ops"===a){const t={op_id:Hr(),kind:"add",item_id:null,path:["taxonomy","domains"],value:i},{run:n}=await Cf({client:r,projectId:e.project_id,op:t});return n.answers.some(e=>"noop"===e.status)?ql(sl(co(i,!1),Lo)):$f(n.outcome,{domain:{name:i},message:lo(i)},n.chunks)}const l=async()=>{const{data:t,error:n}=await r.rpc("append_project_domain",{p_project_id:e.project_id,p_domain:i});if(n)throw new Error(n.message);if(t&&!1===t.added){const{functionTags:t}=await $g(r,e.project_id),n=null!==$s(i,t);return ql(sl(co(i,n),Lo))}return $l(Xo({domain:{name:i},message:lo(i)}))};return await l()}catch(r){const a=qf(n,t,r);return a?Eg(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}async function Og(e,t){let n;const r=_p("atoms_update_domain",e);if(r)return ql(r);try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();if(n=i,"string"!=typeof e.new_name)return ql(sl("Pass new_name, the domain's new name."));const{domains:s,functionTags:o}=await $g(r,e.project_id),l=Al(e.name).trim(),c=function(e,t){const n=e.trim();return"ops"===t?n:n.toLowerCase()}(Al(e.new_name),"ops"===i?"ops":"main");if(!c)return ql(sl("new_name cannot be empty."));const{spelling:d,registered:u}=await so(r,e.project_id,l,s);if(null===d)return ql(nl("Domain",l.toLowerCase()));if(null!==$s(c,[d]))return ql(sl(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!==$s(t,[e]))return null;const a=$s(t,r);if(null!==a)return{kind:"function",name:a};const i=$s(t,n);return null!==i?{kind:"domain",name:i}:null}(d,c,s,o);if("function"===p?.kind)return ql(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:ao,functions:[n]}}}(d,c,p.name));if("domain"===p?.kind&&u)return ql(sl(uo(p.name)));const m="domain"===p?.kind&&!u,_=m&&p?p.name:c,f=await oo(r,e.project_id,[d]);if(e.dry_run)return $l(Xo({dry_run:!0,rename:{from:d,to:_},items_affected:f,message:m?`Dry run: "${d}" is not registered and "${_}" is, so the ${f} item${1!==f?"s":""} carrying "${d}" would be merged into the registered domain "${_}" (the registry is not changed). Call again with dry_run=false to apply.`:`Dry run: renaming "${d}" → "${c}" would update ${f} item${1!==f?"s":""}. Call again with dry_run=false to apply.`}));if("ops"===i){const t={op_id:Hr(),kind:"rename",item_id:null,path:["taxonomy","domains"],value:_,base:d},{run:n,retagged:a}=await Cf({client:r,projectId:e.project_id,op:t,repeat:!0});return Df(n,"deleted")?ql(nl("Domain",d.toLowerCase())):Df(n,"invalid","name_taken")?ql(sl(uo(_))):$f(n.outcome,{domain:{name:_},renamed_from:d,items_updated:a,message:m?`Domain "${d}" merged into the registered domain "${_}". ${a} item${1!==a?"s":""} updated.`:`Domain renamed "${d}" → "${c}". ${a} item${1!==a?"s":""} updated.`},n.chunks)}const h=async()=>{const t=await xg(r,e.project_id,d,_,a);return m?$l(Xo({domain:{name:_},renamed_from:d,items_updated:t,message:`Domain "${d}" 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,d,c),$l(Xo({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=qf(n,t,r);return a?Og(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}async function Rg(e,t){let n;try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();n=i;const{domains:s}=await $g(r,e.project_id),o=Al(e.name).trim(),{spelling:l,registered:c}=await so(r,e.project_id,o,s),d=l??o.toLowerCase(),u=null===l?0:await oo(r,e.project_id,[l]);if(!c&&0===u)return ql(nl("Domain",d));if(u>0&&!e.force)return ql(sl(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(Pf("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=Uf(t);return $l(Xo({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=zf(e.confirmation_token,t);if(!n.valid)return ql(sl(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t={op_id:Hr(),kind:"remove",item_id:null,path:["taxonomy","domains"],value:d},{run:n,retagged:a}=await Cf({client:r,projectId:e.project_id,op:t,repeat:!0});return Df(n,"deleted")?ql(nl("Domain",d)):$f(n.outcome,{deleted:!0,name:d,items_updated:a,message:u>0?`Domain "${d}" deleted and stripped from ${a} item${1!==a?"s":""}.`:`Domain "${d}" deleted.`},n.chunks)}const p=async()=>{const t=u>0?await xg(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 $l(Xo({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=qf(n,t,r);return a?Rg(e,a):r instanceof Error&&r.message.includes("Not authenticated")?ql(ol()):ql(kl(r instanceof Error?r.message:String(r)))}}B(Ig,{DOMAIN_CHANGE_BATCH:()=>Sg,createDomainHandler:()=>Eg,deleteDomainHandler:()=>Rg,listDomainsHandler:()=>qg,updateDomainHandler:()=>Og});var Mg=V({"src/tools/domains.ts"(){ic(),pu(),Bf(),Ml(),io(),da(),Nf(),go(),Op(),Sg=200}}),Tg={};async function Cg(e){try{const t=await Bl(),{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 tu(()=>t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null),Ld);if(!a&&0===s.length){if(i)throw new Error(i);return ql(nl("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 Ju(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=qd(n);"passed"===e?t.passed++:"failed"===e?t.failed++:"blocked"===e?t.blocked++:t.not_run++}return t}(s),u=Ou(s,await tu(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),Wd)),p=_u(s,u),m=c.filter(e=>p.has(e.id)).length,_=c.length,f={covered:m,uncovered:_-m,total:_,percent:$u(m,_),via_mitigation:Su(c.map(e=>e.id),p,hu(s,u))},h=await Nu(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"===qd(t)&&r++;return{requirements:new Set(t.map(e=>e.requirement_id)).size,test_cases:r}}(s,await Pu(t,e.project_id,p,h.releaseId)),g=new Map;for(const e of c){const t=e.domains.length>0?e.domains:["(untagged)"],n=p.has(e.id);for(const e of t){g.has(e)||g.set(e,{covered:0,total:0});const t=g.get(e);t.total++,n&&t.covered++}}const w=Array.from(g.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:$u(t.covered,t.total)})),v=new Date;v.setDate(v.getDate()-7);const b=!0===await p_(t,e.project_id),{count:j,error:k}=b?await t.from("project_changes").select("seq",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("committed_at",v.toISOString()):await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",v.toISOString());if(k)throw new Error(k.message);return $l(Xo({project_id:e.project_id,project_name:a??`Project ${e.project_id.slice(0,8)}`,counts:o,test_status:d,coverage:f,coverage_by_domain:w,rerun:y,rerun_scope:h.label,recent_changes:j??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(Tg,{projectSummaryHandler:()=>Cg});var Dg=V({"src/tools/project-summary.ts"(){ic(),i_(),Eu(),Bu(),xu(),pu(),Ml(),A_(),op()}}),Hg={};async function Fg(e){try{const t=await Bl();let n,r;if(e.query&&e.query.trim().length>0){const a=await a_(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:qd(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),r=a.totalCount}else{const a=await Zm(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:qd(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 tu(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),Ld),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 $l(Xo({items:n,filters:{domains:a.domains,levels:a.levels,types:Gu(await Ju(t,e.project_id))},project_id:e.project_id},el(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(Hg,{browseHandler:()=>Fg});var Ng,Pg=V({"src/tools/browse.ts"(){ic(),i_(),Ml(),Dd(),op()}}),Ug={};async function zg(e){try{const t=e.direction??"downstream",n=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await Bl(),a=await Xm(r,e.project_id,e.item_id);if(!a)return ql(nl("Item",e.item_id));const i=await tu(()=>r.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),Ld),s=Ou(i,await tu(()=>r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),Wd)),o=new Map;for(const e of i)o.set(e.id,{title:Pm(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=Um(e,e=>o.get(e)?.type),r=n.type;"upstream"!==t&&"both"!==t||(Tm.includes(r)&&c(n.from_id,n.to_id,r),Cm.includes(r)&&c(n.to_id,n.from_id,Dm[r]??r)),"downstream"!==t&&"both"!==t||(Cm.includes(r)&&c(n.from_id,n.to_id,r),Tm.includes(r)&&c(n.to_id,n.from_id,Dm[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(;m.length>0&&u.length<Ng;){const{id:e,depth:t,path:r}=m.shift();if(d.has(e))continue;if(null!==n&&t>n)continue;d.add(e);const a=o.get(e);if(a&&(u.push({item_id:e,title:a.title,type:a.type,depth:t,relationship_path:r,shared_variables:[]}),t>p&&(p=t),null===n||t<n))for(const n of l.get(e)??[])d.has(n.neighbor)||m.push({id:n.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:n.neighbor,relationship_type:n.relType}]})}let _=0;if(e.include_variable_refs){const{data:t,error:n}=await r.from("variable_references").select("variable_id").eq("item_id",e.item_id).eq("project_id",e.project_id);if(n)throw new Error(n.message);const a=[...new Set((t??[]).map(e=>e.variable_id))];if(a.length>0){const{data:t,error:n}=await r.from("project_variables").select("id, name").in("id",a);if(n)throw new Error(n.message);const i=new Map((t??[]).map(e=>[e.id,e.name])),s=await tu(()=>r.from("variable_references").select("variable_id, item_id, field").in("variable_id",a).eq("project_id",e.project_id).neq("item_id",e.item_id),Vd),l=new Map;for(const t of s){const n=t.item_id;if(n===e.item_id)continue;const r=i.get(t.variable_id)??t.variable_id;l.has(n)||l.set(n,new Set),l.get(n).add(r)}const c=new Map(u.map(e=>[e.item_id,e]));for(const[t,n]of l){const r=[...n].sort(),a=c.get(t);if(a){a.shared_variables=r;continue}if(u.length>=Ng)break;const i=o.get(t);i&&(u.push({item_id:t,title:i.title,type:i.type,depth:1,relationship_path:[{from_id:e.item_id,to_id:t,relationship_type:`variable_ref:${r[0]}`}],shared_variables:r}),_++)}}}const f={};for(const e of u)f[e.type]=(f[e.type]??0)+1;const h=o.get(e.item_id);return $l(Xo({root:{item_id:e.item_id,title:h?.title??a.title,type:h?.type??a.type},impacted_items:u,summary:{total_impacted:u.length,by_type:f,max_depth_reached:p,..._>0?{variable_impact_count:_}:{},...u.length>=Ng?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}B(Ug,{impactAnalysisHandler:()=>zg});var Lg,Wg,Vg,Bg,Jg,Gg,Qg,Kg,Yg,Zg,Xg,ew,tw=V({"src/tools/impact-analysis.ts"(){ic(),i_(),Bm(),pu(),Ml(),Ng=200}});function nw(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function rw(e){return null==e?"":String(e)}function aw(e){if(null==e||""===e)return"null";if(Array.isArray(e))return 0===e.length?"null":`[${e.map(aw).join(",")}]`;if("object"==typeof e){const t=e,n=Object.keys(t).filter(e=>"null"!==aw(t[e])).sort();return 0===n.length?"null":`{${n.map(e=>`${JSON.stringify(e)}:${aw(t[e])}`).join(",")}}`}return JSON.stringify(e)}function iw(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function sw(e){return null==e||""===e?null:e}function ow(e,t=!0){const n=sw(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=>ow(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)}:${ow(r[e],t)}`).join(",")}}`}function lw(e,t){return e.some(e=>!t.includes(e))||t.some(t=>!e.includes(t))}function cw(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 dw(e,t){const n=iw(e),r="parents"===t?n.parent:"children"===t?n.child:void 0;return Array.from(new Set([...cw(n[t]),...cw(r)])).sort()}function uw(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){const e=iw(n);if("string"!=typeof e.date||!e.date.trim())continue;const r={};for(const t of Gg){const n=sw(e[t]);null!==n&&(r[t]=n)}t.set(e.date,r)}return t}function pw(e,t){const n=uw(e),r=uw(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&&Gg.every(e=>ow(t[e])===ow(a[e])))});return[Object.fromEntries(a.map(e=>[e,n.get(e)??null])),Object.fromEntries(a.map(e=>[e,r.get(e)??null]))]}function mw(e,t){const n=[];sw(e.title)!==sw(t.title)&&n.push({path:"title"}),sw(e.type)!==sw(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 Bg)sw(r[e])!==sw(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)?lw(t,n):ow(t)!==ow(n))&&i("tags",e)}const l=iw(r.analysis_props),c=iw(a.analysis_props);for(const e of Array.from(new Set([...Object.keys(l),...Object.keys(c)])).sort())!Lg.has(e)&&nw(l[e])&&nw(c[e])&&rw(l[e])!==rw(c[e])&&i("analysis_props",e);ow(r.ownership)!==ow(a.ownership)&&i("ownership");for(const e of Jg)lw(dw(r.relationships,e),dw(a.relationships,e))&&i("relationships",e);Object.keys(pw(r.runs,a.runs)[0]).length>0&&i("runs");for(const e of Array.from(new Set([...Object.keys(r),...Object.keys(a)])).sort())Qg.has(e)||ow(r[e],!1)!==ow(a[e],!1)&&i(e);return n}function _w(e,t){const n=mw(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"),(fw(e)||fw(t)?sw(yw(e))!==sw(yw(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=iw(e),r=iw(t),a=[],i=iw(n.analysis_props),s=iw(r.analysis_props),o=Array.from(new Set([...Object.keys(i),...Object.keys(s)])).sort();for(const e of o){if(Lg.has(e))continue;const t=i[e],n=s[e];nw(t)&&nw(n)?rw(t)!==rw(n)&&a.push(`analysis_props.${e}`):aw(t)!==aw(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(iw(n.fields)),d=l(iw(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 fw(e){return"test-case"===e.type}function hw(e){const t=iw(e.data);return fw(e)?Cd(t):t.runs}function yw(e){const t=iw(e.data);return fw(e)?qd({type:"test-case",data:t})??null:t.status??null}function gw(e,t){for(const[n,r]of Object.entries(e))if(n.toLowerCase()===t)return"string"==typeof r?r:null;return null}function ww(e,t,n){const r=iw(e.data),a=iw(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:yw(e),to:yw(t)};else if("tags.level"===o)s[o]={from:iw(r.tags).level??null,to:iw(a.tags).level??null};else if("tags.domains"===o)s[o]={from:iw(r.tags).domains??null,to:iw(a.tags).domains??null};else if(o.startsWith("analysis_props.")){const e=o.slice(15);s[o]={from:iw(r.analysis_props)[e]??null,to:iw(a.analysis_props)[e]??null}}else if(o.startsWith("fields.")){const e=o.slice(7).toLowerCase();s[o]={from:gw(iw(r.fields),e),to:gw(iw(a.fields),e)}}else if("data"===o){const n=mw(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=fw(e)||fw(t);for(const n of c){if("status"===n&&p)continue;const[s,o]="runs"===n?bw(n,hw(e),hw(t),i,l):bw(n,r[n],a[n],i,l);aw(s)!==aw(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 vw(e,t){return null===e||"object"!=typeof e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).filter(([e])=>!t(e)))}function bw(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[vw(t,e),vw(n,e)]}if("relationships"===e){const e=Jg.filter(e=>a.has(`data.relationships.${e}`)),r=t=>Object.fromEntries(e.map(e=>[e,dw(t,e)]));return[r(t),r(n)]}if("runs"===e)return pw(t,n);if("analysis_props"===e){const e=e=>r.has(`analysis_props.${e}`);return[vw(t,e),vw(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[vw(t,e),vw(n,e)]}return Array.isArray(t)&&Array.isArray(n)?function(e,t){const n={},r={},a=jw(e),i=jw(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;aw(t)!==aw(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++)aw(e[a])!==aw(t[a])&&(n[a]=e[a]??null,r[a]=t[a]??null);return[n,r]}(t,n):[t,n]}function jw(e){const t=[];for(const n of e){const e=iw(n).id;if("string"!=typeof e||"order"===e)return null;t.push(e)}return new Set(t).size===t.length?t:null}function kw(e){return"string"==typeof e?1:Array.isArray(e)?e.reduce((e,t)=>e+kw(t),0):null!==e&&"object"==typeof e?Object.values(e).reduce((e,t)=>e+kw(t),0):0}function Sw(e){const t=JSON.stringify(e,null,2),n=t.split("\n").length;return t.length+n*Zg+Yg*kw(e.diff)+2}function Aw(e,t,n){if("string"==typeof e){if(e.length<=t+ew)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=>Aw(e,t,n)):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Aw(r,t,n)])):e}function Iw(e,t){const n=e.diff??{};for(const r of Xg){const a={n:0},i=Aw(n,r,a),s={...e,diff:i,...a.n>0?{diff_clipped:!0}:{}};if(Sw(s)<=t)return s}const r={n:0},a=Aw(n,Xg[Xg.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(Sw(c)>t)break;o=r,l=c}return 0===l.diff_omitted&&delete l.diff_omitted,l}var xw,$w=V({"src/core/baseline-diff.ts"(){Dd(),Lg=new Set(["field_source","approved","approved_at","approved_by","approved_note"]),Wg=["approval_state","approver_user_id","rev_label","approved_at","requires_impacted_approval"],Vg=["id","title","type","metadata","parent","child",...Wg],Bg=["body","summary","status","level","isLocked","lockedBy","lockedAt"],Jg=["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"],Gg=["result","by","note","asset"],Qg=new Set(["tags","ownership","relationships","runs",...Bg,...Vg]),Kg=2e4,Yg=29,Zg=6,Xg=[1e3,400,160,60,20],ew=40}});function qw(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 xw){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 Ew(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 Ow,Rw,Mw,Tw,Cw=V({"src/core/restore-preview.ts"(){xw=[{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"}]}}),Dw={};function Hw(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):null}async function Fw(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 Nw(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 Pw(e,t,n){const{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a)return ql(kl(a.message));if(!r)return ql(nl("Project",t));if(r.deleted_at)return ql(Bn());const{data:i,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?ql(kl(s.message)):!0!==(i?.feature_flags??{})[n]?ql(tl(`Feature '${n}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function Uw(e){try{const t=await Bl(),n=await async function(e,t){const{data:n,error:r}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, release_version, release_status").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1}).order("id",{ascending:!1});if(r)throw new Error(`listBaselines: ${r.message}`);return n??[]}(t,e.project_id),r=Math.max(e.offset??0,0),a=Math.min(Math.max(e.limit??50,1),100);return $l(Xo({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},el(n.length,a,r)))}catch(e){return Hw(e)??ql(vl(e))}}async function zw(e){try{const t=await Bl(),n=await Pw(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?ql(tl(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):ql(vl(a)):$l(Xo({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 Hw(e)??ql(vl(e))}}async function Lw(e){try{const t=await Bl(),n=await t_(t,e.baseline_id);if(!n)return ql(nl("Baseline",e.baseline_id));const r=await Pw(t,n.project_id,"baselines_enabled");if(r)return r;if(null!==n.locked_at)return ql(tl("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 ql(nl("Project",n.project_id));const{data:i,error:s}=await t.auth.getUser();if(Mt(s))return ql(Tt());const o=i?.user?.id;if(!o)return ql(ol());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 ql(tl("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?ql(vl(d)):$l(Xo({id:c.id,locked_at:c.locked_at,locked_by:c.locked_by}))}catch(e){return Hw(e)??ql(vl(e))}}async function Ww(e){try{const t=await Bl(),[n,r]=await Promise.all([t_(t,e.baseline_a_id),t_(t,e.baseline_b_id)]);if(!n||!r)return ql(nl("Baseline","one of the baseline_ids"));if(n.project_id!==r.project_id)return ql(tl("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[a,i]=await Promise.all([r_(t,n.project_id,Kd(n.id)),r_(t,r.project_id,Kd(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=_w(t,n);r.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:r}))}}const m=Math.max(e.offset??0,0),_=Math.min(Math.max(e.limit??50,1),200);let f=c.slice(m,m+_);const h={offset:m,limit:_,total:c.length};if(!0===e.detail){const e=function(e,t,n,r,a={}){const i=a.budget??Kg,s=a.diffOf??ww,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=Sw(e);if(l+a>i){if(o.length>0)break;e=Iw(e,i),a=Sw(e)}e.diff_clipped&&(c=!0),e.diff_omitted&&(d=!0),o.push(e),l+=a}if(o.length===e.length&&!c&&!d)return{items:o,pageInfo:{}};const u={returned:o.length,truncated:!0},p=[];return o.length<e.length&&(u.next_offset=r+o.length,p.push(`Response bounded to ${i} characters of items: returned ${o.length} of the ${e.length} items on this page. Call again with offset=${u.next_offset} for the rest, or omit detail to get only the names of the changed fields.`)),c&&p.push('Long values in an item were clipped to fit, each marked "[clipped, N more characters]".'),d&&p.push("diff_omitted counts the changed fields of an item whose values did not fit; their names are still in fields_changed."),(c||d)&&p.push("Compare the two snapshots in the app to see every value in full."),u.truncation_message=p.join(" "),{items:o,pageInfo:u}}(f,s,o,m);f=e.items,Object.assign(h,e.pageInfo)}return $l(Xo({summary:{added:d,removed:u,modified:p,total_compared:l.length},items:f,page_info:h,baselines:{a:{id:n.id,name:n.name,snapshot_at:n.snapshot_at},b:{id:r.id,name:r.name,snapshot_at:r.snapshot_at}}}))}catch(e){return Hw(e)??ql(vl(e))}}async function Vw(e,t){let n;try{const i=await Bl(),s=await t_(i,e.baseline_id);if(!s)return ql(nl("Baseline",e.baseline_id));const o=await Pw(i,s.project_id,"baselines_enabled");if(o)return o;const{data:l}=await i.from("projects").select("org_id").eq("id",s.project_id).maybeSingle();if(!l)return ql(nl("Project",s.project_id));const{data:c,error:d}=await i.auth.getUser();if(Mt(d))return ql(Tt());const u=c?.user?.id;if(!u)return ql(ol());const{data:p}=await i.from("org_members").select("role").eq("user_id",u).eq("org_id",l.org_id).maybeSingle();if(!p||"admin"!==p.role)return ql(tl("Only admins can restore from a baseline",["Ask an org admin to run the restore"]));const{data:m}=await i.rpc("cc_project_is_controlled",{p_project_id:s.project_id});if(!0===m)return ql(tl("Change control is on for this project. Release review before restoring a baseline.",["Release review on the project, then run the restore"]));const _=t??await Af(i,s.project_id);if("unreadable"===_)return If();n=_;const f=await r_(i,s.project_id,Kd(s.id)),h=await su(f.map(e=>e.id),e=>i.from("items").select("*").eq("project_id",s.project_id).in("id",e)),y=function(e,t){const n=new Map(t.map(e=>[e.id,e]));return e.flatMap(e=>{const t=n.get(e.id),r=[];var a,i;return t?(null!==t.deleted_at&&r.push("deleted_at"),t.type!==e.type&&r.push("type"),t.title!==e.title&&r.push("title"),a=t.data,i=e.data,JSON.stringify(a??{})!==JSON.stringify(i??{})&&r.push("data")):r.push("missing"),0===r.length?[]:[{id:e.id,type:e.type,title:e.title,data:e.data??{},diff_summary:{changed_fields:r,restored:!0},oldData:t?.data??null}]})}(f,h),g=await iu(i,s.project_id,Kd(s.id));if(!0!==e.confirm){const e="ops"===_?await hr(i,s.project_id):null,t=function(e){if(e.error)throw new Error(`restore preview counts: ${e.error.message}`);const t=e.data;if(!t||!Number.isInteger(t.items_to_trash)||!Number.isInteger(t.variables_to_archive))throw new Error("restore preview counts: the database answered no counts");return{items_to_trash:t.items_to_trash,variables_to_archive:t.variables_to_archive}}(await i.rpc("restore_baseline_preview_counts",{p_baseline_id:s.id}));return $l(Xo({preview:!0,...null!==e?{source_seq:e,items:y.slice(0,Ow).map(e=>({id:e.id,type:e.type,title:e.title,changed_fields:e.diff_summary?.changed_fields??[]})),...y.length>Ow?{items_truncated:!0}:{}}:{},items_to_restore:y.length,variables_to_restore:g.length,field_definitions_to_restore:s.field_definitions_snapshot?.length??null,items_to_trash:t.items_to_trash,variables_to_archive:t.variables_to_archive,summary:(r=y.length,a=t,`${r} item(s) will be written back to this snapshot. ${a.items_to_trash} item(s) created after it will be moved to Trash, where they can be restored. ${a.variables_to_archive} variable(s) added after it will be archived. Every revision is kept.`)}))}if("ops"===_)return"number"!=typeof e.source_seq||!Number.isInteger(e.source_seq)||e.source_seq<0?ql(sl("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.",Rw)):await async function(e,t){const n=Date.now();let r=t.bulkId??Hr(),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=[];do{const{data:n,error:p}=await Io(()=>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:Tw}),ko);if(p&&Ao(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<Mw);const p=Ew({items_restored:o.restored,items_trashed:o.trashed,variables_archived:o.archived}),m=function(e,t=[],n=!1){return[qw(e,"item"),qw(t,"variable"),n?"The field definitions were left as someone changed them after the preview.":""].filter(Boolean).join(" ")}(c,d,l),_=m?` ${m}`:"",f=i?p+_:`Restore not finished. ${p}${_} Call atoms_restore_baseline again with confirm true, source_seq ${t.sourceSeq}, bulk_id ${r} and after_id ${a??""} to continue.`;return $l(Xo({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:f}))}(i,{baselineId:s.id,projectId:s.project_id,userId:u,sourceSeq:e.source_seq,bulkId:e.bulk_id,afterId:e.after_id});const w=await Fw(i,{baselineId:s.id,projectId:s.project_id,userId:u});return $l(Xo({ok:!0,items_restored:w.items_restored,variables_restored:w.variables_restored,field_definitions_restored:w.field_definitions.length,items_trashed:w.items_trashed,variables_archived:w.variables_archived,summary:Ew(w)}))}catch(r){const a=qf(n,t,r);return a?Vw(e,a):Hw(r)??ql(vl(r))}var r,a}B(Dw,{RESTORE_CALL_BUDGET_MS:()=>Mw,createBaselineHandler:()=>zw,diffBaselinesHandler:()=>Ww,listBaselinesHandler:()=>Uw,lockBaselineHandler:()=>Lw,restoreBaselineHandler:()=>Vw,restoreBaselineStateAtomicallyViaMain:()=>Fw,syncRestoredItemRelationships:()=>Nw});var Bw,Jw,Gw,Qw,Kw=V({"src/tools/baselines.ts"(){ic(),da(),To(),Nf(),Ht(),lb(),Ml(),i_(),Hu(),$w(),Cw(),pu(),Ow=200,Rw=400,Mw=2e4,Tw=200}});function Yw(e){return"string"==typeof e}function Zw(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:Yw(n.by)?n.by:null,on:Yw(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:Yw(e.by)?e.by:"",on:Yw(e.on)?e.on:"",count:"number"==typeof e.count&&Number.isFinite(e.count)?e.count:0})):[]}}}function Xw(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>Gw)return{ok:!1,error:`scenario_catalogs accepts at most ${Gw} 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(!Yw(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),!Yw(e.name)||!e.name.trim())return{ok:!1,error:`catalog "${e.id}" must carry a non-empty name`};if(e.name.length>Jw)return{ok:!1,error:`catalog "${e.id}" name must be at most ${Jw} characters`};if(!Array.isArray(e.entries))return{ok:!1,error:`catalog "${e.id}" entries must be an array`};if(e.entries.length>Bw)return{ok:!1,error:`catalog "${e.id}" accepts at most ${Bw} 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(!Yw(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=Yw(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>Jw)return{ok:!1,error:`an entry of catalog "${e.id}" must be at most ${Jw} characters`};const s=Array.isArray(n.function_tags)?n.function_tags.filter(Yw).map(e=>e.trim()).filter(Boolean):[],o=Array.isArray(n.function_ids)?n.function_ids.filter(Yw).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=Zw(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 ev,tv=V({"src/core/catalogs.ts"(){Bw=50,Jw=100,Gw=200,Qw=["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]}}),nv={};function rv(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}function av(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function iv(e){const t=e?.relationships?.verified_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function sv(e){return JSON.parse(JSON.stringify(e??{}))}async function ov(e,t,n,r){const a=await Ap(n,Object.keys(r),()=>Ju(e,t));if(a)return{ok:!1,result:ql(sl(a,Lo))};if(!(Xu in r))return{ok:!0,rest:r,writes:{},answer:{}};const{[Xu]: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 Ju(e,t);if(!r&&"tags"===a)return{ok:!1,error:{status:"error",message:ap,next_steps:[...ip],code:"function_items_off",retryable:!1}};const i=await vp(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:ql(o.error)}}async function lv(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 rs(n)}function cv(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function dv(e){return ql("tool"===e.kind?e.error:sl(e.message,Lo))}function uv(e,t,n){return _m(t,n).map(t=>({op_id:Hr(),kind:t.kind,item_id:e,path:[...t.path],value:t.value}))}async function pv(e,t,n,r){const a=cv(r);if(!a)return!1;const i=await Xm(e,t,a);return vm(n,i?.data)}async function mv(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:as(n,a,a?null:await lv(e,t))}}async function _v(e,t,n,r){const a=cv(r),i=a?await Xm(e,t,a):null;return mv(e,t,n,i?.data)}function fv(e,t,n,r={}){const a=r.where?`${r.where}: `:"",i=function(e,t){if("security_tir57"!==e)return{ok:!0,fields:t};const n=Object.keys(t??{}),r=[];for(const e of n){const a=Object.prototype.hasOwnProperty.call(vi,e)?vi[e]:e;if(a!==e&&n.includes(a))return{ok:!1,message:`${e} and ${a} are the same field on a security risk analysis row (${e} is its security name); send one of them. Nothing was written.`};r.push([a,t[e]])}return{ok:!0,fields:Object.fromEntries(r)}}(e,n??{});if(!i.ok)return{ok:!1,message:`${a}${i.message}`};n=i.fields;const s=new Set([...wi[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=>Ji.includes(e));if(l.length>0)return{ok:!1,message:`${a}${Ns(e,l)}`};const c=Ps(e);if(c&&o.includes(c.field))return{ok:!1,message:`${a}${Us(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=gi[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=ds(t,r,i);if(e)return{ok:!1,message:`${a}${e}`};p[r]=i}}return{ok:!0,writes:p}}async function hv(e,t){let n;const r=_p("atoms_create_analysis",e);if(r)return ql(r);try{const r=await Bl(),i=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const s=t??await Af(r,e.project_id);if("unreadable"===s)return If();n=s;const o="string"==typeof(a=e.subtype)&&Object.prototype.hasOwnProperty.call(Ti,a)?Ti[a]:null;if(!o)return ql(sl(function(e){return`subtype must be one of: ${Ci.join(", ")} (got ${JSON.stringify(e)})`}(e.subtype)));const l=e.source_req_ids??[],c=e.source_function_ids??[],d=(e.source_assets??[]).map(e=>Al(e));if("hara"===o&&l.length>0)return ql(sl("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 ql(sl("source_function_ids and source_assets apply to hara only; seed a DFMEA with source_req_ids"));if(l.length>50)return ql(sl("source_req_ids supports at most 50 entries per call"));if(c.length>sp||d.length>sp)return ql(sl(`source_function_ids and source_assets support at most ${sp} 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 ql(nl("Source requirement(s)",i.join(", ")));const s=l.filter(e=>{const t=a.get(e);return"requirement"!==t.type||ev.has(t.data?.req_type)});if(s.length>0)return ql(sl(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${s.join(", ")}`))}if(void 0!==e.variant&&!js(e.subtype).includes(e.variant))return ql(sl(function(e,t){const n=js(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 lv(r,e.project_id),p=e.variant??function(e,t){return"medical"===t?Hi[e]:Di[e]}(e.subtype,u),m=await async function(e,t,n,r){const a=n??"automotive";return ba(a).includes(r)||"automotive"===a&&await ja(e,t,a)?null:function(e,t){return`Cannot create a ${fa[t]}: this project's industry is ${ha[e]}, which offers ${function(e){const t=e.map(e=>fa[e]);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}(ba(e))}. Analyses already in the project keep working. Create one of the offered analyses instead, or change the industry on the project settings page (allowed while no analysis in the project would end up outside the new industry).`}(a,r)}(r,e.project_id,u,p);if(m)return ql(sl(m,Lo));const _=as(o,p),f=is(_),h=ps(_),y={},g=[];for(const t of[...bi,...Ii]){const n=e[t];"string"==typeof n&&""!==n&&(g.push(t),h.includes(t)&&(y[t]=Al(n)))}const w=g.filter(e=>!h.includes(e));if(w.length>0)return ql(sl(gs(_,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=>lp(e)===lp(t))&&i.push(t)}if("security_tir57"===n)return a?{ok:!1,error:Ip("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(!Sp(n))return a||i.length>0?{ok:!1,error:Ip(`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:Ip(`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 ${Yu}`])};if(!a)return{ok:!0,seeds:[]};const s=await wp(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:c,assets:d});if(!t.ok)return ql(t.error);v=t.seeds}const b="hara"===o?v:l.map(e=>({text:e,functionId:null})),j=cm({...void 0!==e.hazard_id?{hazard_id:e.hazard_id}:{},...void 0!==e.goal_id?{goal_id:e.goal_id}:{}});if(j.error)return ql(sl(j.error));let k=!1;if("hara_iso26262"===_&&("ops"===s||dm(j.picks))){const t=await sm(r,e.project_id);if(null===t)return ql(om(null));if(k=function(e,t){return"hara_iso26262"===e&&null!==t&&null===ka(t)}(_,t),!k&&dm(j.picks))return ql(om(t))}const S=await fm(r,e.project_id,"atoms_create_analysis",_,k,j.picks,null,t=>Xm(r,e.project_id,t));if(S)return dv(S);if("ops"===s)return await async function(e){const{client:t,projectId:n,subtype:r,schemeId:a,seeds:i}=e,s=$i[r],o=Ei[a],l=bs(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?jp(e):{source_req:e.text},u=hm(null,e.picks),p=[Vr({type:"analysis",title:e.title,fields:{...c,...u}}),...i.map(e=>Vr({type:"requirement",title:"",req_type:s,fields:{...d(e),...u}}))],m=await Mf({projectId:n,tool:"atoms_create_analysis",key:e.key,contents:p}),_=await na(t,n,[...m.create,...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 y=Object.keys(f).length>0?jf(await kf(t,n,f)):null,g=_.get(m.create[0])?.item_id??y(o),w=m.create.slice(1).map(e=>_.get(e)?.item_id??y(l)),v=[{op_id:m.create[0],kind:"create_item",item_id:g,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,...jp(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:g,path:["relationships","children"],value:e})});for(const t of w)v.push(...uv(t,null,e.picks));const b=await xf({client:t,projectId:n,ops:v,preFound:_,labels:gv(a)}),j=m.create.map(e=>b.answers.find(t=>t.op_id===e)),k=await Tf(t,n,j.filter(e=>!!e)),S=j[0]?.item_id??g,A=i.map((t,n)=>{const a=j[n+1]?.item_id??w[n];return{..."hara"===r?kp(a,t):{id:a,source_req:t.text},...dm(e.picks)?hm(null,e.picks):{},...k.get(a)?{base_token:k.get(a)}:{}}});return $f(b.outcome,{id:S,subtype:r,title:e.title,revision:e.revision,scheme:a,variant:e.variant,labels:wm(a,e.stamp?"hazard_goal":"legacy"),...e.stamp?{event_model:"hazard_goal"}:{},...e.schemeStandard?{standard:e.schemeStandard}:{},...k.get(S)?{base_token:k.get(S)}:{},rows:A,...b.outcome.replayed?{message:Pn}:{}},b.chunks)}({client:r,projectId:e.project_id,userId:i,subtype:o,schemeId:_,variant:p,schemeStandard:f,scopeInput:y,seeds:b,title:e.title??`New ${zs(_).parent}`,revision:e.revision??"1.0",key:e.idempotency_key,stamp:k,picks:j.picks});const A=async()=>{const t=Ei[_],n=bs(_,"legacy"),a={[t]:1};a[n]=(a[n]??0)+b.length;const s=jf(await kf(r,e.project_id,a)),l=s(t),c=`New ${zs(_).parent}`,d=e.title??c,u=e.revision??"1.0",m=$i[o],h=(new Date).toISOString(),g={id:l,type:"analysis",title:d,body:"",tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis:{subtype:o,scheme:_,revision:u,...f?{standard:f}:{}},analysis_props:{variant:p,...y},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:g,p_user_id:i,p_event_source:"mcp",p_event_session_id:ib()??null,p_diff_summary:null});if(w)throw new Error(w.message);const v=(e,t)=>"hara"===o?kp(e,t):{id:e,source_req:t.text},j=[],k=[];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,...jp(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:ib()??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`),k.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:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),j.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:g,actor:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),$l(Xo({id:l,subtype:o,title:d,revision:u,scheme:_,variant:p,labels:zs(_),...f?{standard:f}:{},rows:j,...k.length>0?{link_warnings:k,warning:`${k.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=qf(n,t,r);return a?hv(e,a):ql(vl(r))}var a}function yv(e){for(const t of Object.keys(e)){const n=e[t];"string"==typeof n&&(e[t]=Al(n))}}function gv(e){const t=new Map(ks(e).map(e=>[e.key,e.label]));return{analysisLabel:e=>t.get(e)??null}}function wv(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 vv(e,t,n){const r=n.data,a=new Map;for(const n of av(r)){const r=await Xm(e,t,n);r&&a.set(n,r)}const i=await wu(e,t,{id:n.id,type:n.type,data:r},[...a.values()]),s=[];for(const r of i){const a=await Xm(e,t,r);a?.data?.asil_source===n.id&&s.push(r)}return s}async function bv(e,t){let n;try{const s=await Bl(),o=Kl();try{await tc(s,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const l=t??await Af(s,e.project_id);if("unreadable"===l)return If();n=l;const c=await Xm(s,e.project_id,e.row_id);if(!c)return ql(nl("Analysis row",e.row_id));const d=c.data;if("goal"===c.type){const t=ym(Object.keys(e.fields??{}));if(t.length>0)return ql(sl(gm(c.id,t),Lo))}if("analysis"===c.type)return async function(e,t,n,r,a,i,s){const{schemeId:o}=await mv(e,n,function(e){return"dfmea"===e?.analysis?.subtype?"dfmea":"hara"}(a),a),l=function(e,t){const n=ps(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,Ba.includes(t)||Ja.includes(t);var t});if(a.length>0)return{ok:!1,message:Ka(a)};const i=r.filter(e=>!n.includes(e));if(i.length>0)return{ok:!1,message:gs(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=ms(e);if("overall_residual_risk"===n&&""!==r&&!a.includes(r))return{ok:!1,message:ws(n,r,a)};if("software_safety_class"===n&&""!==r&&!Ai.includes(r))return{ok:!1,message:ws(n,r,Ai)};s[n]=r}return{ok:!0,writes:s}}(o,i);if(!l.ok)return ql(sl(l.message));const c=l.writes;if(yv(c),s){const{ops:t,refusals:i}=await Rf({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 xf({client:e,projectId:n,ops:t,refusals:i,labels:gv(o)}),d={...a.analysis_props??{},...c};return $f(l.outcome,{analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:fs(d),overall:hs(d,ms(o))},l.chunks)}return await(async()=>{const i=sv(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:ib()??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:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),$l(Xo({analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:fs(s),overall:hs(s,ms(o))}))):ql(tl(`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:Ef(e.base_token)}:void 0);const u=rv(d?.req_type);if(!u)return ql(sl(Sm(e.row_id,c.type,"atoms_fill_row"),Lo));const{schemeId:p}=await _v(s,e.project_id,u,d),m=await Ap(p,Object.keys(e.fields??{}),()=>Ju(s,e.project_id));if(m)return ql(sl(m,Lo));const{[Xu]:_,...f}=e.fields??{},h=cm(f);if(h.error)return ql(sl(h.error));const y=h.rest,g=void 0!==_,w=dm(h.picks),v=(g||w)&&0===Object.keys(y).length?{ok:!0,writes:{}}:fv(p,u,y,{extraKeys:"hara"===u?["effect","title"]:["effect"]});if(!v.ok)return ql(sl(v.message));const b=v.writes;yv(b);const j=mm(c.id,d?.relationships,Object.keys(b),h.picks);if(j)return ql(sl(j,Lo));if(w){const t=await fm(s,e.project_id,c.id,p,await pv(s,e.project_id,p,d),h.picks,d?.relationships,t=>Xm(s,e.project_id,t));if(t)return dv(t)}let k={};if(g){const t=await ov(s,e.project_id,p,{[Xu]:_});if(!t.ok)return t.result;Object.assign(b,t.writes),k=t.answer}const S=d?.analysis_props??null;if("ops"===l){const{ops:t,refusals:n}=await Rf({client:s,projectId:e.project_id,itemId:c.id,tokens:Ef(e.base_token),cells:wv(u,b)}),o=uv(c.id,d?.relationships,h.picks),l=await xf({client:s,projectId:e.project_id,ops:[...t,...o],refusals:n,labels:gv(p)}),m={...S??{}};for(const[e,t]of Object.entries(b))"effect"!==e&&"title"!==e&&(m[e]=t);const _=Object.keys(b).length>0&&Zs({...m})||(r=S,a=d?.relationships,i=h.picks,!0===r?.approved&&_m(a,i).length>0),f=Ds(p,m),y=Mp(d?.relationships,"event_goal").length>0||void 0!==h.picks.event_goal,g=0===l.outcome.not_applied.length&&"hara_iso26262"===p?[...new Set([...await vv(s,e.project_id,c),...y?await $m(s,e.project_id,(await Xm(s,e.project_id,c.id))?.data?.relationships,t=>Xm(s,e.project_id,t)):[]])].sort():[];return $f(l.outcome,{row_id:c.id,subtype:u,written_fields:Object.keys(b),computed_level:f,..."hara_iso26262"===p?{asil_propagated_to:g}:{},..._?{approval_cleared:!0}:{},acceptance_revoked:Of(l.answers),...k,...w?hm(d?.relationships,h.picks):{}},l.chunks)}const A=async()=>{const t=function(e,t){const n={};for(const r of["event_hazard","event_goal"])void 0!==t[r]&&_m(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 $l(Xo({row_id:c.id,subtype:u,written_fields:[],computed_level:Ds(p,S),..."hara_iso26262"===p?{asil_propagated_to:[]}:{},acceptance_revoked:!1,...k,...w?hm(d?.relationships,h.picks):{}}));const n=sv(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=Zs(r),l=(new Date).toISOString();n.metadata={...n.metadata??{},updated_at:l,updated_by:o};const{data:m,error:_}=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:ib()??null,p_diff_summary:null,p_expected_updated_at:c.updated_at});if(_)throw new Error(_.message);if(!m)return ql(tl(`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:sb(),session_id:ib(),...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 f=cv(d),y=f?await ti(f,"The row was",{readParent:()=>Xm(s,e.project_id,f),saveParent:(t,n)=>Io(()=>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:ib()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at})),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},g=y.revoked,v=Ds(p,r),j=[];if("hara_iso26262"===p){const t=Ds(p,S);if(v!==ci&&v!==t){const t=new Map;for(const r of av(n)){const n=await Xm(s,e.project_id,r);n&&t.set(r,n)}const r=await wu(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 Xm(s,e.project_id,n);if(!r)continue;const a=r.data;if(a?.asil===v&&a?.asil_source===c.id)continue;const i=a?.asil??null,d=a?.asil_source??null,u=sv(a);u.asil=v,u.asil_source=c.id,u.metadata={...u.metadata??{},updated_at:l,updated_by:o};const{error:p}=await s.rpc("save_item_with_revision",{p_item_id:r.id,p_project_id:e.project_id,p_type:r.type,p_title:r.title,p_data:u,p_user_id:o,p_event_source:"mcp",p_event_session_id:ib()??null,p_diff_summary:null,p_expected_updated_at:r.updated_at});if(p)throw new Error(p.message);await s.from("change_history").insert({item_id:r.id,project_id:e.project_id,changed_by:o,event_type:"updated",old_data:{asil:i,asil_source:d},new_data:{asil:v,asil_source:c.id},actor:sb(),session_id:ib(),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`)}),j.push(n)}}}return $l(Xo({row_id:c.id,subtype:u,written_fields:Object.keys(b),computed_level:v,...j.length>0?{asil_propagated_to:j}:{},...i?{approval_cleared:!0}:{},acceptance_revoked:g,...y.warning?{warning:y.warning}:{},...k,...w?hm(d?.relationships,h.picks):{}}))};return await A()}catch(r){const a=qf(n,t,r);return a?bv(e,a):ql(vl(r))}var r,a,i}function jv(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 kv(e,t,n,r=!1){const a=await Xm(e,t,n);if(!a)return{ok:!1,result:ql(nl("Analysis",n))};if("analysis"!==a.type)return{ok:!1,result:ql(sl(`Item ${n} is not an analysis (type='${a.type}')`))};const i=a.data,s=rv("hara"===i?.analysis?.subtype?"safety-goal":"dfmea"===i?.analysis?.subtype?"failure-mode":null);if(!s)return{ok:!1,result:ql(sl(`Analysis ${n} is missing a valid analysis.subtype`))};const o=$i[s],{variant:l,schemeId:c}=await mv(e,t,s,i),d=vm(c,i),u=Array.isArray(i?.relationships?.children)?i.relationships.children.filter(e=>"string"==typeof e):[],p=r?await _r(e,t,[a.id,...u]):new Map;let m=[];if(u.length>0){const{data:n,error:r}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",u);if(r)throw new Error(r.message);const a=new Map((n??[]).filter(e=>!e.deleted_at&&u.includes(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 av(e.data))_.add(t);for(const t of iv(e.data))_.add(t);for(const t of Tp(e.data?.relationships))_.add(t)}const f=new Map,h=new Map;let y=[];if(_.size>0){const{data:n,error:r}=await e.from("items").select(lu).eq("project_id",t).is("deleted_at",null).in("id",[..._]);if(r)throw new Error(r.message);y=n??[];for(const e of y)f.set(e.id,e.updated_at),h.set(e.id,e.content_changed_at??e.updated_at)}const g=m.length>0?gu(m,[...y,...await yu(e,t)]):new Map,w=await bp(e,t,function(e){return hp(e.map(e=>cp(e).source_function_id))}(m.map(e=>({analysis_props:e.data?.analysis_props??null})))),v=d?await xm(e,t):null,b=v?Im(v):null,j="security_tir57"===c?await async function(e,t,n){const r=e=>vu(e.data?.relationships?.affects),a=[...new Set(n.flatMap(r))];if(0===a.length)return new Set;const i=await su(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,k=new Map,S=m.map(e=>{const t=e.data?.analysis_props??{},n=g.get(e.id)??[],r=av(e.data).filter(e=>f.has(e)),a=iv(e.data).filter(e=>f.has(e)),i=n.length>0,s=Ds(c,t),o=Tp(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=qs(t);return"QM"===e||e===ci?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=Rs(t);return"Low"!==e&&e!==ci?`${e.toLowerCase()} risk uncontrolled`:null}if("security_tir57"===e){const e=Ts(t);return Va(e)?`${e.toLowerCase()} security risk uncontrolled`:null}const a=parseInt(Ds(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);k.set(e.id,{props:t,affectsLinked:j.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:Is(c,s),is_gap:null!==u,gap_rule:u,is_critical:Hs(c,t,i,d),is_stale:Fs(t,r,e=>(l.has(e)?h.get(e):f.get(e))??null,pp({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?Ms(t):"security_tir57"===c?Cs(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 wi[c])p[e]=t[e]??null;return Object.assign(p,function(e,t){const n=dp(cp(e).source_function_id).trim();if(!n)return{};const r=up(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{...bm(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:is(c)??null,variant:l,labels:wm(c,d?"hazard_goal":"legacy"),...d?{event_model:"hazard_goal"}:{},acceptability:As(c),definitions:Ss(c),control_types:Ws(c),field_labels:ks(c),scope:ps(c).length>0?fs(i?.analysis_props):null,overall:ps(c).length>0?hs(i?.analysis_props,ms(c)):null,threat_model:"security_tir57"===c?jv(i?.analysis_props):null,acceptance:Za(i?.analysis_props)},schemeId:c,parentProps:i?.analysis_props??null,revisions:p,rows:S,gapFacts:k,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 Sv(e){try{return await async function(e,t=po){let n;const r=new Promise((e,r)=>{n=setTimeout(()=>r(new fo(t)),t)});try{return await Promise.race([e(),r])}finally{clearTimeout(n)}}(()=>async function(e){const t=await Bl(),n=!0===await Yr(t,e.project_id),r=await kv(t,e.project_id,e.analysis_id,n);if(!r.ok)return r.result;if(!n)return $l(Xo({analysis:r.analysis,rows:r.rows,counts:r.counts}));const a=async e=>{const t=r.revisions.get(e);return t?cr(t,"analysis"):void 0},i=new Map(ks(r.schemeId).map(e=>[e.key,e.label])),s=await yr(t,e.project_id,[r.analysis.id,...r.rows.map(e=>e.id)],{analysisLabel:e=>i.get(e)??null}),o=await a(r.analysis.id),l=await Promise.all(r.rows.map(async e=>{const t=await a(e.id);return{...e,...t?{base_token:t}:{},editing_now:s.get(e.id)??[]}}));return $l(Xo({analysis:{...r.analysis,...o?{base_token:o}:{},editing_now:s.get(r.analysis.id)??[]},rows:l,counts:r.counts}))}(e))}catch(e){return ql(vl(e))}}async function Av(e,t,n,r){const a=cv(n);if(!a)return;const i=await Xm(e,t,a);if(!i)return;const{revoked:s,parentProps:o}=ei(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:ib()??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 Iv(e,t){let n;try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();if(n=i,e.row_id===e.req_id)return ql(sl("row_id and req_id must be different items"));const s=await Xm(r,e.project_id,e.row_id);if(!s)return ql(nl("Analysis row",e.row_id));const o=s.data;if("goal"===s.type)return await xv(r,e,s,i,null);const l=rv(o?.req_type);if(!l)return ql(sl(Sm(e.row_id,s.type,"atoms_link_mitigation"),Lo));if("remove"!==e.action&&Mp(o?.relationships,"event_goal").length>0){const{schemeId:t}=await _v(r,e.project_id,l,o),n=await pv(r,e.project_id,t,o),a=n?await Xm(r,e.project_id,Mp(o?.relationships,"event_goal")[0]):null,c=function(e,t,n){if(!e)return null;const r=Mp(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 xv(r,e,a,i,s.id)}const c=await Xm(r,e.project_id,e.req_id);if(!c)return ql(nl("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 ql(sl(cu));if(!bu(e.row_id,o,e.req_id,d))return ql(sl(ju(e.row_id,e.req_id),Lo));const{schemeId:t}=await _v(r,e.project_id,l,o);if("ops"===i){const n={op_id:Hr(),kind:"remove",item_id:e.row_id,path:["relationships","mitigated_by"],value:e.req_id},a=await xf({client:r,projectId:e.project_id,ops:[n],labels:gv(t)});return $f(a.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,acceptance_revoked:Of(a.answers)},a.chunks)}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:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await Av(r,e.project_id,o,a);const i=await Xm(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=sv(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:ib()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});if(n)throw new Error(n.message)}return $l(Xo({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t}))};return await n()}if("requirement"!==c.type||ev.has(d?.req_type))return ql(sl(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));const{schemeId:u}=await _v(r,e.project_id,l,o);if(Vs(u)&&d?.req_type!==ii)return ql(sl(Bs(e.req_id,u)));const p=Ls(u);if(0===p.length&&void 0!==e.control_type)return ql(sl(Js(u)));if(p.length>0&&!e.control_type)return ql(sl(Gs(u)));if(!(void 0===e.control_type||ss(e.control_type)&&function(e,t){return Ls(e).some(e=>e.id===t)}(u,e.control_type)))return ql(sl(Gs(u)));if("dfmea"===l&&!e.role)return ql(sl(`role is required for dfmea mitigation links. Choose one of: ${di.join(", ")}`));if("hara"===l&&e.role)return ql(sl("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:Hr(),kind:"add",item_id:e.row_id,path:["relationships","mitigated_by"],value:n},i=await xf({client:r,projectId:e.project_id,ops:[a],labels:gv(u)});return $f(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}:{},acceptance_revoked:Of(i.answers)},i.chunks)}const m=async()=>{let t=ci;if("hara_iso26262"===u){t=Ds(u,o?.analysis_props);const r=d?.asil;if(t!==ci&&"string"==typeof r&&r.length>0&&r!==t&&!0!==e.override)return ql((i=t,{...tl(`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:c.updated_at,p_role:m});if(_)throw new Error(_.message);let f,h;if(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:sb(),session_id:ib()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await Av(r,e.project_id,o,a),e.control_type&&ss(e.control_type)){const t=await Xm(r,e.project_id,e.row_id)??s,n=sv(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:ib()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});if(l)throw new Error(l.message);f=e.control_type}if("hara_iso26262"===u&&t!==ci){const n=await Xm(r,e.project_id,e.req_id);if(n){const i=n.data,o=i?.asil??null,l=i?.asil_source??null,c=sv(i);c.asil=t,c.asil_source=s.id;const d=(new Date).toISOString();c.metadata={...c.metadata??{},updated_at:d,updated_by:a};const{error:u}=await 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:c,p_user_id:a,p_event_source:"mcp",p_event_session_id:ib()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at});if(u)throw new Error(u.message);await r.from("change_history").insert({item_id:n.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{asil:o,asil_source:l},new_data:{asil:t,asil_source:s.id},actor:sb(),session_id:ib(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${o??"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 $l(Xo({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}:{}}))};return await m()}catch(r){const a=qf(n,t,r);return a?Iv(e,a):ql(vl(r))}}async function xv(e,t,n,r,a){const i="hara_iso26262";if(void 0!==t.role)return ql(sl("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 ql(sl(Js(i)));if(t.req_id===n.id)return ql(sl("row_id and req_id must be different items"));const s=await Xm(e,t.project_id,t.req_id);if(!s)return ql(nl("Requirement",t.req_id));const o=s.data,l="remove"===t.action?"remove":"add";if("remove"===l){if(void 0!==t.override)return ql(sl(cu));if(!bu(n.id,n.data,t.req_id,o))return ql(sl(ju(n.id,t.req_id),Lo))}else{if("requirement"!==s.type||ev.has(o?.req_type))return ql(sl(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${t.req_id}`));if(Vs(i)&&o?.req_type!==ii)return ql(sl(Bs(t.req_id,i)))}if("ops"!==r)return ql(Ma());const c={op_id:Hr(),kind:l,item_id:n.id,path:["relationships","mitigated_by"],value:t.req_id},d=await xf({client:e,projectId:t.project_id,ops:[c],labels:gv(i)}),u=await Xm(e,t.project_id,t.req_id),p=u?.data??{};return $f(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:Of(d.answers)},d.chunks)}async function $v(e){try{const n=await Bl(),r=await kv(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=os(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=Ys(r.schemeId).some(e=>"requirement"===e.scope)?await async function(e,t,n){const r=(await tu(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null).eq("type","requirement"),Ld)).filter(e=>e.data?.req_type===ii&&function(e,t){const n=ls(e);return n.length>0&&n===ls(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 su([...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??ci,severity:Qs(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=Xw(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:ys(e),overallJudged:""!==hs(e,a?Ha:Si).residual_risk,everyRowSettled:t.every(e=>e.linked&&e.residualLevel!==ci),catalogsDraft:r,accepted:"accepted"===e?.acceptance_state}}(r.parentProps,o,r.schemeId,l),d=function(e,t,n,r){const a=[];for(const i of Ys(e)){if("analysis"===i.scope){if(!r||!i.matchesAnalysis||!i.matchesAnalysis(r))continue;a.push({kind:i.kind,label:i.label(1),rowIds:[],reqIds:[],count:1,fix:i.fix,fixLabel:i.fixLabel});continue}if("requirement"===i.scope){if(0===n.length)continue;a.push({kind:i.kind,label:i.label(n.length),rowIds:[],reqIds:[...n],count:n.length,fix:i.fix,fixLabel:i.fixLabel});continue}const e=i.matches;if(!e)continue;const s=t.filter(t=>e(t)).map(e=>e.id);0!==s.length&&a.push({kind:i.kind,label:i.label(s.length),rowIds:s,reqIds:[],count:s.length,fix:i.fix,fixLabel:i.fixLabel})}return a}(r.schemeId,o,s,c),u=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!==ci&&"QM"!==e&&Rp(e)>0,r=[],a=[],i=[],s=new Map,o=[],l=new Set;for(const c of t){const t=qs(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,qs(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,Am(n))).map(e=>{const t=ts.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)]}(d,r.stamped.index,r.stamped.rows):d,p=u.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}:{}}));return $l(Xo({analysis_id:r.analysis.id,subtype:r.analysis.subtype,scheme:r.analysis.scheme,labels:r.analysis.labels,gaps:a,count:(t=u,t.reduce((e,t)=>e+(t.informational?0:t.count),0)),gap_kinds:p,system_level:i.level,system_level_source:i.source}))}catch(e){return ql(vl(e))}var t}async function qv(e,t){let n;const r=_p("atoms_propose_rows",e);if(r)return ql(r);try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();n=i;const s=await Xm(r,e.project_id,e.analysis_id);if(!s)return ql(nl("Analysis",e.analysis_id));if("analysis"!==s.type)return ql(sl(`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 ql(sl(`Analysis ${e.analysis_id} is missing a valid analysis.subtype`));const{variant:d,schemeId:u}=await mv(r,e.project_id,c,o);if("hara"===c&&e.source_req)return ql(sl("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 ql(sl("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 ql(sl("rows must contain at least one drafted row"));if(p.length>oi)return ql(sl(`Propose rows accepts at most ${oi} 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 Ap(u,Object.keys(p[t]??{}),()=>Ju(r,e.project_id));if(n)return ql(sl(`row ${t+1}: ${n}`,Lo));const a=cm(p[t]??{});if(a.error)return ql(sl(`row ${t+1}: ${a.error}`));const i=fv(u,c,a.rest,{extraKeys:"hara"===c?["effect","title"]:["effect"],where:`row ${t+1}`});if(!i.ok)return ql(sl(i.message));yv(i.writes);const s=mm(`row ${t+1}`,null,Object.keys(i.writes),a.picks);if(s)return ql(sl(s,Lo));m.push(i.writes),_.push(a.picks)}const f=vs(o);for(let t=0;t<_.length;t++){const n=await fm(r,e.project_id,`row ${t+1}`,u,vm(u,o),_[t],null,t=>Xm(r,e.project_id,t));if(n)return dv(n)}const h=await async function(e,t,n,r){if(void 0===r)return{ok:!0,seed:null};const a=await Ap(n,[Xu],()=>Ju(e,t));if(a)return{ok:!1,error:Ip(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 wp(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 ql(h.error);const y=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=$i[r],l=bs(a,e.model),c=i.map((t,a)=>function(e,t,n,r,a){return function(e,t){return er({analysis_id:e,writes:Wr(t)})}(e,{...t,__seed:"hara"===n?r?r.functionId??r.text:"":a??null})}(n.analysis_id,{...t,...hm(null,e.rowPicks[a]??{})},r,e.seed,n.source_req)),d=await Mf({projectId:s,tool:"atoms_propose_rows",key:n.idempotency_key,contents:c}),u=await na(t,s,[...d.create,...d.link]),p=d.create.filter(e=>!u.has(e)).length,m=p>0?jf(await kf(t,s,{[l]:p})):null,_=d.create.map(e=>u.get(e)?.item_id??m(l)),f=[],h=[];i.forEach((t,a)=>{const i={source_req:"dfmea"===r?n.source_req??null:null,..."hara"===r?xp(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=us(t)),h.push({writes:t,props:i}),f.push({op_id:d.create[a],kind:"create_item",item_id:_[a],path:[],value:{type:"requirement",title:l,data:{body:s,req_type:o,analysis_props:i}}})}),_.forEach((e,t)=>{f.push({op_id:d.link[t],kind:"add",item_id:n.analysis_id,path:["relationships","children"],value:e})}),_.forEach((t,n)=>f.push(...uv(t,null,e.rowPicks[n]??{})));const y=await xf({client:t,projectId:s,ops:f,preFound:u,labels:gv(a)}),g=d.create.map(e=>y.answers.find(t=>t.op_id===e)),w=await Tf(t,s,g.filter(e=>!!e)),v=h.map((t,n)=>{const r=g[n]?.item_id??_[n];return{id:r,written_fields:Object.keys(t.writes),computed_level:Ds(a,t.props),...dm(e.rowPicks[n]??{})?hm(null,e.rowPicks[n]):{},...w.get(r)?{base_token:w.get(r)}:{}}});return $f(y.outcome,{analysis_id:n.analysis_id,subtype:r,scheme:a,...e.variant?{variant:e.variant}:{},labels:wm(a,e.model),...$p(r,e.seed,n.source_req),rows:v,count:v.length,max_rows:oi,approved:!1,acceptance_revoked:Of(y.answers),...y.outcome.replayed?{message:Pn}:{}},y.chunks)}({client:r,params:e,parent:s,subtype:c,schemeId:u,variant:d,validatedRows:m,seed:y,model:f,rowPicks:_});const g=async()=>{const t=(new Date).toISOString(),n=$i[c],i=[],s=[],o=bs(u,f),l=jf(await kf(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?xp(y):{},approved:!1,approved_at:null,approved_by:null,field_source:{}};let _="",f="";for(const[e,t]of Object.entries(d))"effect"===e?_=t:"title"===e?f=t:(m[e]=t,"failure_mode"===e&&"dfmea"===c&&(f=t)),m.field_source[e]="mcp";f||(f=us(d));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:g}=await Io(()=>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:ib()??null,p_diff_summary:null}));if(g)throw new Error(g.message);const{error:w}=await Io(()=>r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:p,p_to_id:e.analysis_id,p_type:"parent",p_action:"add",p_user_id:a,p_event_source:"mcp"}));w&&(process.stderr.write(`[atoms-mcp] Warning: proposed row parent link sync failed for ${p}: ${w.message}\n`),s.push({row_id:p,message:w.message})),await r.from("change_history").insert({item_id:p,project_id:e.project_id,changed_by:a,event_type:"created",old_data:null,new_data:h,actor:sb(),session_id:ib(),reason:"Row proposed through atoms_propose_rows (machine-proposed, unapproved)"}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),i.push({id:p,written_fields:Object.keys(d),computed_level:Ds(u,m)})}let p=!1,_=null;if(i.length>0)try{for(let t=0;t<3;t+=1){const n=await Xm(r,e.project_id,e.analysis_id);if(!n)break;const i=n.data,{revoked:s,parentProps:o}=ei(i);if(!s)break;const l={...i,analysis_props:o},{error:c}=await Io(()=>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:ib()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at}));if(!c){p=!0;break}if(!(t<2&&/stale_item_write/i.test(c.message??""))){process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${n.id}': ${c.message}\n`),_=`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 $l(Xo({analysis_id:e.analysis_id,subtype:c,scheme:u,...d?{variant:d}:{},labels:wm(u,f),...$p(c,y,e.source_req),rows:i,count:i.length,max_rows:oi,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 g()}catch(r){const a=qf(n,t,r);return a?qv(e,a):ql(vl(r))}}async function Ev(e,t){let n;try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();n=i;const s=await Xm(r,e.project_id,e.row_id);if(!s)return ql(nl("Analysis row",e.row_id));const o=s.data,l=rv(o?.req_type);if(!l)return ql(sl(Sm(e.row_id,s.type,"atoms_suggest_field"),Lo));const{schemeId:c}=await _v(r,e.project_id,l,o),d=e.rationale?function(e,t){return gi[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 ql(sl(`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 ov(r,e.project_id,c,u);if(!p.ok)return p.result;const m=0===Object.keys(p.rest).length?{ok:!0,writes:{}}:fv(c,l,p.rest,{extraKeys:"hara"===l?["effect","title"]:["effect"]});if(!m.ok)return ql(sl(m.message));const _=m.writes;yv(_),Object.assign(_,p.writes);const f=p.answer;if("ops"===i){const{ops:t,refusals:n}=await Rf({client:r,projectId:e.project_id,itemId:s.id,tokens:Ef(e.base_token),cells:wv(l,_)}),a=await xf({client:r,projectId:e.project_id,ops:t,refusals:n,labels:gv(c)}),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=Zs({...i}),m=Object.entries(u).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return $f(a.outcome,{row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(_),...d?{rationale_field:d}:{},...p?{approval_cleared:!0}:{},row:{id:s.id,computed_level:Ds(c,i),approved:!0===i.approved&&!p,mcp_fields:m,...Object.fromEntries(wi[c].map(e=>[e,i[e]??null])),...f},acceptance_revoked:Of(a.answers),...f},a.chunks)}const h=async()=>{const t=sv(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=Zs(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:ib()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(h)throw new Error(h.message);if(!m)return ql(tl(`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:sb(),session_id:ib(),reason:`${e.field} suggested through atoms_suggest_field (machine-proposed, unapproved)`+(u?"; approval cleared (a signature never covers content the approver did not see)":"")}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=cv(o),g=y?await ti(y,"The suggestion was",{readParent:()=>Xm(r,e.project_id,y),saveParent:(t,n)=>Io(()=>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:ib()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at})),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},w=Object.entries(n.field_source).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return $l(Xo({row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(_),...d?{rationale_field:d}:{},...u?{approval_cleared:!0}:{},acceptance_revoked:g.revoked,...g.warning?{warning:g.warning}:{},row:{id:s.id,computed_level:Ds(c,n),approved:!0===n.approved,mcp_fields:w,...Object.fromEntries(wi[c].map(e=>[e,n[e]??null])),...f},...f}))};return await h()}catch(r){const a=qf(n,t,r);return a?Ev(e,a):ql(vl(r))}}async function Ov(e,t){let n;try{const r=await Bl(),a=Kl();try{await tc(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}const i=t??await Af(r,e.project_id);if("unreadable"===i)return If();n=i;const s=await Xm(r,e.project_id,e.row_id);if(!s)return ql(nl("Analysis row",e.row_id));const o=s.data,l=rv(o?.req_type);if(!l)return ql(sl(Sm(e.row_id,s.type,"atoms_approve_row"),Lo));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 ql(sl(`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 ql(sl(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 _v(r,e.project_id,l,o),p=o?.analysis_props??{},m=Ds(u,p);if(m===ci)return ql(sl(`${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=Al(e.note??""),n=(new Date).toISOString(),{ops:a,refusals:i}=await Rf({client:r,projectId:e.project_id,itemId:s.id,tokens:Ef(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 xf({client:r,projectId:e.project_id,ops:a,refusals:i,labels:gv(u)}),_=Object.entries(p.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return $f(o.outcome,{row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:c,approved_at:n,approved_note:t,approver_role:d,computed_level:m,cleared_markers:_,acceptance_revoked:Of(o.answers)},o.chunks)}const _=async()=>{const t=sv(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=Al(e.note??""),_=(new Date).toISOString();n.approved=!0,n.approved_at=_,n.approved_by=c,n.approved_note=i;const f=[];for(const[e,t]of Object.entries(n.field_source))"mcp"===t&&(n.field_source[e]="user",f.push(e));f.sort(),t.metadata={...t.metadata??{},updated_at:_,updated_by:a};const{data:h,error:y}=await r.rpc("save_item_with_revision",{p_item_id:s.id,p_project_id:e.project_id,p_type:s.type,p_title:s.title,p_data:t,p_user_id:a,p_event_source:"mcp",p_event_session_id:ib()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(y)throw new Error(y.message);if(!h)return ql(tl(`Approval silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await r.from("change_history").insert({item_id:s.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{approved:!0===p.approved,approved_at:p.approved_at??null,approved_by:p.approved_by??null,approved_note:p.approved_note??""},new_data:{approved:!0,approved_at:_,approved_by:c,approved_note:i},actor:sb(),session_id:ib(),reason:`${e.row_id} approved by ${c} via atoms_approve_row`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const g=cv(o);if(g){const t=await Xm(r,e.project_id,g);if(t){const{revoked:n,parentProps:i}=ei(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:ib()??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 $l(Xo({row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:c,approved_at:_,approved_note:i,approver_role:d,computed_level:m,cleared_markers:f}))};return await _()}catch(r){const a=qf(n,t,r);return a?Ov(e,a):ql(vl(r))}}B(nv,{approveRowHandler:()=>Ov,createAnalysisHandler:()=>hv,fillRowHandler:()=>bv,getAnalysisHandler:()=>Sv,getGapsHandler:()=>$v,linkMitigationHandler:()=>Iv,proposeRowsHandler:()=>qv,suggestFieldHandler:()=>Ev});var Rv=V({"src/tools/analysis.ts"(){ic(),ve(),i_(),Sf(),To(),lb(),Ml(),da(),Nf(),da(),wo(),io(),Op(),op(),tv(),qa(),Nm(),rm(),La(),xu(),ns(),ev=new Set(["safety-goal","failure-mode"])}}),Mv={};async function Tv(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=Xw(n?.scenario_catalogs??[]);return a.ok?a.value:[]}async function Cv(e){try{const t=await Bl(),n=Math.min(Math.max(e.limit??50,1),200),r=Math.max(e.offset??0,0),a=await Tv(t,e.project_id);return $l(Xo(a.slice(r,r+n),el(a.length,n,r)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}}async function Dv(e){const t=_p("atoms_mutate_scenario_catalog",e);if(t)return ql(t);try{const t=await Bl();Kl();try{await tc(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return ql(il("Viewer"));throw e}if("string"!=typeof(n=e.op)||!Qw.includes(n))return ql(sl("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 Tv(t,e.project_id)).length>=Gw)return ql(sl(`This project already carries the maximum of ${Gw} 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=Al(e.name)),void 0!==e.entry_id&&(a.entry_id=e.entry_id),void 0!==e.text&&(a.text=Al(e.text)),void 0!==e.function_ids){const n=await async function(e,t,n){const r=await Ju(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:np,next_steps:[...rp],code:"function_items_off",retryable:!1}};const a=await vp(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 ql(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?ql(re(s.message)??sl(s.message)):$l(Xo({scenario_catalogs:i?.scenario_catalogs??[]}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?ql(ol()):ql(kl(e instanceof Error?e.message:String(e)))}var n}B(Mv,{listScenarioCatalogsHandler:()=>Cv,mutateScenarioCatalogHandler:()=>Dv});var Hv,Fv,Nv,Pv,Uv,zv,Lv,Wv,Vv,Bv,Jv,Gv,Qv,Kv,Yv,Zv,Xv=V({"src/tools/catalogs.ts"(){ic(),de(),Ml(),Op(),tv()}}),eb={};function tb(t){Ye(t.toolName)&&function(t,n){const r=`ui://${n.toolName}/${n.htmlFile}`,a=function(e,t){const n=h(import.meta.url),r=l.dirname(n);return l.resolve(r,"apps","src","apps",e,t)}(n.appName,n.htmlFile),i=[...Vm.resourceDomains,...n.extraResourceDomains??[]];v(t,n.toolName,{title:n.title,description:n.description,inputSchema:n.inputSchema,annotations:n.annotations,_meta:{ui:{resourceUri:r}}},n.handler),b(t,`${n.title} UI`,r,{mimeType:j},async()=>{const t=await e.readFile(a,"utf-8");return{contents:[{uri:r,mimeType:j,text:t,_meta:{ui:{csp:{resourceDomains:i}}}}]}})}(Pv,t)}function nb(e){return void 0===e?.requestId?void 0:String(e.requestId)}function rb(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 Et||/^auth_unavailable:/.test(r)?ql(Tt()):Zt(r)?ql(ul()):/not authenticated/i.test(r)?ql(ol()):wl(t)||Xt(r)?ql(ll()):ql(n())}function ab(e,t){return async(n,r)=>{let a="",i=null,s=!1;try{i=await Bl(),a=Kl()}catch(e){i=null,s=e instanceof Et}if(i){const e=await async function(e,t){let n;try{n=await Tl(e,t)}catch(e){return process.stderr.write(`[atoms-mcp] platform_status lookup failed: ${e instanceof Error?e.message:String(e?.message??e)}\n`),wl(e)?ll():tl("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?rl("account"):"pending"===n?tl("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 ql(e)}if(i&&await Je(i,a),!Ne&&x.has(e))return ql(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}:ol());if(!ce.has(e)){let t;try{t=await Ql(async()=>(i=await Bl(),a=Kl(),async function(e,t,n,r){if(ce.has(n))return{refused:!1};const a=await ue(e,t);if(pe(a))return{refused:!0,reason:"viewer_everywhere"};const i=me(a);if(0===i.size)return{refused:!1};const{projectIds:s}=await _e(e,r);for(const t of s){const n=await fe(e,t);if(n&&i.has(n))return{refused:!0,reason:"viewer_in_org"}}return{refused:!1}}(i,a,e,n)))}catch(e){return rb("viewer gate",e,ye)}if(t.refused)return ql((o=t.reason,{status:"error",message:se,next_steps:[..."viewer_everywhere"===o?le:oe]}))}var o;{let t;try{t=await Ql(async()=>{let t=null,r=null;try{t=await Bl(),i=t,a=Kl()}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=>Ae(e,t,n))||!!a(e=>e.require_confirmation_for.includes(t))||we.has(t)&&a(e=>te(e,"atoms_create_level").allowed)}(a,n,r)){const e=a.orgs[0]?.effective??G,s=Ae(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 ge.some(e=>"string"==typeof l[e])&&(i||null!==e.project_scope)&&(c=await _e(t,r)),i&&(c.unresolved>0||c.projectIds.some(e=>e!==i))?o(i):ae(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 ge){const n=r[t];if("string"!=typeof n)continue;const s=await he(e,n);s?a.push(s):i++}const s=[];for(const n of a)s.push({projectId:n,orgId:await Ie(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:je(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:ke(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=Ae(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=ae(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:Ve(),toolName:e,params:n,envProjectId:Oe(),envProjectRefusal:cl,envOrgId:Re(),envOrgRefusal:dl,reload:t?()=>async function(e,t){return De=0,await Je(e,t),Ce}(t,a):void 0});var s})}catch(e){return rb("project scope",e,ie)}if(t)return ql(t)}if(!i)return t(n,r);const l=await async function(e,t){const n=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Rc,r=new Date,a=new Date(r.getTime()-Mc);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())+Mc-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*Mc);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 ql(ul(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(()=>(ic(),Vl));await t(i,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(Ml(),Ko));return ql(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 Gc(e,Nv)}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:zv,client_name:Lv,client_version:Nv};try{!function(e,t,n){const r=Oc(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 Bl(),a,t)}catch{}}}}function ib(){return zv}function sb(){return Wv}function ob(){return Lv}B(eb,{ATOMS_MCP_SERVER_VERSION:()=>Nv,getMcpActor:()=>sb,getMcpClientName:()=>ob,getMcpSessionId:()=>ib,server:()=>Pv});var lb=V({"src/server.ts"(){jc(),qc(),Pc(),Uc(),et(),Me(),Ge(),fd(),de(),Ee(),Yt(),hd(),io(),X(),Jm(),Op(),Dd(),da(),Qo(),Nm(),ic(),Wl(),ve(),Ml(),zn(),Ht(),Gm(),Hv=S(import.meta.url),Fv=Hv("../package.json"),Nv=Fv.version,function(e){const t=e=>e.endsWith(z)?e:`${e}\n\n${z}`;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)}}(Pv=new k({name:"atoms-mcp-server",version:Nv})),function(e){Ue=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&&Pe.set(e,r),r}}(Pv),Uv=(e,t,n)=>{if(Ye(e))return Pv.registerTool(e,t,n)},zv=m(),Lv=Wt(process.env.ATOMS_CLIENT_NAME),Wv=Vt(Lv),Uv("atoms_status",{title:"ATOMS MCP Health Check",description:Wm.atoms_status,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>Qc(await(async()=>{const e=(e,t)=>async function(e,t,n){try{const e=await(async()=>async function(e,t){Ol.delete(t);const n=await Tl(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=pe(await ue(e,t))}catch{s=null}return{platform_status:n,org_suspended:r,viewer_only:s}}(await Bl(),Kl()))();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:se,next_steps:[...le]}:{status:"authenticated",email:t,message:(e.org_suspended??[]).length>0?Rl: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(()=>(ft(),tt)),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(()=>(Lt(),Ft)),{email:n}=await t(),{invalidateClient:r}=await Promise.resolve().then(()=>(ic(),Vl));return r(),{content:[{type:"text",text:Cl(await e(n,"Token was expired but has been refreshed. You're good to go!"))}]}}catch(e){return e instanceof Et?{content:[{type:"text",text:JSON.stringify({...Tt(),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:Cl(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)}]}}})(),Nv)),Uv("atoms_list_projects",{title:"List ATOMS Projects",description:Wm.atoms_list_projects,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(l_(),s_));return e()})),Uv("atoms_list_items",{title:"List ATOMS Items",description:Wm.atoms_list_items,inputSchema:{project_id:w.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:w.enum(Jp).optional().describe("Filter by item type"),domain:w.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:w.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:w.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:w.number().int().min(0).default(0).describe("Pagination offset (default 0)"),after:w.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:w.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:w.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns items as they were at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(u_(),c_));return t(e)})),Uv("atoms_get_item",{title:"Get ATOMS Item Details",description:Wm.atoms_get_item,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:w.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:w.string().datetime().optional().describe("Optional ISO 8601 timestamp. Returns the item as it was at that moment. Mutually exclusive with baseline_id.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(O_(),I_));return t(e)})),Uv("atoms_list_changes",{title:"List ATOMS Changes",description:U,inputSchema:{project_id:w.string().uuid(),since_seq:w.number().int().min(0).optional(),limit:w.number().int().min(1).max(500).default(100)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_changes",async e=>{const{listChangesHandler:t}=await Promise.resolve().then(()=>(C_(),R_));return t(e)})),Uv("atoms_search",{title:"Search ATOMS Items",description:Wm.atoms_search,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),query:w.string().min(1).max(1e3).describe("Search text"),type:w.enum(Jp).optional().describe("Filter by item type"),asset:w.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:w.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:w.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}},ab("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(N_(),H_));return t(e)})),Uv("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:Wm.atoms_semantic_search,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),query:w.string().min(1).max(1e3).describe("Natural-language concept query"),type:w.enum(Jp).optional().describe("Filter by item type"),limit:w.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(z_(),P_));return t(e)})),tb({appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:Wm.atoms_get_coverage,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),domain:w.string().max(64).optional().describe("Filter by domain tag"),level:w.string().max(32).optional().describe("Filter by level"),baseline_id:w.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:w.string().datetime().optional().describe("Compute coverage as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:ab("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(J_(),L_));return t(e)})}),Uv("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\nArgs:\n - project_id (string, UUID): The project to report on\n - release_id (string, UUID, optional): A formal Release (a baselines row with\n a release_version). Defaults to the project's CURRENT Release\n (release_status = 'released'). Without one, only rerun is returned.\n - include_gaps (boolean, optional, default false): Also return the not-run\n (test x unit x value) points for the Release.\n\nReturns:\n { release: {id, version, status} or null,\n readiness: {requirements, verified, failing, incomplete, not_run, stale,\n points_total, points_run}. Each requirement is counted once:\n verified = state verified and not stale; incomplete = state incomplete\n and not stale; failing = state failing; not_run = state not-run;\n stale = state verified or incomplete and stale. A stale requirement is\n counted under stale only (never also under verified or incomplete), so\n verified + failing + incomplete + not_run + stale = requirements,\n requirements: [{requirement_id, state, stale, points_total, points_run}],\n rerun: [{requirement_id, test_case_ids}],\n gaps?: [{tc_id, asset, point_key}] }\n readiness, requirements and gaps are left out when release is null.\n An empty requirements array with a \"hint\" field means the projection has not\n been rebuilt for this project yet, NOT that everything is unverified.\n\nExamples:\n - \"Are we ready to ship 2.0?\" → atoms_verification_status(project_id)\n - \"What's still not run for release R?\" → atoms_verification_status(project_id, release_id=\"...\", include_gaps=true)\n - \"Which tests need a rerun?\" → atoms_verification_status(project_id), then read rerun",inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),release_id:w.string().uuid().optional().describe("Formal Release (baselines row) UUID; defaults to the project's current Release"),include_gaps:w.boolean().default(!1).describe("Include the not-run (test x unit x value) points for the Release")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_verification_status",async e=>{const{verificationStatusHandler:t}=await Promise.resolve().then(()=>(ef(),G_));return t(e)})),Uv("atoms_get_history",{title:"Get Item Change History",description:Wm.atoms_get_history,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).describe("Item ID"),limit:w.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(lf(),sf));return t(e)})),tb({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:Wm.atoms_export_mermaid,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),root_item_id:w.string().max(20).optional().describe("Root item ID to start from"),depth:w.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:w.boolean().default(!0).describe("Include test case links"),baseline_id:w.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:w.string().datetime().optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:ab("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(wf(),ff));return t(e)})}),Bv=()=>w.string().max(128).optional().describe(C),Jv=()=>w.enum(["edit","apply_mine"]).describe(D).optional(),Gv=()=>w.string().min(1).max(600).optional().describe(F),Qv=(Vv=()=>w.union([w.string().min(1).max(_n),w.array(w.string().min(1).max(_n)).min(1).max(fn)]).describe(T).optional())(),Kv=Bv(),Uv("atoms_create_item",{title:"Create ATOMS Item",description:Wm.atoms_create_item,inputSchema:{project_id:w.string().uuid().describe("UUID of the target project"),type:w.enum(Fp).describe(Np),title:w.string().min(1).max(500).describe("Item title"),req_type:w.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe(bc),body:w.string().max(5e4).optional().describe("Rich text body"),summary:w.string().max(2e3).optional().describe("Brief summary"),domains:w.array(w.string().max(64)).max(20).optional().describe("Domain tags"),level:w.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:w.array(w.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:w.record(w.string().max(60),w.string().max(1e4)).optional().describe("Project-field values keyed by defined field name"),echo:w.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens"),idempotency_key:Bv()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Zh(),Kh));return t(e)})),Yv={steps:w.array(w.object({id:w.string().describe(cd),instruction:w.string().describe("What the tester does"),test_data:w.string().optional().describe("Optional test data for the step"),expected:w.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. "+cd),params:w.array(w.object({name:w.string().describe("Parameter name; steps reference it as {name}"),unit:w.string().optional().describe("Optional unit (e.g. km/h, V, m)"),values:w.array(w.union([w.string(),w.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. "+ld)},Uv("atoms_update_item",{title:"Update ATOMS Item",description:Wm.atoms_update_item,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).optional().describe("Item ID (single form)"),title:w.string().min(1).max(500).optional().describe("New title"),body:w.string().max(5e4).optional().describe("New body"),summary:w.string().max(2e3).optional().describe("New summary"),domains:w.array(w.string().max(64)).max(20).optional().describe("New domain tags (a function tag is not a domain and is rejected)"),level:w.string().max(32).optional().describe("New level"),status:w.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:w.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe(bc),fields:w.record(w.string().max(60),w.string().max(1e4)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),...Yv,expected_updated_at:Yc.optional().describe(`metadata.updated_at value from atoms_get_item; rejects stale writes. ${N}`),base_token:Vv(),intent:Jv(),asil_confirm_lower:w.string().max(8).optional().describe(_c),widget_proof:Gv(),echo:w.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:w.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:w.array(w.object({item_id:w.string().min(1).max(20),title:w.string().min(1).max(500).optional(),body:w.string().max(5e4).optional(),summary:w.string().max(2e3).optional(),domains:w.array(w.string().max(64)).max(20).optional(),level:w.string().max(32).optional(),status:w.enum(["passed","failed","blocked","not-run"]).optional(),req_type:w.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional(),fields:w.record(w.string().max(60),w.string().max(1e4)).optional(),...Yv,expected_updated_at:Yc.optional(),base_token:Vv(),intent:Jv(),asil_confirm_lower:w.string().max(8).optional().describe(_c)})).optional().describe("Array form: update many items in one call"),idempotency_key:Bv(),continue_on_error:w.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(Oy(),Iy));return t(e)})),Uv("atoms_delete_item",{title:"Delete ATOMS Item",description:Wm.atoms_delete_item,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:w.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}},ab("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Ty(),Ry));return t(e)})),Uv("atoms_restore_item",{title:"Restore ATOMS Item",description:Ro,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().max(256).describe("ID of the item in Trash"),confirm:w.boolean().optional().describe(Mo)},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(Py(),Cy));return t(e)})),Uv("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?: persisted in audit history\n\nArray form (batch link ops, same tool, much faster for restructures):\n - project_id, operations: [{action, from_id, to_id, type, expected_from_updated_at?, expected_to_updated_at?}]\n - Validated as a whole (DAG cycle check) before any write, then applied one at a time (removes before adds), NOT in a single transaction: a mid-batch failure leaves earlier operations committed and names which ones\n - reason?, idempotency_key? supported\n\nidempotency_key: ${C}`,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),from_id:w.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:w.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:w.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]).optional().describe("Relationship type"),action:w.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:Yc.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:Yc.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:w.boolean().optional().describe("false → lean response"),reason:w.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:w.array(w.object({action:w.enum(["add","remove"]),from_id:w.string().min(1).max(20),to_id:w.string().min(1).max(20),type:w.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]),expected_from_updated_at:Yc.optional(),expected_to_updated_at:Yc.optional()})).optional().describe("Array form: batch relationship ops, DAG-validated as a whole then applied in sequence (not one transaction); a mid-batch failure reports which ops committed."),idempotency_key:Bv()},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},ab("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(By(),Uy));return t(e)})),tb({appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:Wm.atoms_bulk_import,inputSchema:{project_id:w.string().uuid().describe("UUID of the target project"),items:w.array(w.object({type:w.enum(Fp).describe(Np),title:w.string().min(1).max(500).describe("Item title"),body:w.string().max(5e4).optional().describe("Rich text body"),summary:w.string().max(2e3).optional().describe("Brief summary"),domains:w.array(w.string().max(64)).max(20).optional().describe("Domain tags"),level:w.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:w.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(500).describe("Items to create (1-100; 1-500 on a project that saves one field at a time)"),confirmation_token:w.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),idempotency_key:Bv()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:ab("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(Zy(),Gy));return t(e)})}),Zv={point:w.record(w.string(),w.union([w.string(),w.number()])).optional().describe('Matrix point this run executed, e.g. {"speed": 40}'),release_id:w.string().uuid().optional().describe("Formal Release to bind this run to (a baseline with a release_version)"),build:w.string().optional().describe("Free-text build label"),environment:w.string().optional().describe("Structured environment field, distinct from build"),tooling:w.string().optional().describe("Structured tooling field, distinct from build"),steps_rev:w.string().optional().describe(id),evidence_url:w.string().optional().describe(od),step_results:w.array(w.object({step_id:w.string().describe("Step id from atoms_get_item steps[].id"),status:w.enum(["passed","failed","blocked","skipped"]).describe("Per-step status"),actual:w.string().optional().describe("Actual-result note"),evidence_url:w.string().optional().describe(sd)}).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.")},Uv("atoms_record_test_result",{title:"Record Test Result",description:Wm.atoms_record_test_result,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:w.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:w.string().max(500).optional().describe("Reason or comment for this result"),asset:w.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new."),date:w.string().optional().describe(td),...Zv,idempotency_key:Kv},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_record_test_result",async(e,t)=>{const{recordTestResultHandler:n}=await Promise.resolve().then(()=>(ng(),Xy));return n({...e,request_id:nb(t)})})),Uv("atoms_record_test_results",{title:"Record Test Results (bulk)",description:Wm.atoms_record_test_results,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:w.array(w.object({asset:w.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:w.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:w.string().max(500).optional().describe("Run note"),date:w.string().optional().describe("Ignored: runs are stamped with server time. A supplied date is reported in the response warning, never stored."),...Zv})).min(1).max(100).describe("1 to 100 result entries on this test case"),idempotency_key:Kv},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_record_test_results",async(e,t)=>{const{recordTestResultsBulkHandler:n}=await Promise.resolve().then(()=>(ig(),rg));return n({...e,request_id:nb(t)})})),tb({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:Wm.atoms_trace,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).describe("Starting item ID"),direction:w.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:w.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:w.array(w.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")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:ab("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(lg(),sg));return t(e)})}),Uv("atoms_list_assets",{title:"List Project Assets",description:Wm.atoms_list_assets,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),include_archived:w.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>(pg(),cg));return t(e)})),Uv("atoms_list_variables",{title:"List Project Variables",description:Wm.atoms_list_variables,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),baseline_id:w.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:w.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads"),limit:w.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:w.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(Ag(),mg));return t(e)})),Uv("atoms_get_variable",{title:"Get Project Variable",description:Wm.atoms_get_variable,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),variable_name:w.string().min(1).max(64).describe("Variable name"),baseline_id:w.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:w.string().datetime().optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(Ag(),mg));return t(e)})),Uv("atoms_update_variable",{title:"Update Project Variable",description:Wm.atoms_update_variable,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),variable_name:w.string().min(1).max(64).describe("Variable name"),value:w.string().max(500).optional().describe("New value"),unit:w.string().max(32).optional().describe("Unit abbreviation"),description:w.string().max(2e3).optional().describe("Description"),echo:w.boolean().optional(),base_token:Qv},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(Ag(),mg));return t(e)})),Uv("atoms_create_variable",{title:"Create Project Variable",description:Wm.atoms_create_variable,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(64).optional().describe("Variable name (single form)"),value:w.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:w.string().max(32).optional().describe("Unit abbreviation"),description:w.string().max(2e3).optional().describe("Description"),echo:w.boolean().optional().describe("false → lean response (default true)"),variables:w.array(w.object({name:w.string().min(1).max(64).describe("Variable name"),value:w.string().min(1).max(500).describe("Initial value"),unit:w.string().max(32).optional().describe("Unit abbreviation"),description:w.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:w.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(Ag(),mg));return t(e)})),Uv("atoms_delete_variable",{title:"Delete Project Variable",description:Wm.atoms_delete_variable,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(64).describe("Variable name to delete"),force:w.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:w.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),base_token:Qv},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},ab("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(Ag(),mg));return t(e)})),Uv("atoms_list_domains",{title:"List Project Domains",description:Wm.atoms_list_domains,inputSchema:{project_id:w.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(Mg(),Ig));return t(e)})),Uv("atoms_create_domain",{title:"Create Project Domain",description:Wm.atoms_create_domain,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(Mg(),Ig));return t(e)})),Uv("atoms_list_levels",{title:"List Project Levels",description:Wm.atoms_list_levels,inputSchema:{project_id:w.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(hh(),Kf));return t(e)})),Uv("atoms_create_level",{title:"Create Project Level",description:Wm.atoms_create_level,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(hh(),Kf));return t(e)})),Uv("atoms_delete_level",{title:"Delete Project Level",description:Wm.atoms_delete_level,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(64).describe("Level name to delete"),confirmation_token:w.string().optional().describe("Token from the first (preview) call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},ab("atoms_delete_level",async e=>{const{deleteLevelHandler:t}=await Promise.resolve().then(()=>(hh(),Kf));return t(e)})),Uv("atoms_reorder_levels",{title:"Reorder Project Levels",description:Wm.atoms_reorder_levels,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),names:w.array(w.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}},ab("atoms_reorder_levels",async e=>{const{reorderLevelsHandler:t}=await Promise.resolve().then(()=>(hh(),Kf));return t(e)})),Uv("atoms_list_fields",{title:"List Project Fields",description:'List the project\'s custom field definitions (project-scoped key-value slots on items, e.g. "Verification Method"), with counts of items carrying a value.\n\nField values are set per item via atoms_create_item / atoms_update_item fields.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { fields: [{ name, type, options, item_count }], total }',inputSchema:{project_id:w.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(Qh(),Rh));return t(e)})),Uv("atoms_create_field",{title:"Create Project Field",description:Wm.atoms_create_field,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:w.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:w.array(w.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:w.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization"),appliesTo:w.array(w.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}},ab("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(Qh(),Rh));return t(e)})),Uv("atoms_delete_field",{title:"Delete Project Field",description:"Delete a project field definition. Existing item values are left in item JSON but no longer render as Matrix columns until a matching field is created again.\n\nOnly an org admin of the project's organization can delete a field definition.\n\nArgs:\n - project_id (string, UUID): Project containing the field\n - name (string): Field name to delete",inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(60).describe("Field name")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},ab("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(Qh(),Rh));return t(e)})),Uv("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:w.string().uuid().describe("UUID of the project"),names:w.array(w.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}},ab("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(Qh(),Rh));return t(e)})),Uv("atoms_update_domain",{title:"Update Project Domain",description:Wm.atoms_update_domain,inputSchema:w.object({project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(64).describe("Current domain name"),new_name:w.string().min(1).max(64).describe("New domain name"),dry_run:w.boolean().optional().describe("Preview impact without applying (default false)")},{errorMap:fp("atoms_update_domain")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(Mg(),Ig));return t(e)})),Uv("atoms_delete_domain",{title:"Delete Project Domain",description:Wm.atoms_delete_domain,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(64).describe("Domain name to delete"),force:w.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:w.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}},ab("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(Mg(),Ig));return t(e)})),tb({appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:Wm.atoms_project_summary,inputSchema:{project_id:w.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:ab("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(Dg(),Tg));return t(e)})}),tb({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:Wm.atoms_browse,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),type:w.enum(Jp).optional().describe("Filter by item type"),domain:w.string().max(64).optional().describe("Filter by domain tag"),level:w.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:w.string().max(1e3).optional().describe("Full-text search query"),limit:w.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:w.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:ab("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(Pg(),Hg));return t(e)})}),Uv("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:Wm.atoms_impact_analysis,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),item_id:w.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:w.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:w.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:w.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(tw(),Ug));return t(e)})),Uv("atoms_list_baselines",{title:"List ATOMS Baselines",description:Wm.atoms_list_baselines,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),limit:w.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:w.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(Kw(),Dw));return t(e)})),Uv("atoms_create_baseline",{title:"Create ATOMS Baseline",description:Wm.atoms_create_baseline,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),name:w.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:w.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(Kw(),Dw));return t(e)})),Uv("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:Wm.atoms_lock_baseline,inputSchema:{baseline_id:w.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(Kw(),Dw));return t(e)})),Uv("atoms_diff_baselines",{title:"Diff ATOMS Baselines",description:Wm.atoms_diff_baselines,inputSchema:{baseline_a_id:w.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:w.string().uuid().describe("UUID of the second (newer) baseline"),detail:w.boolean().default(!1).describe("Add a per-field from/to diff object to each modified item (default false)"),limit:w.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:w.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(Kw(),Dw));return t(e)})),Uv("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:Wm.atoms_restore_baseline,inputSchema:{baseline_id:w.string().uuid().describe("UUID of the baseline to restore from"),confirm:w.boolean().default(!1).describe("Set true to execute; false (default) returns a preview"),source_seq:w.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:w.string().uuid().optional().describe(H),after_id:w.string().min(1).max(64).optional().describe(H)},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},ab("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(Kw(),Dw));return t(e)})),Uv("atoms_create_analysis",{title:"Create Analysis (HARA, Risk analysis, FMEA)",description:Wm.atoms_create_analysis,inputSchema:w.object({project_id:w.string().uuid().describe("UUID of the target project"),subtype:w.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:w.string().min(1).max(500).optional().describe("Analysis title"),source_function_ids:w.array(w.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:w.array(w.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:w.array(w.string().min(1).max(20)).max(50).optional().describe("dfmea only: requirement IDs to seed rows from (0-50)"),revision:w.string().min(1).max(32).optional().describe("Revision label (default 1.0)"),variant:w.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:w.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:w.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:w.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:w.string().max(1e4).optional().describe("Security risk analysis only: the threat modeling methodology used, e.g. STRIDE."),threat_model_rationale:w.string().max(1e4).optional().describe("Security risk analysis only: why that methodology was chosen."),environment_assumptions:w.string().max(1e4).optional().describe("Security risk analysis only: assumptions about the operating environment, one per line."),attack_surfaces:w.string().max(1e4).optional().describe("Security risk analysis only: interfaces and entry points considered, one per line."),related_documents:w.string().max(1e4).optional().describe("Security risk analysis only: where the SBOM, the security testing report and the architecture views live."),idempotency_key:Kv,hazard_id:w.string().max(20).optional().describe(Pp),goal_id:w.string().max(20).optional().describe(Up)},{errorMap:fp("atoms_create_analysis")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("atoms_fill_row",{title:"Fill Analysis Row Fields",description:Wm.atoms_fill_row,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),row_id:w.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:w.record(w.string().max(64),w.union([w.string().max(5e4),w.number()])).describe("Field name to value map (see description for allowed keys per subtype)"),base_token:Qv},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("atoms_get_analysis",{title:"Get Analysis",description:Wm.atoms_get_analysis,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),analysis_id:w.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}},ab("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:Wm.atoms_link_mitigation,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),row_id:w.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:w.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:w.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows (every FMEA); must be omitted for hara rows."),override:w.boolean().optional().describe("hara only: apply the row's level (ASIL or Risk) over a conflicting existing value (history-logged)"),control_type:w.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:w.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}},ab("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:Wm.atoms_get_gaps,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),analysis_id:w.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}},ab("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("atoms_propose_rows",{title:"Write Proposed Analysis Rows",description:Wm.atoms_propose_rows,inputSchema:w.object({project_id:w.string().uuid().describe("UUID of the project"),analysis_id:w.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),rows:w.array(w.record(w.string().max(64),w.union([w.string().max(5e4),w.number()]))).min(1).max(oi).describe(`The drafted rows (1-${oi}), each a scheme field name to value map`),source_function_id:w.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:w.string().min(1).max(20).optional().describe("FMEA only: the requirement these rows analyse"),idempotency_key:Kv},{errorMap:fp("atoms_propose_rows")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_propose_rows",async e=>{const{proposeRowsHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("atoms_suggest_field",{title:"Write a Suggested Value for One Analysis Field",description:Wm.atoms_suggest_field,inputSchema:{project_id:w.string().uuid().describe("UUID of the project"),row_id:w.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),field:w.string().min(1).max(64).describe("The field to fill (a scheme key of this row)"),value:w.union([w.string().max(5e4),w.number()]).describe("The suggested value"),rationale:w.string().max(5e4).optional().describe("The evidence behind a suggested rating; written to the scheme's evidence field"),base_token:Qv},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_suggest_field",async e=>{const{suggestFieldHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("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:w.string().uuid().describe("UUID of the project"),row_id:w.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),approver_id:w.string().uuid().optional().describe("The approving project member; defaults to the calling user"),note:w.string().max(2e3).optional().describe("Optional note captured with the approval"),base_token:Qv},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_approve_row",async e=>{const{approveRowHandler:t}=await Promise.resolve().then(()=>(Rv(),nv));return t(e)})),Uv("atoms_list_scenario_catalogs",{title:"List Operational Scenario Catalogs",description:Wm.atoms_list_scenario_catalogs,inputSchema:{project_id:w.string().uuid("Must be a valid project UUID").describe("UUID of the project"),limit:w.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:w.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},ab("atoms_list_scenario_catalogs",async e=>{const{listScenarioCatalogsHandler:t}=await Promise.resolve().then(()=>(Xv(),Mv));return t(e)})),Uv("atoms_mutate_scenario_catalog",{title:"Mutate an Operational Scenario Catalog",description:Wm.atoms_mutate_scenario_catalog,inputSchema:w.object({project_id:w.string().uuid().describe("UUID of the project"),op:w.enum(["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]).describe("The mutation to apply"),catalog_id:w.string().min(1).max(64).optional().describe("The catalog id (optional for create_catalog: generated when omitted)"),name:w.string().min(1).max(100).optional().describe("The catalog name (create_catalog, rename_catalog)"),entry_id:w.string().min(1).max(64).optional().describe("The entry id (caller-generated for add_entry)"),text:w.string().min(1).max(100).optional().describe("The entry's operational scenario text"),function_ids:w.array(w.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:w.string().min(1).max(200).optional().describe("The accepter's name (accept_catalog)"),on:w.string().min(1).max(32).optional().describe("The acceptance date (accept_catalog)")},{errorMap:fp("atoms_mutate_scenario_catalog")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},ab("atoms_mutate_scenario_catalog",async e=>{const{mutateScenarioCatalogHandler:t}=await Promise.resolve().then(()=>(Xv(),Mv));return t(e)})),Be()}});et(),Ge(),ic(),ze();var cb=S(import.meta.url)("../package.json"),db=process.argv.slice(2)[0];(async function(){switch(db){case"login":{const{login:e}=await Promise.resolve().then(()=>(cc(),sc));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(()=>(Lt(),Ft));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(()=>(ft(),tt));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${cb.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(()=>(fc(),dc)),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 Bl(),t=Kl(),n=await Te(e,t);!function(e){Ce=e,De=Date.now(),Ne=!0}(n),Le(n)}catch(e){We(),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 We(),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=Ke(),t=Qe(),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(()=>(lb(),eb)),n=new A;await t.connect(n);const{startUpdateCheck:r}=await Promise.resolve().then(()=>(fd(),zc));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
|
+
import e,{readFile as t,mkdir as n,writeFile as r,unlink as a,stat as i,open as s}from"fs/promises";import{homedir as o}from"os";import l,{join as c}from"path";import{createClient as d}from"@supabase/supabase-js";import{createServer as u}from"http";import p,{randomUUID as m,randomBytes as _,createHash as f}from"crypto";import{fileURLToPath as h,URL as y}from"url";import{promises as g}from"fs";import{registerAppTool as w,registerAppResource as v,RESOURCE_MIME_TYPE as b}from"@modelcontextprotocol/ext-apps/server";import{McpServer as j}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as k}from"zod";import{createRequire as S}from"module";import{StdioServerTransport as A}from"@modelcontextprotocol/sdk/server/stdio.js";var $,I,x,q,O,E,R,M,T,C,D,H,N,F,P,z,U,L=Object.defineProperty,W=Object.getOwnPropertyNames,V=(e,t,n)=>function(){if(n)throw n[0];try{return e&&(t=(0,e[W(e)[0]])(e=0)),t}catch(e){throw n=[e],e}},B=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})};function J(e){return M.get(e)}var G,Q,K,Y,Z,X,ee=V({"src/core/tool-catalog.ts"(){$=new Set(["atoms_status","atoms_list_projects"]),I=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"]),x=new Set(["atoms_delete_item","atoms_delete_variable","atoms_delete_domain","atoms_delete_level","atoms_delete_field","atoms_restore_baseline"]),q={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"]}},O=new Set(["atoms_bulk_import"]),E={items:["atoms_list_items","atoms_get_item","atoms_search","atoms_semantic_search","atoms_browse","atoms_get_history","atoms_list_changes","atoms_create_item","atoms_update_item","atoms_delete_item","atoms_restore_item","atoms_bulk_import"],traceability:["atoms_trace","atoms_link_items","atoms_export_mermaid","atoms_impact_analysis"],coverage:["atoms_get_coverage","atoms_verification_status","atoms_record_test_result","atoms_record_test_results","atoms_project_summary","atoms_list_assets"],variables:["atoms_list_variables","atoms_get_variable","atoms_create_variable","atoms_update_variable","atoms_delete_variable"],domains:["atoms_list_domains","atoms_create_domain","atoms_update_domain","atoms_delete_domain","atoms_list_levels","atoms_create_level","atoms_delete_level","atoms_reorder_levels","atoms_list_fields","atoms_create_field","atoms_delete_field","atoms_reorder_fields"],baselines:["atoms_list_baselines","atoms_create_baseline","atoms_lock_baseline","atoms_diff_baselines","atoms_restore_baseline"],analysis:["atoms_create_analysis","atoms_fill_row","atoms_get_analysis","atoms_link_mitigation","atoms_get_gaps","atoms_propose_rows","atoms_suggest_field","atoms_approve_row","atoms_list_scenario_catalogs","atoms_mutate_scenario_catalog"]},R=Object.keys(E),M=new Map;for(const[e,t]of Object.entries(E))for(const n of t)M.set(n,e);T="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.",C="Retry key: sending the same call again with the same key within 24 hours changes nothing twice.",D="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.",H="Set both from the previous answer when it says complete is false, to continue the same restore.",N="Set by the ATOMS editor card. Do not set this yourself.",F="Ignored on projects that save one field at a time; send base_token instead.",P="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.",z="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.",U="If a call answers code rate_limited, wait retry_after_seconds seconds before calling again. Do not retry sooner."}}),te=V({"src/core/types.ts"(){G={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:[]},Q={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 ne(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&&I.has(t))return{allowed:!1,reason:"read_only"};if(e.block_destructive&&x.has(t))return{allowed:!1,reason:"block_destructive"};if(e.block_bulk_import&&O.has(t))return{allowed:!1,reason:"block_bulk_import"};const n=J(t);return void 0===n||e.allowed_toolsets.includes(n)?{allowed:!0}:{allowed:!1,reason:"toolset_disabled"}}function re(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 ae(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?Z:re(r),"Contact your org admin to adjust the MCP access policy.","Do not retry this call."],code:n,retryable:!1}}function ie(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:Y,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:X,next_steps:a}:t.some(t=>!function(e,t){return null===e.project_scope||e.project_scope.includes(t)}(e,t))?{status:"error",message:Z,next_steps:a}:null}function se(){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 oe,le,ce,de,ue=V({"src/core/policy.ts"(){ee(),K="Your organization's MCP policy could not be read just now. Nothing was run. Try again in a moment.",Y="Your admin set Project scope to No projects for your role. Ask an org admin to change it.",Z="Tool call rejected: project_id is outside your org's MCP project scope.",X="Tool call rejected: this baseline is not in a project your org's MCP project scope allows, or could not be found."}});async function pe(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 me(e){return e.length>0&&e.every(e=>"viewer"===e.role)}function _e(e){return new Set(e.filter(e=>"viewer"===e.role&&"string"==typeof e.org_id).map(e=>e.org_id))}async function fe(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 ye(e,i);s?r.push(s):a++}return{projectIds:r,unresolved:a}}async function he(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 ye(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 ge(){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 we,ve,be,je=V({"src/core/viewer-gate.ts"(){oe="Viewers cannot use the ATOMS MCP. Ask an org admin for editor access.",le=["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"],ce=["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"],de=new Set(["atoms_status"])}});function ke(e,t=new Map){return{orgs:e,projectOrgs:t}}function Se(e){const t="string"==typeof e?.code?e.code:"";return""===t||/^PGRST00[0-3]$/.test(t)}function Ae(e,t){return e.orgs.find(e=>e.orgId===t)?.effective??Q}function $e(e){if(0===e.orgs.length)return G;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 Ie(e,t){return!!$.has(t)||(0===e.orgs.length?ne(G,t).allowed:e.orgs.some(e=>ne(e.effective,t).allowed))}function xe(e,t,n){const r=ne(e,t);if(!r.allowed)return{status:"error",message:`Tool ${t} is blocked by org policy.`,next_steps:[re(r.reason),"Contact your org admin to adjust the MCP access policy."]};const a=function(e,t,n){const r=q[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:[re(a.reason),"Contact your org admin to adjust the MCP access policy."]}}async function qe(e,t,n){const r=t.projectOrgs.get(n);if("string"==typeof r)return r;const a=await he(e,n);return null!==a&&t.projectOrgs.set(n,a),a}function Oe(e,t){if(e.orgs.length<=1)return e.orgs[0]?.effective??G;const n=t?e.projectOrgs.get(t):void 0;return"string"==typeof n?Ae(e,n):$e(e)}var Ee,Re,Me=V({"src/core/org-policy.ts"(){te(),ue(),ee(),je(),we=["baseline_id","baseline_a_id","baseline_b_id"],ve=new Set(["atoms_create_item","atoms_update_item","atoms_bulk_import"]),be=class extends Error{name="PolicyTransientError"}}});function Te(){const e=process.env.ATOMS_MCP_PROJECT_ID?.trim();return e?Ee.test(e)?e:(Re||(process.stderr.write(`[atoms-mcp] WARNING: ATOMS_MCP_PROJECT_ID="${e.slice(0,50)}" is not a valid UUID — scope ignored.\n`),Re=!0),null):null}function Ce(){return process.env.ATOMS_MCP_ORG_ID?.trim()||null}var De=V({"src/middleware/project-scope.ts"(){Ee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Re=!1}});async function He(e,t,n){return async function(e,t,n=new Map){const r=await Promise.all(e.map(t));return ke(e.map((e,t)=>({orgId:e,role:r[t].role,effective:r[t].effective,failedClosed:r[t].effective===Q})),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=Ce();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:G};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&&Se(a.error)?await e.rpc("mcp_resolve_policy",r):a}(e,t,n);if(a&&Se(a))throw process.stderr.write(`[atoms-mcp] mcp_resolve_policy unreachable: ${a.message}. Changes are paused until it loads.\n`),new be(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:Q}):function(e){if(!e||"object"!=typeof e)return{role:null,is_member:!1,effective:G};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,G.read_only),lockdown:s(a.lockdown,G.lockdown),block_destructive:s(a.block_destructive,G.block_destructive),block_bulk_import:s(a.block_bulk_import,G.block_bulk_import),cross_project_browse:s(a.cross_project_browse,G.cross_project_browse),allowed_toolsets:i(a.allowed_toolsets,G.allowed_toolsets),forbidden_tools:i(a.forbidden_tools,G.forbidden_tools),project_scope:l,require_confirmation_for:i(a.require_confirmation_for,G.require_confirmation_for)}}}(r)}(e,t,n),n)}var Ne,Fe,Pe,ze,Ue,Le,We,Ve,Be=V({"src/db/policy.ts"(){Me(),De(),te()}});function Je(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 Ge(){Ue=!1}function Qe(){return Ne}function Ke(){const e=Ve,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 We){const n=Ie(Ne,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 Ye(e,t){Ue&&Date.now()-Fe<=Pe||(ze||(ze=(async()=>{try{const n=await He(e,t,Ne.projectOrgs);Ne=n,Ue||Je(n),Ue=!0,Le=!1}catch(e){Ue=!1,Le=e instanceof be}Fe=Date.now(),Ke()})().finally(()=>{ze=null})),await ze)}var Ze=V({"src/middleware/session-policy.ts"(){Me(),Be(),Ne=ke([]),Fe=Date.now(),Pe=3e4,ze=null,Ue=!0,Le=!1,We=new Map,Ve=null}});function Xe(){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)R.includes(e)?n.add(e):r.push(e);return{allowed:n,unknown:r}}function et(){const e=process.env.ATOMS_MCP_READ_ONLY;return"1"===e||"true"===e?.toLowerCase()}function tt(e){if(et()&&I.has(e))return!1;if($.has(e))return!0;const t=Xe();if(null===t)return!0;const n=J(e);return!!n&&t.allowed.has(n)}var nt,rt,at=V({"src/middleware/tool-registry.ts"(){ee(),Me(),Ze()}}),it={};async function st(){try{const e=await t(rt,"utf-8"),n=JSON.parse(e);return n.access_token&&n.refresh_token?n:null}catch{return null}}async function ot(e){await n(nt,{recursive:!0,mode:448}),await r(rt,JSON.stringify(e,null,2),{mode:384})}async function lt(){const e=await st();return!!e&&e.expires_at>Date.now()+6e4}function ct(e){return e.expires_at>Date.now()+6e4}async function dt(){try{await a(rt)}catch{}}function ut(){return rt}B(it,{clearCredentials:()=>dt,getCredentialsPath:()=>ut,hasValidCredentials:()=>lt,isTokenValid:()=>ct,readCredentials:()=>st,writeCredentials:()=>ot});var pt,mt,_t,ft,ht,yt,gt,wt=V({"src/auth/token-store.ts"(){nt=c(o(),".atoms"),rt=c(nt,"credentials.json")}}),vt={};async function bt(){try{await n(pt,{recursive:!0,mode:448});const e=await s(mt,"wx");try{await e.writeFile(`${process.pid} ${Date.now()}`)}finally{await e.close()}return!0}catch(e){if("EEXIST"===e.code)return!1;throw e}}async function jt(){try{await a(mt)}catch{}}async function kt(){try{const e=await i(mt);return Date.now()-e.mtimeMs>_t}catch{return!1}}async function St(e,t,n=gt){const r=n.now()+ft;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(ht)}}}B(vt,{runExclusiveAuth:()=>St});var At,$t,It,xt=V({"src/auth/lock.ts"(){pt=c(o(),".atoms"),mt=c(pt,".auth.lock"),_t=7e4,ft=12e4,ht=300,yt=e=>new Promise(t=>setTimeout(t,e)),gt={now:Date.now,wait:yt,tryAcquire:bt,release:jt,isStale:kt}}}),qt={};function Ot(e){return e.trim().replace(/\/+$/,"")}B(qt,{ATOMS_APP_URL:()=>It,ATOMS_SUPABASE_ANON_KEY:()=>$t,ATOMS_SUPABASE_URL:()=>At,resolveUrl:()=>Ot});var Et,Rt,Mt,Tt,Ct,Dt=V({"src/config.ts"(){At=Ot(process.env.ATOMS_SUPABASE_URL??"https://gmebjyhomsbvhrxffzre.supabase.co"),$t=process.env.ATOMS_SUPABASE_ANON_KEY??"sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",It=process.env.ATOMS_APP_URL??"https://atoms.tech"}});function Ht(e){return e instanceof Tt||!!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||!!Ct.statuses.includes(n)||Ct.codedStatuses.includes(n)&&"string"==typeof r&&Ct.codes.includes(r)}(e)}function Nt(){return{status:"error",code:Et,retryable:!0,message:Mt,next_steps:[`Wait ${Rt} seconds, then retry the same call`,"Do not sign out or log in again: the saved session is still valid"]}}var Ft,Pt,zt=V({"src/core/auth-outage.ts"(){Et="auth_unavailable",Rt=5,Mt="ATOMS could not check your sign-in just now. Your session is kept. Try again in a moment.",Tt=class extends Error{code=Et;constructor(e){super(`${Et}: ${e}`),this.name="AuthServiceUnavailableError"}},Ct={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"]}}}),Ut={};async function Lt(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=Vt(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await st();if(t&&t.expires_at>Date.now()+6e4){const e=Vt(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 Wt(){const e=await Lt();if(e)return e;const t=await st();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp@latest login' to connect your ATOMS account.");return St(async()=>{const e=await Lt();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=d(At,$t,{global:{fetch:Pt}});let n=await t.auth.refreshSession({refresh_token:e.refresh_token});if(n.error||!n.data.session){const r=await st();if(r&&r.expires_at>Date.now()+6e4){const e=Vt(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(Ht(n.error))throw new Tt(`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 r=n.data.session;return await ot({access_token:r.access_token,refresh_token:r.refresh_token,expires_at:Date.now()+1e3*(r.expires_in??3600),user_email:r.user?.email}),{access_token:r.access_token,refresh_token:r.refresh_token,user_id:r.user?.id??"",email:r.user?.email??""}}(t))}function Vt(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}B(Ut,{AUTH_CALL_TIMEOUT_MS:()=>Ft,getValidToken:()=>Wt,readValidToken:()=>Lt});var Bt,Jt,Gt=V({"src/auth/refresh.ts"(){wt(),xt(),Dt(),zt(),Ft=1e4,Pt=async(e,t)=>{const n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Auth did not answer within ${Ft} ms`)),Ft),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 Qt(e){const t=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,Jt).replace(/_+$/g,"")}(e??"");return t?t.includes("cursor")?"cursor":t.includes("copilot")?"copilot":t.includes("claude")?Bt:t:Bt}function Kt(e){const t=Qt(e);return"cursor"===t?"mcp_cursor":"copilot"===t?"mcp_copilot":"mcp_claude"}var Yt,Zt,Xt,en,tn,nn,rn=V({"src/core/client-identity.ts"(){Bt="claude_desktop",Jt=64}});function an(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 sn(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 on(e){return"string"==typeof e&&e.includes(Xt)}function ln(e){return"string"==typeof e&&e.includes(en)}function cn(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 dn(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 un(e){const t=nn.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 pn=V({"src/core/errors.ts"(){Yt=[/^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],Zt=class extends Error{},Xt="rollout_switched:multiuser_saving: This project still saves whole items. Reload, then save again.",en="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.",tn=10,nn=/^(?:[A-Za-z_][\w ]{0,60}:\s+){0,2}hierarchy_cycle:\s+(\S+) cannot go under (\S+) because \S+ is already above it \(([^)]*)\)/}});function mn(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function _n(e){return e.replace(/[\\%_*]/g,e=>`\\${e}`)}function fn(e){return mn(`*${_n(e)}*`)}function hn(e){return _n(e)}function yn(e){return`*"${_n(e)}"*`}async function gn(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 wn,vn,bn,jn,kn,Sn,An,$n,In,xn,qn,On,En=V({"src/core/postgrest.ts"(){}});async function Rn(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(Tn(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(`${Mn(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(`${Mn(s)} read, page ${i}: the page did not move past the last row read`);r.push(...c),a=d}}function Mn(e){const t=e.url;return t instanceof URL?decodeURIComponent(t.pathname).replace(/^.*\/rest\/v1\//,""):"query"}function Tn(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 mn(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 Cn(e,t,n,r){return Rn(()=>e.rpc(t,{p_project_id:n,p_snapshot_at:r}),kn[t])}function Dn(e,t,n){return"baselineId"in n?Rn(()=>e.rpc("baseline_variables_state",{p_baseline_id:n.baselineId}),jn):Cn(e,"variables_at",t,n.at)}async function Hn(e,t){const n=[];for(let r=0;r<e.length;r+=$n){const{data:a,error:i}=await t(e.slice(r,r+$n));if(i)throw new Error(i.message);n.push(...a??[])}return n}function Nn(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(qn(t)?[e.created_at,e.id,t]:[e.created_at,e.id]))}var Fn,Pn,zn,Un,Ln,Wn,Vn,Bn,Jn,Gn,Qn,Kn,Yn,Zn,Xn,er,tr,nr,rr,ar,ir,sr,or,lr,cr,dr,ur,pr,mr,_r,fr,hr,yr,gr,wr,vr,br,jr,kr,Sr,Ar,$r,Ir,xr=V({"src/core/paginate.ts"(){En(),vn=["from_id","to_id","type"],bn=["name","id"],kn={project_state_at:wn=["id"],variables_at:jn=["name","id"]},Sn=e=>({at:e}),An=e=>({baselineId:e}),$n=200,In=100,xn=["created_at","id"],qn=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0,On=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 qr(e){return/rollout_switched:multiuser_saving/i.test(e)}function Or(){return{status:"error",message:Pn,next_steps:[zn],code:"rollout_switched",retryable:!1}}function Er(e){return/project_in_trash/i.test(e)||e===Ln}function Rr(){return{status:"error",message:Un,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 Mr(e){return e===Vn||/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 Tr(){return{status:"error",message:Wn,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 Cr(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 Dr(e){const t=/approved_item_delete_blocked: ([^\s;:]{1,60}) /.exec(e);return t?{status:"error",message:`${t[1]}: ${Bn}. 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 Hr(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&&an(t.message)?new Error(t.message):t&&"42501"!==t.code||!Jn.test(e)?new Error(`Project '${e}' not found`):new Error(Vn)}function Nr(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 Fr(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 Pr(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":Pr(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)}:${Pr(t[e])}`).join(",")}}`}return"null"}async function zr(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 Ur(e,t,n="item"){return e&&"object"==typeof e?"variable"===n?"variables"!==t[0]?null:t.length<=2?e:Lr(e[t[2]],t.slice(3)):0===t.length?e.data??null:er.has(t[0])?1===t.length?e[t[0]]??null:null:Lr(e.data,t):null}function Lr(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 Wr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Vr(e,t){return e.length<=t.length&&e.every((e,n)=>e===t[n])}function Br(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=>Vr(e,t)));if(0===t.length||tr.has(t[0]))return!1;switch(r){case"item":case"all":return!0;case"core":return Kn.some(e=>Wr(e,t));case"analysis":return Wr(t,["title"])||Wr(t,["body"])||("analysis_props"===t[0]||"relationships"===t[0])&&t.length>=2;case"paths":return(a??[]).some(e=>Vr(e,t))}return!1}async function Jr(e,t,n="item"){let r;if("string"!=typeof t)r=t.paths.map(t=>Ur(e,t,n));else if("core"===t||"analysis"===t){const a="core"===t?Kn:Yn;r=Object.fromEntries(a.map(t=>[JSON.stringify(t),Ur(e,t,n)]))}else r=e??null;return(await zr(Pr(r))).slice(0,16)}function Gr(e,t,n){return`${e}.${t}~${function(e){return"string"==typeof e?e:`paths:${encodeURIComponent(JSON.stringify(e.paths))}`}(n)}`}async function Qr(e,t,n="item"){return Gr(e.id,await Jr(e.fields_snapshot,t,n),t)}function Kr(e){if("string"!=typeof e||0===e.length||e.length>Gn)return null;const t=Xn.exec(e);if(!t)return null;const n=t[1].toLowerCase(),r=t[2].toLowerCase(),a=t[3];if(Zn.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 Yr(e){return"variable"===e?{table:"variable_revisions",idCol:"variable_id"}:{table:"item_revisions",idCol:"item_id"}}function Zr(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 Xr(e,t){return new Error(String(e?.message??`${t} failed`))}async function ea(e,t,n,r="item"){const a=new Map,i=[...new Set(n)],{table:s,idCol:o}=Yr(r);for(let n=0;n<i.length;n+=In){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+In)).is("valid_to",null).is("deleted_at",null);if(l)throw Xr(l,`${s} read`);for(const e of r??[]){const t=Zr(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 ta(e,t,n,r="item"){const a=new Map,i=[...new Set(n)],{table:s,idCol:o}=Yr(r);for(let n=0;n<i.length;n+=In){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+In));if(l)throw Xr(l,`${s} read`);for(const e of r??[]){const t=Zr(e,o);a.set(t.id,t)}}return a}async function na(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 Xr(r,"changes_since");const a=n?.head_seq;return"number"==typeof a?a:Number(a??0)}async function ra(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 Xr(o,"fresh_typing_notes");for(const e of s??[]){const t=a.get(e.item_id)??[];t.push({path:e.path,field_label:aa(e.path,r),person:{name:e.user_name??"Someone",kind:"person"}}),a.set(e.item_id,t)}return a}function aa(e,t){if(!e||0===e.length)return"Item";const n=rr[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 ia(e){return JSON.stringify(e)}async function sa(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=Kr(n);t?(e.parsed.push(t),r.push(t.revisionId)):e.bad=!0}n.set(t.itemId,e)}const a=await ta(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 Jr(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)Br(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(ia(n),{base:Ur(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 ea(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",...oa(t,e.req),path:e.path,seq:null,current:r?Ur(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",...oa(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 oa(e,t){return"variable"===e?{item_id:null,name:t.name??t.itemId,variable_id:t.itemId}:{item_id:t.itemId}}function la(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 ca(e){return e?"agent"===e.kind?e.label??e.name??null:e.name??null:null}async function da(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??""}|${ia(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(ar.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:ca(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??""}|${ia(c??[])}`),u={item_id:l.item_id??null,...null===l.item_id&&l.name?{name:l.name}:{},path:c,field_label:aa(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<=ur&&(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&&c?(u.theirs_value=Ur(m.fields_snapshot,c),_={revId:m.id,rev:m,value:u.theirs_value}):"current"in l&&"deleted"!==l.status&&(u.theirs_value=l.current),"base"in l?u.base_value=l.base:d&&"base"in d&&(u.base_value=d.base);const f=l.current_author??p?.change?.author??null;f&&(u.changed_by={kind:f.kind,name:ca(f)});const h=l.current_at??p?.change?.at??null;(f||h)&&(u.changed_at=h);const y=l.current_seq??p?.change?.seq;if(null!=y&&(u.seq=y),("skipped_typing"===l.status||"skipped"===l.status&&"typing"===l.reason)&&(u.typing={name:l.typing?.name??null,renewed_at:l.typing?.renewed_at??null}),("locked"===l.status||"skipped"===l.status&&"locked"===l.reason)&&(u.locked_by=l.locked_by?{name:l.locked_by.name??null}:null),l.target&&(u.target=l.target),"boolean"==typeof l.restorable&&(u.restorable=l.restorable),l.replayed&&(u.replayed=!0),_&&c){const e=`${u.item_id??u.name??""}|${_.revId}`,t=i.get(e)??{revId:_.revId,rev:_.rev,entries:[]};t.entries.push({entry:u,value:_.value}),i.set(e,t)}s.push({entry:u,answer:l})}for(const e of i.values()){const t=new Set,n=[],r=[];for(const{entry:a,value:i}of e.entries){const s=ia(a.path);t.has(s)||(t.add(s),n.push(a.path),r.push(e.rev?Ur(e.rev.fields_snapshot,a.path):i))}const a=(await zr(Pr(r))).slice(0,16),i=Gr(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=pa(e,t),a.not_applied.push(_a(e));return a.replayed=e.answers.length>0&&e.answers.every(e=>!0===e.replayed),a}function ua(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 pa(e,t){const n=ua(e),r=e.field_label,a=e.changed_by?.name??"Someone",i=e.changed_at?` at ${e.changed_at}`:"",s=e.reason??"",o=e.locked_by&&e.locked_by.name?`is locked to ${e.locked_by.name}`:"is locked for everyone";switch(e.status){case"conflict":return"no_base"===s?t?.no_revision?`${n} ${r} not saved: ${n} has no saved revision yet; save it once in ATOMS, then try again.`:`${n} ${r} not saved: no base_token covers it. Its current value is in theirs_value; send your change again with this entry's base_token. If you are in an ATOMS editor card, close the card and open ${n} again.`:"bad_token"===s?t?.no_revision?`${n} ${r} not saved: ${n} has no saved revision yet; save it once in ATOMS, then try again.`:`${n} ${r} not saved: the base_token you sent is not a token for ${n}. Its current value is in theirs_value; send your change again with this entry's base_token.`:`${n} ${r} not saved: ${a} changed it${i} after you read it.`;case"skipped_typing":return`${n} ${r} skipped: ${e.typing?.name??"Someone"} is typing in it.`;case"locked":return`${n} ${r} skipped: ${n} ${o}, and this org has Agents respect item locks on.`;case"deleted":return"in_trash"===s?`${n} ${r} not saved: ${n} is in the Trash.`:"row_deleted"===s||"column_deleted"===s?`${n} ${r} not saved: that row was deleted.`:"field_deleted"===s?`${n} ${r} not saved: that field was removed from the project.`:`${n} ${r} not saved: ${n} no longer exists.`;case"forbidden":return s.startsWith("mcp_policy_")?`${n} ${r} not saved: your org's MCP Access Policy does not allow this change.`:"change_open_by_other"===s?`${n} ${r} not saved: ${ca(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}: ${Bn}.`:`${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 ma(e){if("string"==typeof e)return e.length;const t=JSON.stringify(e);return void 0===t?0:t.length}function _a(e){const t={...e},n=[];for(const e of hr)e in t&&ma(t[e])>ir&&(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 ${ir} characters and was left out. Read it with atoms_get_item (${ua(e)}), then send your change again.`),t}function fa(e){return"string"==typeof e?`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`:Array.isArray(e)?e.map(fa):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,fa(t)])):e}function ha(e){const t=new TextEncoder,n=t.encode(JSON.stringify(e)??"").length,r=t.encode(JSON.stringify(fa(e),null,2)??"").length;return Math.max(n,r)}function ya(e,t=ha){if(t(e)<=sr)return e;const n=e.not_applied.map(e=>{const t={...e};let n=!1;for(const e of hr)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)<=sr)return r;const a=n.map(e=>{const{message:t,hint:n,...r}=e;return r});if(r={...r,not_applied:a},t(r)<=sr)return r;const{applied:i,...s}=r,o={...s,next_steps:r.next_steps.map(e=>e===cr?dr: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<lr&&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))<=sr?c=e:d=e-1}return l(c)}function ga(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??pa(a),i=t-r-1>0?` And ${t-r-1} more.`:"";if([...n,e].join(" ").length+i.length>or)break;n.push(e),r+=1}r<t&&n.push(`And ${t-r} more.`);const a=n.join(" ");return a.length<=or?a:a.slice(0,or)}function wa(e){const t=t=>e.not_applied.some(t),n=[cr];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(pr),t(e=>"skipped_typing"===e.status||"skipped"===e.status&&"typing"===e.reason)&&n.push(mr),t(e=>"locked"===e.status||"skipped"===e.status&&"locked"===e.reason)&&n.push(_r),t(e=>"conflict"===e.status&&("no_base"===e.reason||"bad_token"===e.reason))&&n.push(fr),n}function va(e,t,n){const r=e.applied.length+e.captured.length;return{isError:0===r,result:ya({...t??{},status:r>0?"partial":"error",code:"not_all_applied",retryable:!1,message:ga(e),next_steps:wa(e),applied:e.applied,not_applied:e.not_applied,seq:e.seq,...e.merged_fields.length>0?{merged_fields:e.merged_fields}:{}},n)}}function ba(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 ja(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)}`}(yr,e.map(String).join("\n"))}function ka(){return crypto.randomUUID()}function Sa(e){return[e.userId,e.projectId,"create_item",e.content,e.k,e.sessionId]}function Aa(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 $a(e){return Aa({userId:e.userId,projectId:e.projectId,family:xa(e.tool),key:e.key,itemIdOrK:e.itemId,path:["runs"],runHash:e.runHash,runK:e.k})}function Ia(e){return[e.userId,e.projectId,e.what,e.name]}function xa(e){return"atoms_create_item"===e||"atoms_bulk_import"===e?"item":e}function qa(e){const t=new Map;return e.map(e=>{const n=t.get(e)??0;return t.set(e,n+1),n})}function Oa(e){return"string"==typeof e?e.replace(/<\s*\/?\s*user_content\s*>/gi,""):Array.isArray(e)?e.map(Oa):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Oa(t)])):e}function Ea(e){return Pr(Oa({type:e.type,title:e.title,body:e.body??null,summary:e.summary??null,req_type:e.req_type??null,domains:gr(e.domains),level:e.level??null,parent_ids:gr(e.parent_ids),fields:e.fields??{}}))}function Ra(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 Ma(e,t,n){const r=[];let a=[],i=0;for(const s of e)a.length>0&&(i+1>t||a.length+s.ops.length>n)&&(r.push(a),a=[],i=0),a.push(...s.ops),i+=1;return a.length>0&&r.push(a),r.map(e=>e.sort((e,t)=>e.index-t.index).map(e=>e.op))}function Ta(e){return e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message:e)}function Ca(e){return/too_many_items/.test(Ta(e))}function Da(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 Ha(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||Mr(a.message??""))throw new Error(Vn);return null}return!!r&&"object"==typeof r&&!0===r.multiuser_saving}function Na(){return{status:"error",message:br,next_steps:["Send the same call again in a moment"],code:"rollout_state_unreadable",retryable:!0}}function Fa(e,t){const n=Ta(t);return"ops"===e&&on(n)?"main":"main"===e&&(ln(n)||n.includes(Fn))?"ops":null}async function Pa(e,t){try{return await t(e)}catch(n){const r=Fa(e,n);if(!r)throw n;return t(r)}}function za(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 Ua(e){return e.startsWith("op_id_reused: ")}function La(){return{status:"error",message:jr,next_steps:["Send the call again with a new idempotency_key, or without one"],code:"op_id_reused",retryable:!1}}async function Wa(e){return zr("string"==typeof e?e:Pr(Oa(e)))}async function Va(e){return e.content_hash=await Wa({kind:e.kind,value:e.value??null,order_key:e.order_key??null}),e}function Ba(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 Ja(e,t,n){const r=new Map,a=new Set,i=Ba(n),s=[...i.keys()];for(let n=0;n<s.length;n+=$r){const{data:o,error:l}=await e.rpc("mcp_op_answers",{p_project_id:t,p_op_ids:s.slice(n,n+$r)});if(l)throw Xr(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 Ga(e,t,n){const{found:r,reused:a}=await Ja(e,t,n);if(a.size>0)throw new Error(Ir);return r}async function Qa(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=Ba(r),{found:o,reused:l}=await Ja(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:jr};const t=o.get(e.op_id);return t?{...t,replayed:!0}:{...e,message:jr}})}function Ka(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 Ya,Za,Xa,ei,ti,ni,ri,ai,ii,si=V({"src/core/agent-saving.ts"(){rn(),pn(),xr(),ee(),Fn="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.",Pn="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: ",""),zn="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.",Un="This project is in the Trash. Nothing was saved. A project admin can restore it in ATOMS, then try again.",Ln="PROJECT_IN_TRASH",Wn="You no longer have access to this project. Ask an admin of its organization to add you back.",Vn="PROJECT_ACCESS_LOST",Bn="it is approved under change control, so it cannot be moved to Trash",Jn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Gn=2e3,Qn=20,Kn=[["title"],["summary"],["body"],["req_type"],["status"],["tags","domains"],["tags","level"]],Yn=[["title"],["body"],["analysis_props"],["relationships"]],Zn=new Set(["item","all","analysis","core","variable"]),Xn=/^([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,er=new Set(["title","type","approver_user_id","requires_impacted_approval"]),tr=new Set(["variables","taxonomy","settings"]),nr="The items were saved, but their base_token could not be read. Read each item with atoms_get_item before you update it.",rr={'["title"]':"Title",'["summary"]':"Summary",'["body"]':"Body",'["req_type"]':"Type",'["type"]':"Type",'["status"]':"Status",'["tags","level"]':"Level",'["tags","domains"]':"Domains",'["asil_confirm_lower"]':"ASIL"},ar=new Set(["applied","noop","replaced"]),ir=4e3,sr=65536,or=600,lr=200,cr="Changes under applied are saved; do not send them again. Tell the person which changes were not saved and why.",dr="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.",ur=64,pr="For each conflict: merge theirs_value with your change, then call the tool again with that entry's base_token.",mr="For a field someone is typing in: offer to try again in a minute.",_r="For a locked item: ask the person it is locked to, or an admin, to unlock it.",fr="For a change with no base: read the item with atoms_get_item, or use the entry's base_token, then send it again.",hr=["your_value","theirs_value","base_value"],yr="0b7e5c1a-3d2f-4e6b-9a8c-1f2e3d4c5b6a",gr=e=>[...new Set((e??[]).map(e=>String(Oa(e))))].sort(),wr=50,vr=500,br="Could not read how this project saves, so nothing was saved. Try again.",kr="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.",Sr="Already created by an earlier identical call. Nothing new was created. To create another copy, call again with a new idempotency_key.",Ar="Already recorded by an earlier identical call. Nothing new was stored. To record another run, call again with a new idempotency_key.",$r=500,Ir="op_id_reused: "+(jr="idempotency_key already used for a different change; use a new key.")}});function oi(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 li(e){return{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken.replace(/^Bearer\s+/i,"")}`,...e.anonKey?{apikey:e.anonKey}:{}}}async function ci(e,t,n){try{if(!e.supabaseUrl||!e.accessToken)return;const r=e.fetch??fetch,a=[...new Set(n)],i=a.slice(0,ti);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 ${ti} in one call)`);const s=[];for(let n=0;n<i.length;n+=ei){const a=i.slice(n,n+ei).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:li(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:oi(e.data??{})})).filter(e=>e.text.trim().length>=3),i=[];for(let e=0;e<a.length;e+=Za)i.push(a.slice(e,e+Za));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:li(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(Xa,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 di(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&&Ya.includes(e))&&t.add(n.item_id)}return[...t]}function ui(e,t,n){return`${e.supabaseUrl}/rest/v1/project_changes?project_id=eq.${encodeURIComponent(t)}&bulk_id=eq.${encodeURIComponent(n)}`}function pi(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e[ai];return t&&"object"==typeof t?t:null}function mi(e){const t=globalThis.EdgeRuntime;try{t?.waitUntil?.(e)}catch{}}function _i(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&&ii.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?di(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);mi(ci(n,a,r))}}}catch(e){console.error("[embed-on-save] not queued:",e instanceof Error?e.message:e)}return a}}var fi,hi,yi,gi,wi,vi,bi=V({"src/core/embed-on-save.ts"(){Ya=["title","body","summary","tags","type"],Za=5,Xa=3,ei=100,ti=500,ni=1e3,ri=5e3,ai=Symbol.for("atoms.embedOnSave.config"),ii=new Set(["save_item_with_revision","bulk_save_items_with_revisions","apply_item_ops"])}});function ji(e){const t=fi[e];return[...t.top,...t.other]}async function ki(e,t,n){const r=function(e){const t=ji(e);return gi.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 Si(e){return function(e){return"medical"!==(e.industry??"automotive")&&!e.holdsAnalysisOutsideAutomotive}(e)?e.hazardGoalItemsOn&&e.multiuserSavingOn?null:vi:wi}var Ai,$i,Ii,xi,qi,Oi=V({"src/core/analysis-industry.ts"(){fi={automotive:{top:["iso26262","design"],other:[]},medical:{top:["iso14971","tir57","process"],other:["software","use"]}},hi={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"},yi={automotive:"Automotive (ISO 26262)",medical:"Medical device (ISO 14971)"},gi=Object.keys(hi),wi="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.",vi="rollout_switched:hazard_goal_items"}});function Ei(e){const t=Ai.exec(e);return t?t[1]:null}function Ri(e){return e.includes("function_is_item")}function Mi(){return{status:"error",code:"function_is_item",retryable:!1,message:xi,next_steps:['Create a Function with atoms_create_item and type "function", or edit the Function item itself',"Do not retry this call"]}}function Ti(){return{status:"error",code:"rollout_switched",key:"hazard_goal_items",retryable:!1,message:qi,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 Ci(e){return e.includes("hazard_goal_not_automotive")}function Di(){return{status:"error",code:"hazard_goal_not_automotive",retryable:!1,message:`Validation error: ${wi} This change was not saved.`,next_steps:["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)","Do not retry this call"]}}var Hi,Ni,Fi,Pi,zi,Ui,Li,Wi=V({"src/core/rollout-errors.ts"(){Oi(),Ai=/rollout_switched:([a-z][a-z0-9_]{2,62})/,$i="This project's saving rules just changed. Read the item again, then retry your change.",Ii="Function items are not on for this project yet, so a Function item cannot be created here. This change was not saved.",xi="Validation error: this project's Functions are items now, so its function tag list no longer changes. This change was not saved.",qi="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 Vi(e,t){const n=Fi.indexOf(String(e??"")),r=Fi.indexOf(String(t??""));return n<0||r<0?Hi:Pi[n][r]}function Bi(e){return"Moderate"===e||"High"===e||"Very High"===e}var Ji,Gi,Qi,Ki=V({"src/core/securityScheme.ts"(){Hi="-",Ni=["Very Low","Low","Moderate","High","Very High"],Fi=["1","2","3","4","5"],Pi=[["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"]],zi={"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"},Ui=[{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"}],Li={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 Yi(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 Zi(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. ${Qi}`}function Xi(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 es(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function ts(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 ns(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}=ts(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 rs,as,is,ss,os,ls,cs,ds,us,ps,ms,_s,fs,hs,ys,gs,ws,vs,bs,js,ks,Ss,As,$s,Is,xs,qs,Os,Es,Rs,Ms,Ts,Cs,Ds,Hs,Ns,Fs,Ps,zs,Us,Ls,Ws,Vs,Bs,Js,Gs,Qs,Ks,Ys,Zs,Xs,eo,to,no,ro=V({"src/core/acceptance.ts"(){Ji=["acceptance_state","accepted_by","accepted_at","acceptance_note","open_gaps_at_acceptance"],Gi=["prev_accepted_by","prev_accepted_at","accepted_snapshot_id","accepted_snapshot_name"],Qi="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 ao(e){return t=e?.industry,"automotive"===t||"medical"===t?e.industry:null;var t}function io(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 so(e){return as[e]}function oo(e){return is.some(t=>t.id===e)||function(e){return Ui.some(t=>t.id===e)}(e)}function lo(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:os,source:"fallback"}}function co(e){const t=(e??"").trim().toLowerCase();return"sub-system"===t?"subsystem":t}function uo(e,t){const n=lo(e),r=lo(t);return co(n.level)===co(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 po(e,t,n){if("title"!==t&&("dfmea"!==e||"failure_mode"!==t)||n.length<=cs)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 ${cs}. Shorten it to ${cs} or fewer.`}function mo(e){const t=(e.failure_mode??"").trim()||(e.hazard??"").trim()||"";if(t.length<=cs)return t;const n=t.slice(0,cs);return/[\uD800-\uDBFF]$/.test(n)?n.slice(0,-1):n}function _o(e){return"hazard_iso14971"===e?Ss:"security_tir57"===e?xs:[]}function fo(e){return"security_tir57"===e?Ni:As}function ho(e){return String(e??"").split(/\r\n?|\n/).map(e=>e.trim()).filter(e=>""!==e)}function yo(e){const t=e??{};return{intended_use:String(t.intended_use??"").trim(),foreseeable_misuse:ho(t.foreseeable_misuse),safety_characteristics:ho(t.safety_characteristics)}}function go(e,t=As){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:$s.includes(a)?a:"",safety_rationale:String(n.software_safety_rationale??"").trim()}}function wo(e){return""!==yo(e).intended_use}function vo(e,t){const n=_o(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 bo(e,t,n){return`Invalid ${e} value ${JSON.stringify(t)}. Allowed: ${n.join(", ")}`}function jo(e){const t=e?.analysis_props;return null===t||"object"!=typeof t||Array.isArray(t)?"legacy":t.event_model===Ms?"hazard_goal":"legacy"}function ko(e,t){return"hara_iso26262"===e&&"hazard_goal"===t?Ts:Os[e]}function So(e){return"risk_analysis"===e||"hazard_analysis"===e?["iso14971"]:"security_risk"===e?["tir57"]:rs[Cs[e]]}function Ao(e){return Object.entries(Vs[e]).map(([e,t])=>({key:e,label:t}))}function $o(e,t){const n=Vs[e];return t.map(e=>({key:e,label:n[e]??e}))}function Io(e){return Object.entries(function(e){return"hara_iso26262"===e?Ps:"dfmea_rpn"===e?Ls:"hazard_iso14971"===e?Us:"security_tir57"===e?Li:Ws}(e)).map(([e,t])=>({key:e,text:t}))}function xo(e){return"hazard_iso14971"===e?ys:"security_tir57"===e?zi:null}function qo(e,t){const n=xo(e);return n?n[t]??null:null}function Oo(e){return(e??"").trim().toLowerCase()}function Eo(e,t){const n=Oo(e);if(!n)return null;for(const e of t)if(Oo(e)===n)return e;return null}function Ro(e){const t=e?.severity||"",n=e?.exposure||"",r=e?.controllability||"";return t&&n&&r?"S0"===t||"E0"===n||"C0"===r?"QM":ps[`${t}-${n}-${r}`]||ds:ds}function Mo(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)?ds:String(t*n*r)}function To(e,t,n){const r=String(e??""),a=String(t??""),i=String(n??"");if(_s.indexOf(r)<0||_s.indexOf(a)<0||_s.indexOf(i)<0)return ds;const s=fs[`${a}-${i}`];return s&&hs[`${s}-${r}`]||ds}function Co(e){return To(e?.severity,e?.p1,e?.p2)}function Do(e){return To(e?.residual_s,e?.residual_p1,e?.residual_p2)}function Ho(e){return Vi(e?.severity,e?.exploitability)}function No(e){return Vi(e?.residual_s,e?.residual_e)}function Fo(e,t){return"hara_iso26262"===e?Ro(t):"hazard_iso14971"===e?Co(t):"security_tir57"===e?Ho(t):"fmea_software"===e?function(e){return Mo({...e??{},occurrence:gs})}(t):Mo(t)}function Po(e,t,n,r){if(n)return!1;if("hara_iso26262"===e&&r?.cited&&r.satisfied)return!1;if("hara_iso26262"===e){const e=Ro(t);return"C"===e||"D"===e}if("hazard_iso14971"===e)return"High"===Co(t);if("security_tir57"===e){const e=Ho(t);return"High"===e||"Very High"===e}const a=parseInt(Fo(e,t),10);return!Number.isNaN(a)&&a>=200}function zo(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 Uo(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 Lo(e){return"fmea_software"===e?{field:"occurrence",value:gs}:null}function Wo(e){const t=Lo(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 Vo(e){return Qs[e]}function Bo(e){return"security_tir57"===e?Ui:function(e){return"hazard_iso14971"===e||"fmea_process"===e||"fmea_software"===e||"fmea_use"===e}(e)?is:[]}function Jo(e){return Bo(e).map((e,t)=>({...e,precedence:t+1}))}function Go(e){return"hara_iso26262"===e||"hazard_iso14971"===e||"security_tir57"===e}function Qo(e,t){return`${e} is not a ${Qs[t].mitigating_requirement}: a mitigation target must be a requirement of req_type '${ss}'. Create or convert one, then link it.`}function Ko(e){return`control_type applies to the medical schemes only (ISO 14971 clause 7); ${Qs[e].parent} links carry none, so omit it.`}function Yo(e){return"security_tir57"===e?`control_type is required for a security control link (FDA Appendix 1). Choose one of: ${Ui.map(e=>`${e.id} (${e.label})`).join(", ")}.`:`control_type is required for a risk control link (ISO 14971 clause 7). Choose one of: ${is.map(e=>`${e.id} (${e.label})`).join(", ")}.`}function Zo(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 Xo(e){const t=parseInt(e,10);return!Number.isNaN(t)&&t>=100}function el(e){return"hara_iso26262"===e?Zs:"hazard_iso14971"===e?Xs:"security_tir57"===e?to:eo}function tl(e){return!0===e.approved&&(e.approved=!1,e.approved_at=null,e.approved_by=null,e.approved_note="",!0)}function nl(e,t,n,r){const a=[];for(const i of el(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 rl(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function al(e,t,n=Oo){const r=new Set(t.map(n).filter(e=>e.length>0));return e.filter(e=>r.has(n(e)))}function il(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 sl,ol,ll,cl=V({"src/core/analysis.ts"(){Ki(),Ki(),ro(),rs={hara:["iso26262","iso14971","tir57"],dfmea:["design","process","software","use"]},as={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"},is=[{id:"inherent",label:"Inherent design",abbr:"ID"},{id:"protective",label:"Protective measure",abbr:"PM"},{id:"information",label:"Information for safety",abbr:"IFS"}],ss="safety",os="L1",ls=8,cs=500,ds="-",us=["prevention","detection","mitigation"],ps={"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"},fs={"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"},hs={"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"},ys={Low:"Acceptable",Medium:"Acceptable with justification",High:"Not acceptable"},gs="10",ws={hara_iso26262:{severity:["S0","S1","S2","S3"],exposure:["E0","E1","E2","E3","E4"],controllability:["C0","C1","C2","C3"]},dfmea_rpn:{severity:ms=["1","2","3","4","5","6","7","8","9","10"],occurrence:ms,detection:ms},hazard_iso14971:{severity:_s=["1","2","3","4","5"],p1:_s,p2:_s,residual_s:_s,residual_p1:_s,residual_p2:_s},fmea_process:{severity:ms,occurrence:ms,detection:ms},fmea_software:{severity:ms,detection:ms},fmea_use:{severity:ms,occurrence:ms,detection:ms},security_tir57:{severity:[...Fi],exploitability:[...Fi],residual_s:[...Fi],residual_e:[...Fi]}},vs={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"]},bs={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"}},js=["intended_use","foreseeable_misuse","safety_characteristics"],ks=["overall_residual_risk","overall_residual_rationale","software_safety_class","software_safety_rationale"],Ss=[...js,...ks],As=["Low","Medium","High"],$s=["A","B","C"],Is=["threat_model_method","threat_model_rationale","environment_assumptions","attack_surfaces","related_documents","overall_residual_risk","overall_residual_rationale"],xs=[...Is,"lifecycle_sources"],qs={hara:"safety-goal",dfmea:"failure-mode"},Os={hara_iso26262:"SG",dfmea_rpn:"FM",hazard_iso14971:"RSK",fmea_process:"PF",fmea_software:"FM",fmea_use:"FM",security_tir57:"CYB"},Es={hara_iso26262:"HARA",dfmea_rpn:"DFMEA",hazard_iso14971:"RA",fmea_process:"PFMEA",fmea_software:"SFMEA",fmea_use:"UFMEA",security_tir57:"SEC"},Rs=["HA"],Array.from(new Set([...Object.values(Es),...Object.values(Os),...Rs])).sort(),Ms="hazard_goal",Ts="HE",Cs={hara:"hara",dfmea:"dfmea",risk_analysis:"hara",fmea:"dfmea",hazard_analysis:"hara",security_risk:"hara"},Ds=["hara","dfmea","risk_analysis","fmea","hazard_analysis","security_risk"],Hs={hara:"iso26262",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"design",fmea:"process",security_risk:"tir57"},Ns={hara:"iso14971",risk_analysis:"iso14971",hazard_analysis:"iso14971",dfmea:"process",fmea:"process",security_risk:"tir57"},Fs={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."},Ps={...Fs,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:Zi("The confirmation review of the HARA (ISO 26262)")},zs={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)."},Us={...Fs,...zs,accept_analysis:Zi("The ISO 14971 clause 8 overall residual risk conclusion")},Ls={...Fs,dfmea_s:Ps.dfmea_s,o:Ps.o,d:Ps.d,rpn:Ps.rpn,accept_analysis:Zi("The AIAG-VDA FMEA sign-off")},Ws={...Fs,dfmea_s:zs.dfmea_s,o:zs.o,o_sw:zs.o_sw,d:zs.d,rpn:zs.rpn,process_step:zs.process_step,controls:zs.controls,fn:zs.fn,risk_control:zs.risk_control,control_req:zs.control_req,verified_by:zs.verified_by,accept_analysis:Zi("The FMEA sign-off")},Vs={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"}},Bs=["asil","rpn","risk","p0"],Js=["approved","approved_at","approved_by","approved_note","field_source","link_roles","mitigation_types"],Gs=[...Bs,...Js],Qs={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"}},Ks=(e,t,n)=>1===e?t:n,Zs=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft safety requirement",label:e=>`${e} ${Ks(e,"safety goal","safety goals")} unmitigated`,matches:e=>e.level!==ds&&"QM"!==e.level&&!e.linked},{kind:"no_test",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Ks(e,"safety goal","safety goals")} without a test on its ODD`,matches:e=>e.level!==ds&&"QM"!==e.level&&e.linked&&!e.verified},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} ${Ks(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},Ys={kind:"not_accepted",scope:"analysis",fix:"open_analysis",fixLabel:"Accept analysis",label:()=>"Analysis not accepted",matchesAnalysis:e=>e.hasRows&&!e.accepted}],Xs=[{kind:"no_control",scope:"row",fix:"link_requirement",fixLabel:"Draft risk control requirement",label:e=>`${e} ${Ks(e,"risk","risks")} above Low with no control`,matches:e=>e.level!==ds&&"Low"!==e.level&&!e.linked},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Ks(e,"control","controls")} not verified for effectiveness`,matches:e=>e.level!==ds&&"Low"!==e.level&&e.linked&&!e.verified},{kind:"no_residual",scope:"row",fix:"open_row",fixLabel:"Assess residual risk",label:e=>`${e} residual ${Ks(e,"risk","risks")} not assessed`,matches:e=>e.level!==ds&&"Low"!==e.level&&e.linked&&e.residualLevel===ds},{kind:"no_parent",scope:"requirement",fix:"open_item",fixLabel:"Set parent",label:e=>`${e} risk ${Ks(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},Ys],eo=[{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=>Xo(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=>!Xo(e.level)&&null!==e.severity&&e.severity>=9&&!e.linked},Ys],to=[{kind:"unmitigated",scope:"row",fix:"link_requirement",fixLabel:"Draft security control",label:e=>`${e} security ${Ks(e,"risk","risks")} above Low with no control`,matches:e=>Bi(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===ds},{kind:"not_verified",scope:"row",fix:"link_test",fixLabel:"Link a test",label:e=>`${e} ${Ks(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===ds},{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(Bi(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 ${Ks(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},Ys],no=[{kind:"row_no_goal",fix:"open_row",fixLabel:"Set the safety goal",informational:!1,label:e=>`${e} hazardous ${Ks(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} ${Ks(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} ${Ks(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} ${Ks(e,"hazard","hazards")} cited by no hazardous event`},{kind:"goal_trashed",fix:"open_row",fixLabel:"Open row",informational:!0,label:e=>`${e} hazardous ${Ks(e,"event cites","events cite")} a safety goal in Trash`}]}});async function dl(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:Eo(n,r)??Eo(n,a);return{spelling:i,registered:null!==i&&r.includes(i),carried:a.filter(e=>null!==Eo(e,[n]))}}async function ul(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 pl(e){return`Domain "${e}" registered. You can now tag items with domains=["${e}"].`}function ml(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 _l(e){return`Domain "${e}" already exists. Choose a different name.`}var fl,hl,yl,gl,wl=V({"src/core/domains.ts"(){cl(),sl="domain_not_function",ol=class extends Error{code=sl;names;unregistered;constructor(e,t=[]){super(`${sl}: ${e.join(", ")}`),this.name="DomainNotFunctionError",this.names=[...e],this.unregistered=[...t]}},ll="domain_rename_onto_function"}});function vl(){return{status:"error",code:hl,retryable:!0,message:yl,next_steps:["Send the same call again in a moment","If it times out again, tell the user ATOMS is slow right now"]}}function bl(e,t){return"57014"===e||/statement timeout|request timeout|upstream request timeout/i.test(t)}var jl,kl,Sl,Al=V({"src/core/read-budget.ts"(){fl=25e3,hl="read_timed_out",yl="ATOMS did not answer this read in time, so nothing was returned. The read changes nothing: asking again is safe.",gl=class extends Error{code=hl;constructor(e){super(`${hl}: the read did not finish within ${e} ms`),this.name="ReadBudgetExceededError"}}}});function $l(e,t=0,n=kl){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 Il(e,t=jl,n,r){if(Sl(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 Il(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(Sl(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(Sl(i(1))>t)return null;let s=1,o=r.length-1;for(;s<o;){const e=Math.ceil((s+o)/2);Sl(i(e))<=t?s=e:o=e-1}return i(s)}(e,t,n);if(r)return r}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(;Sl(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 Sl(i)<=t?i:xl(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(Sl(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 xl(e,t,a)}function xl(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-Sl({...e,data:{preview:""},meta:r})-200);for(;;){const n={...e,data:{preview:a.slice(0,i)},meta:r},s=Sl(n)-t;if(s<=0||0===i)return n;i=Math.max(0,i-s)}}var ql,Ol,El,Rl=V({"src/core/response-limit.ts"(){jl=25e3,kl=1e3,Sl=e=>JSON.stringify(e,null,2).length}});function Ml(e){if(!e)return!1;const t=String(e.code??""),n=String(e.message??"");return"55P03"===t||"40P01"===t||/item_save_busy|deadlock detected/i.test(n)}async function Tl(e,t=ql){let n=await e();for(const r of t){if(!Ml(n.error))return n;await Ol.sleep(Math.round(r*Ol.jitter())),n=await e()}return n}async function Cl(e){const t=await e();return function(e){return null!=e.error&&[0,502,503,504].includes(e.status??-1)}(t)?(await Ol.sleep(250),e()):t}var Dl,Hl,Nl,Fl,Pl,zl,Ul=V({"src/core/busy-retry.ts"(){ql=[50,100,200,400,800],Ol={sleep:e=>new Promise(t=>setTimeout(t,e)),jitter:()=>.5+Math.random()},El=[250,1e3,3e3]}});function Ll(){return{status:"error",message:Dl,next_steps:["Do not retry this call","Tell the user that a person can restore it from Trash in ATOMS"],code:Hl,retryable:!1}}function Wl(e,t){const n=function(e){const t=e.status??-1;return 0===t||t>=500||Ml(e)||"57014"===e.code||/timeout|timed out|canceling statement/i.test(e.message)}(t),r=Nl.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 Vl(e){const t=e.trashed_by,n=t?.name?.trim()||"Someone";return t?.agent?`${n}'s agent`:n}function Bl(e){return(e.deleted_at??"").slice(0,10)}function Jl(e,t){const n=`Restored ${e.item_id} from Trash. It was moved there by ${Vl(e)} on ${Bl(e)}`;return e.trashed_by?.user_id&&e.trashed_by.user_id!==t?`${n}; they have been notified.`:`${n}.`}var Gl,Ql,Kl,Yl,Zl,Xl,ec,tc,nc,rc=V({"src/core/restore-confirm.ts"(){Ul(),Dl="This item has been in Trash for more than 7 days. Only a person can restore it, from Trash in ATOMS.",Hl="item_trash_too_old",Nl=[[/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}`]],Fl=["Show the user this message","Call atoms_restore_item again with confirm: true only after the user agrees"],Pl='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',zl="true only after the user has seen the needs_confirmation message and agreed to the restore"}}),ac={};function ic(e,t=Ql){if("string"!=typeof e)return"";const n=e.replace(Zl,"").replace(Xl,"");return n.length<=t?n:n.slice(0,t)+"..."}function sc(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function oc(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function lc(e,t,n){return{total_count:e,limit:t,offset:n,has_more:n+t<e}}function cc(e,t,n={}){return{status:"error",message:e,next_steps:t,...n}}function dc(e,t){return cc(`${e} '${ic(t)}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function uc(e){return"account"===e?cc("Account suspended.",["Your ATOMS account is suspended, so ATOMS tools are unavailable","Contact ATOMS support or your organization admin to restore access"]):cc("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 pc(e){const t=/\b(account|organization) suspended\b/i.exec(e);return t?t[1].toLowerCase():null}function mc(e){return cc(`${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 _c(e,t=Kl){return cc(`Validation error: ${ic(e,t)}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function fc(){return cc("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 hc(){return cc("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 yc(e){return cc("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 gc(e){return cc("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 wc(e){return function(e){const t=e&&e>0?Math.ceil(e):tn;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 vc(){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 bc(e){return cc(`Parse error: ${ic(e,Kl)}`,["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 jc(e){return function(e){return/stale_item_write|sqlstate\s*40001|could not serialize access/i.test(e)}(e)}function kc(){return cc("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 Sc(){return cc("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 Ac(){return cc("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 $c(){return cc("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 Ic(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 xc(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,Yt.some(e=>e.test(a)))return _c(n,Yl);var a,i;if(e instanceof Zt)return _c(n);if(on(n))return qc(e);if(qr(n))return Or();if(Ua(n))return La();if(Ei(n))return"function_items"===(i=Ei(n))?{status:"error",code:"rollout_switched",key:"function_items",retryable:!1,message:Ii,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?Ti():{status:"error",code:"rollout_switched",retryable:!0,message:$i,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(Ri(n))return Mi();if(Ci(n))return Di();if(/^auth_unavailable:/.test(n))return Nt();if(/^read_timed_out:/.test(n))return vl();if(t.read&&bl(r,n))return vl();if(/not authenticated/i.test(n))return fc();const s=function(e){const t=function(e){if(e instanceof ol)return e.names;if(e&&"object"==typeof e&&e.code===sl){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!==Eo(e,t)),i={code:sl,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(Ic(e))return hc();if(Er(n))return Rr();const o=un(n);if(null!==o)return o;if(function(e){return/item_trash_too_old/i.test(e)}(n))return Ll();if(Mr(n))return Tr();const l=Nr(n);if(null!==l)return l;const c=Cr(n);if(null!==c)return c;const d=Dr(n);if(null!==d)return d;const u=ae(n);if(null!==u)return u;if("55P03"===r||function(e,t){return"40P01"===e||/deadlock detected/i.test(t)}(r,n)||/item_save_busy/i.test(n))return Sc();if(function(e,t){return!/^[0-9A-Z]{5}$/.test(e)&&/rate.?limit|too many requests|429/i.test(t)}(r,n))return wc();if(jc(n))return kc();if(/soft_deleted_item_write/i.test(n))return $c();if(/save_temporarily_unavailable/i.test(n))return Ac();if("55P03"===r||bl(r,n)||/item_save_busy/i.test(n))return Sc();const p=pc(n);return p?uc(p):"42501"===r&&/org_project_field_admin_required/i.test(n)?cn("organization"):"42501"===r&&/project_field/i.test(n)?cn("project"):"P0002"===r&&/project_field/i.test(n)?cc("Project field not found.",["Refresh the field list and retry with an existing field name"]):"22023"===r&&/^project_field_values_incompatible:/i.test(n)?_c(n.replace(/^project_field_values_incompatible:\s*/i,"")):["22023","23505","23514"].includes(r)&&/project_field/i.test(n)?_c(n.replace(/^project_field_/i,"").replace(/_/g," ")):/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(n)?bc(n):Ec(n)}function qc(e){const t=e instanceof Error?e.message:String(e&&"object"==typeof e&&"message"in e?e.message??"":e??"");if(!on(t)&&!ln(t))return null;const n=t.indexOf(ec);return cc((n>=0?t.slice(n+ec.length):t).trim(),["Wait a moment, read the item again (atoms_get_item), then send your change again"],{code:"rollout_switched",retryable:!0})}function Oc(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=ae(t);return["40001","PT409","55P03","57014"].includes(n)||null!==Ei(t)||null!==r&&"mcp_policy_block_destructive"!==r.code||/stale_item_write|soft_deleted_item_write|save_temporarily_unavailable|item_save_busy|statement timeout|request timeout|upstream request timeout|fetch failed|network error|connection (?:closed|reset|refused)/i.test(t)}function Ec(e){if(/^auth_unavailable:/.test(e))return Nt();const t=un(e);if(null!==t)return t;if(an(e))return wc();if(sn(e))return hc();if(/^not authenticated/i.test(e))return fc();if(Er(e))return Rr();if(qr(e))return Or();if(Ua(e))return La();if(Ri(e))return Mi();if(Ci(e))return Di();if(Mr(e))return Tr();const n=Nr(e);if(null!==n)return n;const r=Cr(e);if(null!==r)return r;const a=Dr(e);if(null!==a)return a;const i=ae(e);return null!==i?i:/row.level security|permission denied for/i.test(e)?cc("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"]):cc(`Database error: ${ic(e,Kl)}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function Rc(e){return null==e?e:`<user_content>${e.replace(/<\/\s*user_content\s*>/gi,"</user_content>")}</user_content>`}function Mc(e){return"string"!=typeof e?e:e.replace(/<\s*\/?\s*user_content\s*>/gi,"")}function Tc(e){return tc.has(e)}function Cc(e,t,n=!1){return"string"==typeof e?n||null!=t&&tc.has(t)?Rc(e):e:Array.isArray(e)?e.map(e=>Cc(e,t,n)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Cc(t,e,n||nc.has(e))])):e}function Dc(e,t={}){const n=t.complete?e:Il(e,void 0,t.paging,t.receipt);return{content:[{type:"text",text:JSON.stringify(Cc(n),null,2)}],structuredContent:n}}function Hc(e){return{content:[{type:"text",text:JSON.stringify(Cc(e),null,2)}],structuredContent:e,isError:!0}}B(ac,{CHARACTER_LIMIT:()=>Gl,USER_CONTENT_KEYS:()=>tc,VALIDATION_MESSAGE_LONG:()=>Yl,accessDeniedError:()=>mc,authError:()=>fc,classifyError:()=>xc,dbError:()=>Ec,errorResponse:()=>cc,formatErrorResult:()=>Hc,formatToolResult:()=>Dc,isAutoWrappedKey:()=>Tc,isItemSaveStopError:()=>Oc,isJwtExpiredErrorForTool:()=>Ic,isStaleWriteErrorMessage:()=>jc,jwtExpiredError:()=>hc,notFoundError:()=>dc,orgScopeError:()=>gc,paginationMeta:()=>lc,parseError:()=>bc,policyNotLoadedError:()=>vc,rateLimitError:()=>wc,sanitizeForEcho:()=>ic,sanitizeTagOrLevel:()=>sc,saveBusyError:()=>Sc,saveUnavailableError:()=>Ac,scopeError:()=>yc,softDeletedItemError:()=>$c,staleWriteError:()=>kc,stripUserContentMarkers:()=>Mc,success:()=>oc,suspendedError:()=>uc,suspensionKind:()=>pc,switchRedoFailedError:()=>qc,validationError:()=>_c,wrapMcpUserContentFields:()=>Cc,wrapUserContent:()=>Rc});var Nc,Fc,Pc,zc=V({"src/tools/_base.ts"(){pn(),Wi(),wl(),zt(),Al(),ue(),Rl(),si(),rc(),Gl=25e3,Ql=50,Kl=200,Yl=600,Zl=new RegExp("[\\u0000-\\u001F\\u007F]","g"),Xl=new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]","g"),ec="rollout_switched:multiuser_saving: ",tc=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"]),nc=new Set(["fields","diff","point","theirs_value","base_value","your_value","old_value","new_value"])}});async function Uc(e,t){const n=Fc.get(t),r=Date.now();if(n&&r-n.at<Nc)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 Fc.set(t,{status:s,at:r}),s}function Lc(e){return JSON.stringify(Cc(e),null,2)}var Wc,Vc,Bc,Jc,Gc,Qc,Kc,Yc,Zc=V({"src/middleware/status-gate.ts"(){zc(),je(),Nc=3e4,Fc=new Map,Pc="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."}}),Xc={};async function ed(){if(Wc)try{const e=await st();e&&e.expires_at>Gc&&(process.stderr.write("[atoms-mcp] Credentials file refreshed elsewhere — rebuilding client.\n"),td())}catch{}if(Wc&&Jc>Date.now()+6e4)return Wc;Wc&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:n}=await async function(){if(Qc&&Date.now()-Qc.at<1e3*Rt)throw Qc.error;return Kc??=Wt().then(e=>(Qc=null,e)).catch(e=>{throw e instanceof Tt&&(Qc={at:Date.now(),error:e}),e}).finally(()=>{Kc=null}),Kc}(),r=e.split(".");if(3===r.length)try{const e=JSON.parse(Buffer.from(r[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());Jc=1e3*(e.exp??0)}catch{Jc=Date.now()+36e5}try{const e=await st();Gc=e?.expires_at??0}catch{Gc=0}const a=function(e,t){try{Object.defineProperty(e,ai,{value:t,enumerable:!1,configurable:!0})}catch{}return e}(d(At,$t,{global:{headers:{Authorization:`Bearer ${e}`},fetch:_i({supabaseUrl:At,anonKey:$t,accessToken:e})}}),{supabaseUrl:At,anonKey:$t,accessToken:e});return Vc=t,Bc=n,Wc=a}function td(){Qc=null,Wc=null,Vc=null,Bc=null,Yc=void 0,Jc=0,Gc=0,Fc.clear()}function nd(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 rd(e){try{return await e()}catch(t){if(!nd(t))throw t;return process.stderr.write("[atoms-mcp] Data tier rejected JWT — invalidating client and retrying once.\n"),td(),await e()}}function ad(){if(!Vc)throw new Error("Not authenticated. Call getClient() first.");return Vc}function id(){return Bc??""}async function sd(e){const t=ad();if(Yc&&Yc.userId===t)return Yc.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 Yc={userId:t,name:a},a}catch{return null}}function od(e){if(e&&e.deleted_at)throw new Error(Ln)}async function ld(e,t){const{data:n,error:r}=await e.from("projects").select("deleted_at").eq("id",t).maybeSingle();if(r||!n)throw Hr(t,r);od(n)}async function cd(e,t){const n=ad(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Hr(t,a);od(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 dd(e,t){const n=ad(),{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a||!r)throw Hr(t,a);od(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")}B(Xc,{assertProjectLive:()=>ld,getClient:()=>ed,getUserEmail:()=>id,getUserId:()=>ad,getUserName:()=>sd,invalidateClient:()=>td,isJwtExpiredError:()=>nd,requireProjectFieldDefinitionAccess:()=>dd,requireWriteAccess:()=>cd,throwIfProjectInTrash:()=>od,withJwtRetry:()=>rd});var ud,pd,md=V({"src/db/client.ts"(){Gt(),zt(),wt(),Dt(),si(),bi(),Zc(),Wc=null,Vc=null,Bc=null,Jc=0,Gc=0,Qc=null,Kc=null}}),_d={};async function fd(){const e=_(32).toString("base64url"),t=f("sha256").update(e).digest("base64url"),n=`http://localhost:${ud}${pd}`,r=new y(`${It}/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 a;function i(){clearTimeout(a)}const s=u(async(r,a)=>{const o=new y(r.url??"/",`http://localhost:${ud}`);if(o.pathname!==pd)return a.writeHead(404),void a.end("Not found");try{if("access_denied"===o.searchParams.get("error"))return a.writeHead(200,{"Content-Type":"text/html"}),a.end(hd("Authorization was cancelled.")),i(),s.close(),void n(new Error("Authorization cancelled by user."));const r=o.searchParams.get("code");if(r){const o=await fetch(`${At}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:$t},body:JSON.stringify({auth_code:r,code_verifier:e})}),l=await o.json();if(!o.ok||!l.access_token){const e=l.error_description??l.msg??"Unknown error";return a.writeHead(200,{"Content-Type":"text/html"}),a.end(hd(`Code exchange failed: ${e}`)),i(),s.close(),void n(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(l.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:d}=await import("@supabase/supabase-js"),u=d(At,$t,{global:{headers:{Authorization:`Bearer ${l.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(hd('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.')),i(),s.close(),void n(new Error("No ATOMS account found. Sign up at atoms.tech first."))):l.refresh_token?(await ot({access_token:l.access_token,refresh_token:l.refresh_token,expires_at:Date.now()+1e3*(l.expires_in??3600),user_email:c}),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)),i(),s.close(),void t({email:c})):(a.writeHead(200,{"Content-Type":"text/html"}),a.end(hd("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.")),i(),s.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(hd("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"),i(),s.close(),n(e)}});s.listen(ud,"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")}}),a=setTimeout(()=>{s.close(),n(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp@latest login' to try again."))},6e4)})}function hd(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>`}B(_d,{login:()=>fd});var yd=V({"src/auth/login.ts"(){wt(),Dt(),ud=19275,pd="/callback"}}),gd={};async function wd(){const{getValidToken:e,readValidToken:t}=await Promise.resolve().then(()=>(Gt(),Ut)),{runExclusiveAuth:n}=await Promise.resolve().then(()=>(xt(),vt)),{login:r}=await Promise.resolve().then(()=>(yd(),_d));try{return(await e()).email}catch(e){if(e instanceof Tt)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}}B(gd,{startupAuth:()=>wd});var vd,bd,jd,kd=V({"src/auth/startup.ts"(){zt()}});function Sd(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&&vd.has(n.level)?{level:n.level,source:"string"==typeof n.source?n.source:null,dismissed:!0===n.dismissed}:null}function Ad(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?Sd(e.data):null;return a&&(r.asil_pending_lower={value:a.level,source:a.source,dismissed:a.dismissed,since:t.since}),r}function $d(e){return{op_id:"",status:"forbidden",reason:"asil_lower_needs_person",item_id:e,path:[...bd],seq:null}}var Id,xd,qd,Od=V({"src/core/asil-read.ts"(){vd=new Set(["QM","A","B","C","D"]),bd=["asil_confirm_lower"],jd="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 Ed(e){return e.startsWith("req_type '")}function Rd(e,t){if("requirement"!==t)return`req_type applies only to requirements (type='requirement'), not '${t}'.`;const n=`Plain requirement types: ${Id.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}`:Id.includes(e)?null:`Unknown req_type '${e.slice(0,50)}'. Allowed: ${Id.join(", ")}.`}var Md,Td,Cd,Dd,Hd=V({"src/core/req-type.ts"(){Id=["functional","interface","performance","safety"],xd=["safety-goal","failure-mode"],qd="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 Nd(e,t=0){if(t>5)return"[depth-limit]";if("string"==typeof e){for(const t of Cd)if(t.test(e.trim()))return"[redacted]";return e.length>Dd?e.slice(0,Dd)+"…":e}if(Array.isArray(e))return e.slice(0,20).map(e=>Nd(e,t+1));if(null!==e&&"object"==typeof e){const n={};for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();Md.has(e)?n[r]="[redacted]":Td.has(e)?n[r]="string"==typeof a?"[content]":Nd(a,t+1):n[r]=Nd(a,t+1)}return n}return e}function Fd(e){return Nd(e)}var Pd,zd,Ud,Ld,Wd,Vd,Bd,Jd,Gd=V({"src/middleware/audit.ts"(){Md=new Set(["access_token","refresh_token","password","api_key","secret","token","authorization","credential","credentials","private_key"]),Td=new Set(["body","description","content","notes","summary","title","system_prompt","prompt"]),Cd=[/^[^\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_-]+$/],Dd=200}}),Qd=V({"src/middleware/rate-limiter.ts"(){Pd=60,zd=6e4}}),Kd={};function Yd(){return l.join(o(),".atoms","update-check.json")}async function Zd(){if(!Jd&&(Jd=!0,"1"!==process.env.ATOMS_MCP_NO_UPDATE_CHECK))try{const e=await async function(){try{const e=JSON.parse(await g.readFile(Yd(),"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<Ld)return void(Vd=e.latest);const t=new AbortController,n=setTimeout(()=>t.abort(),Wd);try{const e=await fetch(process.env.ATOMS_MCP_UPDATE_URL??Ud,{signal:t.signal});if(!e.ok)return;const n=await e.json();if("string"!=typeof n.version)return;Vd=n.version,await async function(e){try{await g.mkdir(l.dirname(Yd()),{recursive:!0}),await g.writeFile(Yd(),JSON.stringify({checked_at:Date.now(),latest:e}),"utf8")}catch{}}(n.version)}finally{clearTimeout(n)}}catch{}}function Xd(e){return null!==Vd&&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,Vd)?{current:e,latest:Vd,args:["@atoms-tech/atoms-mcp@latest"],command:"npx @atoms-tech/atoms-mcp@latest"}:null}function eu(e){const t=Xd(e);return t?Fr(t.current,t.latest):null}function tu(e){if(Bd)return null;const t=eu(e);return null===t?null:(Bd=!0,t)}function nu(e,t){const n=tu(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 ru(e,t){const n=Xd(t);if(null===n||!e||"object"!=typeof e)return e;const r=Fr(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 au(){Vd=null,Bd=!1,Jd=!1}B(Kd,{UPDATE_CHECK_TIMEOUT_MS:()=>Wd,attachUpdateAvailable:()=>ru,attachUpdateNotice:()=>nu,getUpdateAvailable:()=>Xd,resetUpdateCheckForTests:()=>au,startUpdateCheck:()=>Zd,takeUpdateNotice:()=>tu,updateStatusSentence:()=>eu});var iu,su,ou,lu,cu,du,uu,pu,mu,_u,fu,hu,yu,gu,wu,vu,bu,ju=V({"src/middleware/update-check.ts"(){si(),Ud="https://registry.npmjs.org/@atoms-tech/atoms-mcp/latest",Ld=864e5,Wd=3e3,Vd=null,Bd=!1,Jd=!1}}),ku=V({"src/core/timestamps.ts"(){}});function Su(e){return 32===e||9===e||13===e||10===e}function Au(e){if("string"!=typeof e)return NaN;const t=iu.exec(function(e){let t=0,n=e.length;for(;t<n&&Su(e.charCodeAt(t));)t++;for(;n>t&&Su(e.charCodeAt(n-1));)n--;return e.slice(t,n)}(e));if(!t)return NaN;const[,n,r,a,i="0",s="0",o="0",l="",c="Z"]=t,d=Number(n),u=Number(r),p=Number(a),m=Date.UTC(d,u-1,p,Number(i),Number(s),Number(o));if(new Date(m).getUTCDate()!==p)return NaN;let _=0;if("Z"!==c.toUpperCase()){const e="-"===c[0]?-1:1,t=c.slice(1).replace(":","");_=e*(60*Number(t.slice(0,2))+(t.length>2?Number(t.slice(2,4)):0))}return 1e3*(m-6e4*_)+Number(`${l}000000`.slice(0,6))}function $u(e,t){const n=Au(e),r=Au(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 Iu(e){return"passed"===e||"failed"===e||"blocked"===e}function xu(e){const t=[];return e.forEach((e,n)=>{e&&void 0!==e.date&&null!==e.date&&t.push(n)}),t}function qu(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 Ou(e){const t=[];return e.forEach((e,n)=>{const r=e?.release_id;"string"==typeof r&&""!==r.trim()||t.push(n)}),t}function Eu(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 Ru(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 Mu(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 Tu(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 Cu(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 Du(e,t){return"string"==typeof e?t(e):Array.isArray(e)?e.map(e=>Du(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Du(n,t)])):e}function Hu(e,t){const n=Du(e,t);return gu(n?.point)&&(n.point=Object.fromEntries(Object.entries(n.point).map(([e,n])=>[t(e),n]))),n}function Nu(e,t){if(!Array.isArray(e)||!Array.isArray(t))return e;const n=["source","plus","minus"];return e.map(e=>{if(!gu(e)||n.some(t=>t in e))return e;const r=t.find(t=>gu(t)&&t.name===e.name);return gu(r)&&JSON.stringify(r.values)===JSON.stringify(e.values)?{...e,...Object.fromEntries(Object.entries(r).filter(([e])=>n.includes(e)))}:e})}function Fu(e){const t=e.data?.status,n="test-case"===e.type?Vu(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||$u(r.date,n.date)<0)&&(n=r);return n}(e,e=>Iu(e.result))?.result;return Iu(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 Pu(e){const t=e.data?.runs;return"test-case"===e.type&&Array.isArray(t)&&t.length>0}function zu(e){return`${e} has runs: ${wu}. Record a run: atoms_record_test_result(s).`}function Uu(e,t){return"test-case"===e.type&&!Pu(e)&&("passed"===t||"failed"===t||"blocked"===t)}function Lu(e){return`${e} has no runs: ${vu}. Record a run: atoms_record_test_result(s).`}function Wu(e,t){const n="string"==typeof e.result?e.result:void 0;if(Iu(n))return n;if(!Array.isArray(e.step_results)||0===e.step_results.length)return"not-run";const r=e.step_results.map(e=>gu(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 Vu(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=>gu(e)?{...e,result:Wu(e,n)}:e)}var Bu,Ju,Gu,Qu,Ku,Yu,Zu,Xu,ep,tp=V({"src/core/run-order.ts"(){iu=/^([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,su="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).",ou="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.",lu="Ignored: the run is stamped with server time. A supplied date is reported in the response warning, never stored.",cu="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.",du="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.",uu="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).",pu="Ignored: the server pins the test case's current steps revision itself",mu="Link to evidence kept elsewhere, at most 2048 characters. Stored as text; ATOMS does not open it",_u="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",fu="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.",hu="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.",yu="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.",gu=e=>!!e&&"object"==typeof e&&!Array.isArray(e),wu="its status comes from its runs and cannot be set",vu="a result can only come from a run",bu="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 np(e){return"requirement"===e.type&&"string"==typeof e.data?.req_type&&xd.includes(e.data.req_type)}function rp(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 ap(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||!np(a)&&"goal"!==a.type)return;if("requirement"!==i.type||np(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 ip(e,t){const n=ap(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&&np(i)&&"goal"===r.get(n)?.type&&a.set(t,n)}const i=new Map;for(const[e,t]of n)np(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 sp(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 op(e,t){return Rn(()=>e.from("items").select(Bu).eq("project_id",t).eq("type","requirement").is("deleted_at",null).not("data->relationships->mitigates","is",null).neq("data->relationships->mitigates","[]"),wn)}function lp(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 up(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 up(t.data?.relationships?.mitigated_by))r.push({from_id:t.id,to_id:e,type:"mitigated_by"})}const a=ip([...n.values()],r);for(const t of e){const e=a.get(t.id);e&&a.set(t.id,[...new Set([...up(t.data?.relationships?.mitigated_by).filter(t=>e.includes(t)),...e])])}return a}async function cp(e,t,n,r){return lp([n],[...r.map(e=>({id:e.id,type:e.type,req_type:e.data?.req_type,mitigates:e.data?.relationships?.mitigates})),...await op(e,t)]).get(n.id)??[]}function dp(e,t,n,r){return(e?.asil!==n||e?.asil_source!==t)&&(r||e?.asil_source===t)}function up(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function pp(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 mp(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 _p(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 fp(e,t,n){return e.filter(e=>!t.has(e)&&(n.get(e)?.length??0)>0).length}var hp,yp=V({"src/core/coverage-mitigation.ts"(){xr(),cl(),Hd(),Bu="id, type, updated_at, content_changed_at, req_type:data->>req_type, mitigates:data->relationships->mitigates",Ju="id, type, title, req_type:data->req_type, relationships:data->relationships, tags:data->tags, status:data->status",Gu=3,Qu=0,Ku=[],Yu=["severity","exposure","controllability"],Zu="role, control_type and override apply to action add only; omit them to remove a link.",Xu="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.",ep="coverage.covered and coverage.percent count a requirement's own linked test cases. coverage.via_mitigation counts the requirements with no test case of their own that are hazard, failure mode or risk rows with at least one live mitigating requirement, which the app reads as covered through its mitigation; it is not part of covered or percent."}});async function gp(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 wp(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}var vp,bp,jp=V({"src/core/document-closures.ts"(){hp="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."}});function kp(e,t){return t>0?Math.round(e/t*1e3)/10:vp}var Sp,Ap,$p=V({"src/core/project-summary.ts"(){tp(),vp=100,bp="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 Ip(e,t){const n=Ap.find(t=>t.type===e);return n?t?n.lane:n.incoming:void 0}function xp(e){const t={};for(const n of Ap){const r=e[n.lane]??[];(n.always||r.length>0)&&(t[n.lane]=r)}return t}function qp(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 Sp){const a=e[n];if(Array.isArray(a))for(const e of a)"string"==typeof e&&i(t.id,e,r)}}return a}var Op,Ep,Rp,Mp,Tp,Cp=V({"src/core/relationship-sync.ts"(){Sp=[["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"]],Ap=[{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 Dp(e){const t=e?.trim();return t?`Release ${t}`:Op}function Hp(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 Np(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 Ep;const a=Hp(n);return a?{releaseId:a.id,label:Dp(a.release_version)}:Ep}catch{return Ep}}async function Fp(e,t,n,r){return Hn([...new Set(n)],n=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:r,p_requirement_ids:n}))}async function Pp(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 Np(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 Rn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verified_by").in("to_id",o),vn),...await Rn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type","verifies").in("from_id",o),vn)];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 Rp(t?.verifies))c.add(e)}i.push(...await Rn(()=>e.rpc("tcm_requirements_for_test_cases",{p_project_id:t,p_test_case_ids:o,p_requirement_ids:[...c]}),wn))}const o=new Set(i.map(e=>e.id)),l=new Set(n),c=qp([...a,...i.map(e=>({id:e.id,data:{relationships:{verified_by:Rp(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 Fp(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 zp(e,t){const n=e?.flags.get(t);return void 0!==n&&e?.scope?{needs_rerun:n,rerun_scope:e.scope.label}:{}}var Up,Lp,Wp,Vp=V({"src/core/rerun.ts"(){xr(),Cp(),Ep={releaseId:null,label:Op="All runs"},Rp=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],Mp="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.",Tp='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 Bp(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 Jp(e){const t=["requirement","test-case","note","table"];return"items"===e?[...t,"function"]:t}function Gp(e){return"items"===e?null:"unknown"===e?{status:"error",message:Wp,next_steps:["Send the same call again in a moment"],code:"function_mode_unreadable",retryable:!0}:{status:"error",message:Up,next_steps:Lp,code:"function_items_off",retryable:!1}}var Qp,Kp,Yp,Zp,Xp,em,tm,nm,rm,am,im,sm=V({"src/core/function-mode.ts"(){Up="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.",Lp=["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"],Wp="The project's Function setting could not be read just now. Nothing was written. Send the same call again in a moment."}});function om(e){return(e??"").trim().toLowerCase()}function lm(e){const t=e.analysis_props;return t&&"object"==typeof t?t:{}}function cm(e){return"string"==typeof e?e:""}function dm(e,t,n,r){const a=lm(e),i=cm(a.source_function),s={id:null,title:null,label:i,state:"legacy-text"};if(!t||!Qp.has(t))return s;let o=cm(a.source_function_id).trim();if(!o){const e=om(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 um(e,t,n,r){const a=dm(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 pm(e,t){const n=em[e]?.[t]??`Create a Function with ${Kp}.`;return`${t} was removed in ATOMS MCP ${Yp}, with no deprecation period. ${n} Nothing was written.`}function mm(e,t){const n=function(e,t){const n=em[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=>pm(e,t)).join(" ")}`,next_steps:[`Create a Function with ${Kp}, 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 _m(e){return(t,n)=>{if("unrecognized_keys"===t.code){const n=em[e]??{},r=(t.keys??[]).filter(e=>e in n);if(r.length>0)return{message:r.map(t=>pm(e,t)).join(" ")}}return{message:n.defaultError}}}function fm(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 hm(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 ${Kp}`],code:"function_id_invalid",retryable:!1,invalid_function_ids:e.map(e=>e.id)}}function ym(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 gm(e,t,n){return wm(e,t,n,await Bp(e,t))}async function wm(e,t,n,r){const a=Gp(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:ym(n)};const i=fm(n);if(0===i.length)return{ok:!0,functions:[]};const s=await vm(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:hm(o)}:{ok:!0,functions:l}}async function vm(e,t,n){const r=new Map;if(0===n.length)return r;const{data:a,error:i}=await e.from("items").select("id, type, title, deleted_at, content_changed_at, updated_at").eq("project_id",t).in("id",[...n]);if(i)throw new Error(`Function read failed: ${i.message??"unknown error"}`);for(const e of Array.isArray(a)?a:[])r.set(e.id,e);return r}function bm(e){return e.functionId?{source_function:e.text,source_function_id:e.functionId}:{source_function:e.text}}function jm(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 km(e){return!!e&&Qp.has(e)}async function Sm(e,t,n){if(km(e)){if(!t.includes("source_function"))return null;const r=`source_function was removed in ATOMS MCP ${Yp}, 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 ${Kp}). 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(Zp)?"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 Am(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 $m(e){return e?bm(e):{source_function:null}}function Im(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 xm,qm,Om=V({"src/core/functions.ts"(){si(),sm(),xr(),Qp=new Set(["hara_iso26262","hazard_iso14971"]),Yp="0.62.0",Zp="source_function_id",em={atoms_update_domain:{is_function:`A function is no longer a flagged domain tag: it is an item. Create one with ${Kp="atoms_create_item type 'function'"}, on a project with Function items turned on. ${Xp="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 ${Kp}); seed a security risk analysis with source_assets, its asset names. ${Xp}`},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 ${Kp}). ${Xp}`},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 ${Kp}). 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.`}},tm="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.",nm=["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"],rm='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.',am=["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"],im=50}});function Em(e){return e?xm.indexOf(e):-1}function Rm(e,t){const n=e?.[t];return"string"==typeof n?[n]:Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}function Mm(e){return[...Rm(e,"event_hazard"),...Rm(e,"event_goal")]}function Tm(e){const t=e.analysis_props;return"requirement"===e.type&&!!t&&"object"==typeof t}function Cm(e){return!!e&&!e.deleted_at}var Dm,Hm,Nm,Fm,Pm,zm,Um,Lm,Wm,Vm,Bm,Jm,Gm,Qm,Km,Ym,Zm,Xm,e_,t_,n_=V({"src/core/safety-index.ts"(){cl(),yp(),Om(),xm=["QM","A","B","C","D"],qm=new WeakMap}});function r_(e){return"safety_goal"===e?"goal":e}function a_(e){return"hazard"===e||"goal"===e}async function i_(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=ao(n),i="automotive"===(a??"automotive")&&await ki(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 s_(e){if(!e)return{status:"error",message:Jm,next_steps:["Send the same call again in a moment"],code:"hazard_goal_unreadable",retryable:!0};const t=Si(e);return null===t?null:t===wi?Di():Ti()}async function o_(e,t){return s_(await i_(e,t))}function l_(e){const t={},n={};for(const[r,a]of Object.entries(e??{})){const e=Qm[r];if(!e){n[r]=a;continue}if("string"!=typeof a)return{picks:{},rest:{},error:`${r} must be the id of a ${"goal"===Km[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 c_(e){return Object.keys(e).length>0}function d_(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=vs[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 ${Qs[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 u_(e,t,n){const r=Km[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`${Zm[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 p_(e,t,n,r={}){for(const a of["event_hazard","event_goal"]){const i=Ym[a];if(!n.includes(i))continue;const s=void 0!==r[a]?r[a]:Rm(t,a)[0]??null;if(!s)continue;const o="goal"===Km[a]?"Safety goal":"Hazard";return`${e} names its ${o} as an item (${s}), so its ${i} text is read-only. Pick another ${o} with ${Zm[a]}, or change the item itself with atoms_update_item. Nothing was written.`}return null}function m_(e,t){const n=[];for(const r of["event_hazard","event_goal"]){if(void 0===t[r])continue;const a=Rm(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 __(e,t,n,r,a,i,s,o){if(!c_(i))return null;if(!a)return{kind:"validation",message:d_(n,r)};const l=m_(s,i).filter(e=>"add"===e.kind);if(0===l.length)return null;const c=s_(await i_(e,t));if(c)return{kind:"tool",error:c};for(const e of l){const t=u_(e.path[1],e.value,await o(e.value));if(t)return{kind:"validation",message:t}}return null}function f_(e,t){const n={};for(const r of["event_hazard","event_goal"])void 0!==t[r]?n[Zm[r]]=t[r]??null:Rm(e,r).length>0&&(n[Zm[r]]=Rm(e,r)[0]);return n}function h_(e){return e.filter(e=>Xm.has(e.trim().toLowerCase().replace(/[\s-]+/g,"_")))}function y_(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 g_(e,t){const n=Qs[e];return"hara_iso26262"===e&&"hazard_goal"===t?{...n,row:e_}:n}function w_(e,t){return"hara_iso26262"===e&&"hazard_goal"===jo(t)}function v_(e){return{event_label:e_,display_id:(t=e,/^SG-/.test(t)?`Event ${t}`:t)};var t}function b_(e){return"requirement"===e.type&&e.data?.req_type===t_}function j_(e,t){if(!b_(e)||"analysis"!==t?.type)return!1;const n=t.data??null,r=n?.analysis_props?.variant;return w_(io("dfmea"===n?.analysis?.subtype?"dfmea":"hara","string"==typeof r?r:null,null),{analysis_props:n?.analysis_props})}function k_(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 S_(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 A_(e){const t=S_(e);return function(e,t){const n=qm.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=>Cm(n.get(e)),a=e=>r(e)&&"goal"===n.get(e)?.type,i=new Map,s=new Map;for(const t of e){if(!Tm(t))continue;const e=Rm(t.relationships,"event_goal")[0],r=e?n.get(e):void 0;!e||r&&"goal"!==r.type||i.set(t.id,e);const a=Rm(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 Rm(i.relationships,r)){const t=n.get(e);t&&Tm(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=>Ro(n.get(e)?.analysis_props),p=e=>{let t=-1;for(const n of e)t=Math.max(t,Em(u(n)));return t<0?"QM":xm[t]},m=new Set;for(const t of e)if(Cm(t))if("test-case"===t.type)for(const e of Rm(t.relationships,"verifies"))m.add(e);else for(const e of Rm(t.relationships,"verified_by")){const r=n.get(e);Cm(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=dm(e,"hara_iso26262",_);"live"===a.state&&a.id&&t.add(a.id)}return[...t].sort()},h=t=>e.filter(e=>e.type===t&&Cm(e)).map(e=>e.id).sort(),y=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:y,goalCoverage:(e,n)=>{const i=y(e),s=a(e)?c.get(e)??[]:[],o=n?s.filter(e=>n.includes(e)):s,l=new Set(i),d=new Set,p=[],_=[];for(const e of o){const n=(t.byRow.get(e)??[]).filter(r);for(const e of n)l.has(e)||d.add(e);Em(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:[...d].sort(),uncoveredRows:p,untestedRows:_}},directMitigators:e=>[...t.byRow.get(e)??[]],rowMitigated:e=>{if((t.byRow.get(e)??[]).length>0)return!0;const n=i.get(e);return!!n&&y(n).length>0},requirementVerified:e=>m.has(e),hazardFunctions:e=>f(d.get(e)??[]),goalFunctions:e=>f(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 qm.set(e,{links:t,index:r}),r}(t,function(e){const t=[],n=[];for(const r of e)if(Cm(r)){t.push({id:r.id,type:r.type,data:{req_type:r.req_type,analysis_props:r.analysis_props}});for(const e of Rm(r.relationships,"mitigated_by"))n.push({from_id:r.id,to_id:e,type:"mitigated_by"});for(const e of Rm(r.relationships,"mitigates"))n.push({from_id:r.id,to_id:e,type:"mitigates"})}return{byRow:ap(t,n)}}(t))}async function $_(e,t){return await Rn(()=>e.from("items").select("id, title, type, data").eq("project_id",t).is("deleted_at",null),wn)}async function I_(e,t,n,r){const a=Rm(n,"event_goal")[0];if(!a)return[];const i=await r(a);if(!i||"goal"!==i.type)return[];const s=[];for(const e of Rm(i.data?.relationships,"mitigated_by")){const t=await r(e);t&&s.push(t)}const o=await op(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 Rm({mitigates:e.mitigates},"mitigates"))c.push({from_id:e.id,to_id:t,type:"mitigates"})}const u=[];for(const e of ap(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 x_,q_,O_,E_,R_,M_,T_,C_,D_,H_,N_=V({"src/core/hazard-goal-tools.ts"(){Oi(),cl(),ro(),Wi(),n_(),xr(),yp(),Hm=["requirement","test-case","note","function","hazard","goal","safety_goal"],Nm=`Item type. function only where Function items are on. ${Dm="hazard and goal: ISO 26262 (automotive) projects only; in a medical device project hazards are rows of the ISO 14971 risk analysis"}. safety_goal is another name for goal (a Safety goal item, SG-n); a hazard is HAZ-n.`,Fm="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.",Pm="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.",zm='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.',Um='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.',Lm="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.",Wm="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.",Vm='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. 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.',Bm=["requirement","test-case","note","table","analysis","function","hazard","goal"],Jm="Could not read whether this project takes Hazard and Safety goal items, so nothing was written. Send the same call again in a moment.",Gm=["event_hazard","hazard_events","event_goal","goal_events"],Qm={hazard_id:"event_hazard",goal_id:"event_goal"},Km={event_hazard:"hazard",event_goal:"goal"},Ym={event_hazard:"hazard",event_goal:"safety_goal"},Zm={event_hazard:"hazard_id",event_goal:"goal_id"},Xm=new Set(["safe_state","ftti"]),e_="Hazardous event",t_="safety-goal"}});function F_(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 P_(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 z_(e,t){const n=es(e.data);return j_(e,n?t.get(n):void 0)?v_(e.id):{}}function U_(e){return Math.min(Math.max(e??5,1),10)}var L_,W_,V_,B_,J_,G_,Q_,K_=V({"src/core/trace-graph.ts"(){ro(),Rl(),N_(),x_=200,q_=new Set(["parent","verifies","mitigated_by","allocated_to","event_hazard","goal_events"]),O_=new Set(["child","verified_by","mitigates","allocated_from","hazard_events","event_goal"]),E_=["allocated_to","allocated_from"],R_={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"},M_=["parent","verifies","mitigated_by","traces_to","allocated_to","decomposed_from","event_hazard","goal_events"],T_=["child","verified_by","mitigates","allocated_from","decomposes_to","traced_by","hazard_events","event_goal"],C_={...R_,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"},D_="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.",H_="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 Y_(e){return"string"!=typeof e||""===e.trim()||W_.has(e)?null:e}function Z_(e){return!e||"object"!=typeof e||Array.isArray(e)?null:Y_(e.reason)}function X_(e){return"string"==typeof e&&""!==e.trim()?e:null}function ef(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 tf(e){return e.diff_summary&&"object"==typeof e.diff_summary?e.diff_summary:{}}function nf(e,t){const n=tf(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&&Q_.has(n)?n:"mcp_claude"}return"user"}function rf(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}(ef(i?.fields_snapshot),ef(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=X_(t.from_tag),r=X_(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?B_:"hazard_goal_model_revert"===t.kind?J_:X_(e.history)??V_}(r.diff_summary),d=Z_(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":nf(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=tf(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=>!G_.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)),_=(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 af(e,t,n){return{total_count:Math.max(e,Math.min(n,t)),limit:t,offset:0,has_more:n>t}}var sf,of=V({"src/core/history.ts"(){L_="Change rationale, shown with the change in atoms_get_history and on its History line in the app",W_=new Set(["item_deleted","endpoint_deleted","endpoint_restored","endpoint_removed_by_change"]),V_="Changed by a data migration run",B_="Moved to the Hazard and Safety goal model by conversion",J_="Moved back from the Hazard and Safety goal model by revert",G_=new Set(["trash_item","restore_item"]),Q_=new Set(["mcp_claude","mcp_cursor","mcp_copilot"])}});function lf(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 cf=V({"src/core/tool-descriptions.ts"(){tp(),yp(),jp(),$p(),Vp(),K_(),of(),ee(),N_(),sf={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${lf("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? } }\n\n${Mp}\n\nExamples:\n - "Show me all requirements" → atoms_list_items(project_id, type="requirement")\n - "What test cases exist?" → atoms_list_items(project_id, type="test-case")\n\nErrors:\n - "Project not found" → verify project_id\n - "Access denied" → check org membership`,atoms_get_item:`Get full details of a single item including relationships, test history, and ownership.\n\nUse after atoms_list_items or atoms_search to drill into a specific item.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID (e.g., "REQ-001", "TC-050")\n - baseline_id (string, UUID, optional): return the item as it was at that baseline\n - as_of (string ISO 8601, optional): return the item as it was at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\n${Mp}\n\n${yu}\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. ${T}\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${Vm}`,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${lf("uncovered_items")}\n\n${Xu}\n\n${hp}\n\nExamples:\n - "What's our test coverage?" → atoms_get_coverage(project_id)\n - "Safety coverage gaps?" → atoms_get_coverage(project_id, domain="Safety")\n - "Coverage at PDR submission" → atoms_get_coverage(project_id, baseline_id="...")`,atoms_get_history:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_<client>) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",atoms_export_mermaid:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Shows parent-child relationships\nand requirement-to-test-case verification links.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive pan/zoom diagram.\nFalls back to Mermaid text for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to visualize\n - root_item_id (string, optional): Start node (default: all roots)\n - depth (number, optional): Max depth (default 3, max 10)\n - include_tests (boolean, optional): Show test case links (default true)\n - baseline_id (string, UUID, optional): render the graph at that baseline's moment\n - as_of (string ISO 8601, optional): render the graph at that moment\n baseline_id and as_of are mutually exclusive.\n\nReturns:\n { mermaid: string, node_count, edge_count }",atoms_create_item:`Create a new requirement, test case, 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: ${Dm}. 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. ${C} ${P}`,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 - ${bu}\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). ${hu}\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): ${L_}\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: ${T}\nidempotency_key: ${C}\n${P}`,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: ${Dm}\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\nReturns:\n { created: number, items: [{ id, title, type }], errors: [] }\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.\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. ${C} ${P}`,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: ${su}\n\n${du}\n\n${uu}\n\n${cu}\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${du}\n\n${uu}\n\n${cu}\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${H_}\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${lf("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 }",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${Tp}\n\n${ep}\n\n${bp}\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 } }\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${D_}\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${lf("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)",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 } }",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). A project\n with no industry set counts as automotive, as in the app. A variant the industry does not\n offer, an alias counting as the variant it implies, is refused before anything is written,\n naming the industry and what it offers. Analyses already in the project keep working\n whatever their variant. One exception: a project that counts as automotive but already\n holds a live medical device analysis (its industry was never chosen) is not limited and can\n keep creating the medical device analyses. A medical device project is always limited.\n Name none and the default follows the project's industry: automotive gives hara iso26262 and\n dfmea design, medical device gives hara iso14971 and dfmea process. The variant is stored on\n the analysis and selects its scheme for every later read and write; the setting never\n changes an analysis that already exists.\n - title (string, optional): Analysis title (default "New <parent label>": "New HARA",\n "New Risk analysis", "New DFMEA", "New PFMEA", "New Software FMEA", "New Use FMEA")\n - source_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${zm}`,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${zm}`,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${lf("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${Um}`,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${zm}`,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) }\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${Wm}`,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${Lm}`}}});async function df(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 uf(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 pf(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 mf(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=uf(e.requirement_id,n);if(t){for(const t of pf(e.state,!0===e.stale))a[t]-=1;for(const e of pf(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 _f,ff,hf,yf,gf=V({"src/core/accepted-failures.ts"(){}});function wf(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 vf(e,t){const n=t?` in Release ${t}`:"";if(e.failed>0)return{id:e.id,action:"failed",reason:t?`Failed${n}`:"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 bf(e,t){try{const{data:n,error:r}=await e.rpc("rollout_state",{p_project_id:t});return!r&&!0===n?.[_f]}catch{return!1}}async function jf(e,t){const n=await Rn(()=>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),wn),r=await Rn(()=>e.from("items").select("id, verifies:data->relationships->verifies").eq("project_id",t).eq("type","test-case").is("deleted_at",null),wn),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 hf(e.verified_by))s(e.id,t);for(const e of r)for(const t of hf(e.verifies))o.has(t)&&s(t,e.id);return{requirements:n,testsOf:i}}async function kf(e,t,n){const{requirements:r,testsOf:a}=await jf(e,t),i=new Set(r.map(e=>e.id)),s=[...new Set([...a.values()].flatMap(e=>[...e]))].sort(),o=await Hn(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 Fp(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 Rn(()=>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 df(e,t,n.releaseId):null,p=await gp(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=[],c=new Set;for(const t of[...r].sort()){if(a.has(t)||o(t))continue;const r=vf(n.get(t),e.releaseVersion);r&&(l.push(r),c.add(t))}let d=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(wf))],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&&(d+=1,0===e.length&&(o||a.length>0&&a.every(e=>!c.has(e)))&&(u+=1))}return{items:l.sort(ff),requirementsTotal:d,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&&xd.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:c.get(e.tc_id)??[],changedAfterPass:!0===e.changed_after_pass})),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 Sf(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=Hp(n);return a?{id:a.id,release_version:a.release_version??null,release_status:a.release_status??null}:null}catch{return null}}async function Af(e,t,n){if(!await bf(e,t))return{};const r=n?{releaseId:n.id,releaseVersion:n.release_version}:await async function(e,t){const n=await Sf(e,t);return n?{releaseId:n.id,releaseVersion:String(n.release_version??"")}:{releaseId:null,releaseVersion:null}}(e,t);return{needs_attention:(a=await kf(e,t,r),a.items.map(e=>({id:e.id,action:e.action,reason:e.reason})))};var a}var $f,If,xf,qf,Of,Ef,Rf,Mf,Tf,Cf,Df,Hf,Nf,Ff,Pf,zf,Uf,Lf,Wf,Vf=V({"src/core/needs-attention.ts"(){xr(),Hd(),Vp(),gf(),jp(),_f="needs_attention",ff=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,hf=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):"string"==typeof e?[e]:[],yf="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 Bf(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 Jf(e){if(!e)return"";const t=Date.parse(e);return Number.isNaN(t)?String(e):new Date(t).toISOString().slice(0,10)}function Gf(e){return String(e??"").replace(/\s+/g," ").trim()}function Qf(e,t){return`Tested in ${e}: ${t.map(e=>`${e.id} passed${e.build?`, Build ${Gf(e.build)}`:""}`).join("; ")}`}function Kf(e){return`Unchanged since run ${e.test_case_id?`${e.test_case_id} (${Jf(e.run_at)})`:`of ${Jf(e.run_at)}`} on ${e.version}, Build ${e.build?Gf(e.build):"(none)"}`}function Yf(e){return`Closed by document "${Gf(e.document_name)}" (${e.link?`link ${Gf(e.link)}, `:""}closed by ${Gf(e.closed_by)} on ${Bf(e.closed_at)})`}function Zf(e){const t=Gf(e.reason),n=e.link?`${t.replace(/\.$/,"")}. Bug: ${Gf(e.link)}`:t;return`${e.label}. Reason: ${n} (accepted by ${Gf(e.accepted_by)} on ${Bf(e.accepted_at)})`}function Xf(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: ${Gf(e.project_name)}`,""];a.push(`- **Release:** ${r} (snapshot "${Gf(e.release_name)}")`),a.push(`- **Project:** ${Gf(e.project_name)}`),a.push(`- **Generated:** ${Bf(e.generated_at)}`),a.push(`- **Status:** ${function(e){return`Final, stored ${Bf(e.stored_at)} (server time). SHA-256 of the stored report: ${e.sha256}`}(t)}`);for(const t of e.notes)a.push("",`_Note: ${Gf(t)}_`);a.push("",`## ${xf[0]} (${n.verified})`),a.push("",`### Tested in this Release (${e.verified.tested.length})`,""),0===e.verified.tested.length&&a.push(Rf);for(const t of e.verified.tested)a.push(Ef(t.id,t.title,Qf(r,t.tests)));a.push("",`### Verified in an earlier Release (${e.verified.earlier.length})`,""),0===e.verified.earlier.length&&a.push(Rf);for(const t of e.verified.earlier)a.push(Ef(t.id,t.title,Kf(t)));a.push("",`### Closed by document (${e.verified.documents.length})`,""),0===e.verified.documents.length&&a.push(Rf);for(const t of e.verified.documents)a.push(Ef(t.id,t.title,Yf(t)));a.push("",`## ${xf[1]} (${n.anomalies})`,""),0===e.known_anomalies.tests.length&&a.push(Rf);for(const t of e.known_anomalies.tests)a.push(Ef(t.test_case_id,t.title,Zf(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(Ef(t.id,t.title,t.label))}a.push("",`## ${xf[2]} (${n.notDone})`),a.push("",`### Requirements (${e.not_done.requirements.length})`,""),0===e.not_done.requirements.length&&a.push(Rf);for(const t of e.not_done.requirements)a.push(Ef(t.id,t.title,`${t.mark}. ${Gf(t.reason)}`));a.push("",`### Tests (${e.not_done.tests.length})`,""),0===e.not_done.tests.length&&a.push(Rf);for(const t of e.not_done.tests)a.push(Ef(t.id,t.title,`${t.mark}. ${Gf(t.reason)}`));return a.push("",`## ${xf[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"):Of),a.push("","---","",qf),a.join("\n")}async function eh(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?.[$f]?{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:Mf(i.release_version)?i.release_version:null,release_status:Mf(i.release_status)?i.release_status:null,regression_note:Mf(i.regression_note)?i.regression_note:null,final_report:i.final_report??null,final_report_sha256:Mf(i.final_report_sha256)?i.final_report_sha256:null,final_report_at:Mf(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(!Df(e)||e.format!==If)return null;const{verified:t,known_anomalies:n,not_done:r}=e;return Mf(e.release_id)&&Mf(e.release_version)&&Mf(e.release_name)&&Mf(e.project_name)&&Mf(e.generated_at)&&Df(t)&&Cf(t.tested,Nf)&&Cf(t.earlier,Ff)&&Cf(t.documents,Pf)&&Df(n)&&Cf(n.tests,zf)&&Cf(n.requirements,Uf)&&Df(r)&&Cf(r.requirements,Lf)&&Cf(r.tests,Lf)&&Tf(e.regression_note)&&Cf(e.notes,Mf)?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:Xf(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 th,nh=V({"src/core/release-report.ts"(){$f="release_report",If=1,xf=["1. Verified","2. Known anomalies","3. Not done","4. Regression note"],qf="ATOMS records names and server times. This is not a Part 11 signature.",Of="No Regression note was written when this Release was promoted.",Ef=(e,t,n)=>`- ${Gf(`${e} ${t}`)}: ${n}`,Rf="_None._",Mf=e=>"string"==typeof e,Tf=e=>null===e||"string"==typeof e,Cf=(e,t)=>Array.isArray(e)&&e.every(t),Df=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Hf=e=>Df(e)&&Mf(e.id)&&Tf(e.build)&&Tf(e.run_at),Nf=e=>Df(e)&&Mf(e.id)&&Mf(e.title)&&Cf(e.tests,Hf),Ff=e=>Df(e)&&Mf(e.id)&&Mf(e.title)&&Tf(e.test_case_id)&&Mf(e.version)&&Tf(e.build)&&Mf(e.run_at)&&Tf(e.tester),Pf=e=>Df(e)&&Mf(e.id)&&Mf(e.title)&&Mf(e.document_name)&&Tf(e.link)&&Mf(e.closed_by)&&Mf(e.closed_at),zf=e=>Df(e)&&Mf(e.test_case_id)&&Mf(e.title)&&Mf(e.label)&&Mf(e.reason)&&Tf(e.link)&&Mf(e.accepted_by)&&Mf(e.accepted_at),Uf=e=>Df(e)&&Mf(e.id)&&Mf(e.title)&&Mf(e.label),Lf=e=>Df(e)&&Mf(e.id)&&Mf(e.title)&&Mf(e.mark)&&Mf(e.reason),Wf="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."}});var rh=V({"src/apps/register.ts"(){th={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});function ah(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString().replace(/Z$/,"999Z")}var ih=V({"src/core/as-of.ts"(){}});async function sh(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 oh(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&&qn(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 On;const a=void 0===r?.total;let i=e.from("items").select("*",a?{count:"exact"}:void 0).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0}).order("id",{ascending:!0});r&&(i=i.or(function(e){return Tn(xn,e)}(r))),n.type&&(i=i.eq("type",n.type)),n.domain&&(i=i.filter("data->tags->>domains","ilike",yn(n.domain))),n.level&&(i=i.filter("data->tags->>level","ilike",hn(n.level))),i=r?i.range(0,n.limit):i.range(n.offset,n.offset+n.limit);const{data:s,error:o,count:l}=await gn(i);if(o)throw new Error(o.message);const c=s??[],d=c.slice(0,n.limit),u=c.length>n.limit,p=r?.total??l??0,m=r&&a?void 0:p;return{items:d,totalCount:p,hasMore:u,nextCursor:u?Nn(d[d.length-1],m):void 0,cursorTotal:m}}async function lh(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 ch(e,t){if(t.baseline_id&&t.as_of)throw new Zt("baseline_id and as_of are mutually exclusive");if(t.as_of)return Sn(ah(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 Zt("Baseline not found");if(n.project_id!==t.project_id)throw new Zt("Baseline does not belong to this project");return An(t.baseline_id)}return null}async function dh(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 uh(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 ph(e,t,n){return function(e,t,n){return"baselineId"in n?Rn((t,r)=>e.rpc("baseline_state_page",{p_baseline_id:n.baselineId,p_after_id:t?.id??null,p_limit:r}),wn):Cn(e,"project_state_at",t,n.at)}(e,t,n).catch(e=>{throw new Error(`projectStateAt: ${e.message}`)})}async function mh(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 Rn(()=>e.from("test_results").select("id, item_id").eq("project_id",t).eq("asset",n),["id"]);return[...new Set(r.map(e=>e.item_id))]}(e,t,r.asset.trim()):null;if(i&&0===i.length)return{items:[],totalCount:0};const s=()=>{let n=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.${fn(a)},data->>body.ilike.${fn(a)},data->>summary.ilike.${fn(a)}`);return n=void 0===r.offset?n.limit(r.limit):n.order("id",{ascending:!0}).range(r.offset,r.offset+r.limit-1),r.type&&(n=n.eq("type",r.type)),r.domain&&(n=n.filter("data->tags->>domains","ilike",yn(r.domain))),r.level&&(n=n.filter("data->tags->>level","ilike",hn(r.level))),n};if(i)return async function(e,t,n){const r=[];let a=0;for(let t=0;t<e.length;t+=$n){const{data:i,error:s,count:o}=await n(e.slice(t,t+$n));if(s)throw new Error(s.message);a+=o??0,r.push(...i??[])}return{items:r.slice(0,t),totalCount:a}}(i,r.limit,e=>s().in("id",e));const{data:o,error:l,count:c}=await gn(s());if(l)throw new Error(l.message);return{items:o??[],totalCount:c??0}}function _h(e,t,n){return async function(){Qu>=Gu?await new Promise(e=>Ku.push(e)):Qu+=1;try{return await async function(e,t,n){let r,a,i;if(n.moment){const s=(await ph(e,t,n.moment)).map(uh);r=s.filter(e=>"requirement"===e.type),a=s.map(e=>({id:e.id,type:e.type,data:e.data})),i=[]}else a=(await Rn(()=>e.from("items").select(Ju).eq("project_id",t).is("deleted_at",null),wn)).map(sp),r=a.filter(e=>"requirement"===e.type),i=await Rn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t),vn);const s=r.filter(e=>!(n.domain&&!(e.data?.tags?.domains??[]).some(e=>Oo(e)===Oo(n.domain))||n.level&&co(e.data?.tags?.level)!==co(n.level))),o=qp(a,i),l=rp(a,o),c=s.filter(e=>l.has(e.id)),d=s.filter(e=>!l.has(e.id)),u=ip(a,o);return{covered:c,uncovered:d,total:s.length,mitigators:u}}(e,t,n)}finally{const e=Ku.shift();e?e():Qu-=1}}()}var fh=V({"src/db/queries.ts"(){En(),cl(),yp(),xr(),Cp(),ih(),pn()}}),hh={};async function yh(e={}){try{const{projects:t,viewerOrgs:n}=await rd(async()=>{const e=await ed(),t=_e(await pe(e,ad()));return{projects:await sh(e),viewerOrgs:t}}),r=Te(),a=Ce(),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??G).project_scope;return t.filter(e=>n(r,e.id))}return t.filter(t=>{const r="string"==typeof t.org_id?Ae(e,t.org_id):$e(e);return n(r.project_scope,t.id)})}(Qe(),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=$l(i,e.offset,e.limit);return Dc(oc(s.rows,s.meta),{paging:{}})}catch(e){return Hc(xc(e,{read:!0}))}}B(hh,{listProjectsHandler:()=>yh});var gh=V({"src/tools/list-projects.ts"(){md(),je(),fh(),De(),Ze(),Me(),Rl(),zc()}}),wh={};async function vh(e){try{const t=await ed();let n,r,a=null;try{a=await ch(t,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Hc(xc(e,{read:!0}))}let i=null;if(a){const i=(await ph(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=>Oo(t)===Oo(e.domain)))return!1}return!e.level||co(n?.tags?.level)===co(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 oh(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 Pp(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:Fu(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=lc(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)),s?.scope&&(c.rerun_scope=s.scope.label);const d=i?{resume:t=>({meta:{next_cursor:Nn(n[t-1],i?.cursorTotal),...void 0===e.after?{next_offset:e.offset+t}:{}},next:"after=meta.next_cursor"})}:{};return Dc(oc(l,c),{paging:d})}catch(e){return e instanceof On?Hc(_c(e.message)):e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(wh,{listItemsHandler:()=>vh});var bh=V({"src/tools/list-items.ts"(){md(),fh(),zc(),xr(),cl(),tp(),Vp()}});function jh(e,t){return Ha(e,t)}function kh(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 Sh(e,t){if(t&&Fa(e,t))throw kh(t)}async function Ah(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 sd(e)}catch{t=null}return function(e){const t=function(e){const t=Kt(e);return"mcp_cursor"===t?"Cursor":"mcp_copilot"===t?"Copilot":"Claude"}(e.clientName);return{kind:"agent",user_id:e.userId,session_id:e.sessionId,label:za(t,e.name,e.email),client:t}}({userId:ad(),sessionId:qk(),name:t,email:id(),clientName:Ek()})}(e),l=async n=>{const a=function(e,t){return function(e,t,n,r){const a={surface:"mcp",delivery:"npm",package_version:uk,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 kh(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??Ca,n=function(e,t=wr,n=vr){return Ma(Ra(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=Ra(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}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&&Sh("ops",c.error),c}function $h(e){return{...e.chunks?{chunks:e.chunks}:{},...void 0!==e.error?{error:xc(e.error).message}:{}}}function Ih(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 xh(e){const t=e.relooked?[...e.answers]:await Qa(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 ea(e.client,e.projectId,n)),da({answers:t,ops:e.ops,skippedItems:Ih(e.results??[]),openRevisions:r,labels:e.labels})}function qh(e){const t=e.suggestion;return"number"==typeof t?.sg_number?t.sg_number:null}function Oh(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!==qh(e)?{change:{sg_number:qh(e)}}:{}})),r={...e,applied:[...e.applied,...n]},{isError:a,result:i}=va(r,t);return a?Hc(i):Dc(i)}async function Eh(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:ad(),event_type:a,old_data:null,new_data:Ka(n,r,e),actor:Ok(),session_id:qk(),...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 Rh(e){return e&&0!==e.length?"tags"===e[0]?"level"===e[1]?"level":"domains"===e[1]?"domains":"tags":e[0]:null}function Mh(e){return"set"===e.kind?e.path:[...e.path,e.kind,String(e.row_id??Pr(e.value??null))]}function Th(e){return null==e?[]:"string"==typeof e?[e]:[...e]}var Ch,Dh=V({"src/tools/_agent-ops.ts"(){md(),Rk(),si(),zc()}}),Hh={};function Nh(e,t){if(!t)return e;const n={...e};for(const e of Ch){const r=t[e];null!=r&&("evidence_url"===e&&"string"==typeof r&&""===r.trim()||(n[e]=r))}return n}async function Fh(e){try{const r=await ed();let a=null;try{a=await ch(r,{baseline_id:e.baseline_id,as_of:e.as_of,project_id:e.project_id})}catch(e){return Hc(xc(e,{read:!0}))}let i=null;if(!a&&!0===await jh(r,e.project_id)){i={head:await na(r,e.project_id),revision:(await ea(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?uh(e):null):await lh(r,e.project_id,e.item_id);if(!s)return Hc(dc("Item",e.item_id));const o=Object.fromEntries(Ap.map(e=>[e.lane,[]]));if(a){const e=s.data?.relationships??{};for(const t of Object.keys(o)){const n=e[t];Array.isArray(n)&&(o[t]=n.slice())}}else{const t=await async function(e,t,n){const{data:r,error:a}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${n},to_id.eq.${n}`);if(a)throw new Error(a.message);return r??[]}(r,e.project_id,e.item_id),n=(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)}let l=new Set([e.item_id]);const c=Array.from(a);if(c.length>0){const{data:t,error:n}=await r.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",c);if(n)throw new Error(n.message);l=new Set((t??[]).map(e=>e.id)),l.add(e.item_id)}const d=e=>l.has(e);for(const r of t)if(r.from_id===e.item_id){if(!d(r.to_id))continue;n(Ip(r.type,!0),r.to_id)}else{if(!d(r.from_id))continue;n(Ip(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??{},c={};for(const e of Gm){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=(Vu(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)=>$u(String(e.base.run_at),String(t.base.run_at))).slice(0,20).map(e=>Nh(e.base,e.canonical));else{const{data:t,error:n}=await r.from("test_results").select("result, run_by, run_at, note, asset").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);if(!n&&t){const e=new Map;for(const t of s.data?.runs??[])"string"==typeof t?.date&&e.set(t.date,t);d=t.map(t=>Nh(t,e.get(String(t.run_at))))}}const u=i&&function(e){return"requirement"===e.type&&null!==Sd(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 Pp(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:{...xp(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:Fu(s),...zp(p,s.id),...Ad(s,{live:null!==i,since:u}),..."test-case"===s.type?{...Cu(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 _;if(!a&&a_(s.type)){const t=await $_(r,e.project_id),n=A_(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=new Map(n.map(e=>[e.id,e])),a=[...e.rowsOfGoal(t)],i=a.filter(e=>Ro((r.get(e)?.data??{}).analysis_props??null)!==ds),s=[...e.satisfiers(t)],o=e.goalCoverage(t);return{asil:e.goalAsil(t),source_rows:i,events:a,functions:[...e.goalFunctions(t)],satisfied_by:s,verified_satisfiers:s.filter(t=>e.requirementVerified(t)).length,row_mitigators:[...o.rowMitigators],uncovered_rows:[...o.uncoveredRows],untested_rows:[...o.untestedRows]}}(n,s.id,t)}if(_&&Object.assign(m,{safety:_}),a||Object.assign(m,await async function(t){if(!b_(t))return{};const n=es(t.data);return j_(t,n?await(a=n,lh(r,e.project_id,a)):null)?v_(t.id):{};var a}(s)),i){const n=s.data?.steps,a=Array.isArray(n)?n:[],o=(await ra(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 Dc(oc({...m,...i.revision?{base_token:await Qr(i.revision,"item")}:{},seq:i.head,editing_now:o,...l?{presence:l}:{}}))}return Dc(oc(m))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}var t,n}B(Hh,{getItemHandler:()=>Fh});var Ph,zh,Uh=V({"src/tools/get-item.ts"(){Od(),md(),tp(),Vp(),fh(),Cp(),zc(),si(),Dh(),N_(),Ch=["point","release_id","build","environment","tooling","evidence_url","step_results"]}}),Lh={};function Wh(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:aa(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 Vh(e){try{const t=await ed(),n=await jh(t,e.project_id);if(null===n)return Hc(Na());if(!n)return Hc(_c(zh));if(void 0===e.since_seq){const n=await na(t,e.project_id);return Dc(oc({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??Ph});if(a)throw a;const i=r??{},s=(i.changes??[]).map(Wh);return Dc(oc({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 Hc(xc(e,{read:!0}))}}B(Lh,{LIST_CHANGES_DEFAULT_LIMIT:()=>Ph,LIST_CHANGES_NOT_NUMBERED:()=>zh,listChangesHandler:()=>Vh,listedChange:()=>Wh});var Bh=V({"src/tools/list-changes.ts"(){md(),si(),zc(),Dh(),Ph=100,zh="This project does not number its changes yet. Use atoms_get_history for one item."}}),Jh=V({"src/core/snapshot-search.ts"(){}}),Gh={};async function Qh(e){try{const t=await ed();let n,r,a=null;try{a=await ch(t,{baseline_id:e.baseline_id,project_id:e.project_id})}catch(e){return Hc(xc(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 ph(t,e.project_id,a),e.query,{type:e.type,limit:e.limit});r=i.totalCount,n=i.items}else{const a=await mh(t,e.project_id,e.query,{type:e.type,limit:e.limit,asset:e.asset});n=a.items,r=a.totalCount}return Dc(oc(n.map(e=>({id:e.id,title:e.title,type:e.type,status:Fu(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),lc(r,e.limit,0)),{paging:{resume:"none"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(Gh,{searchHandler:()=>Qh});var Kh=V({"src/tools/search.ts"(){md(),fh(),Jh(),zc(),tp()}}),Yh={};async function Zh(e){try{const t=await ed(),{access_token:n}=await Wt(),{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(()=>(Dt(),qt)),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 Dc(oc(r.map(e=>({id:e.id,title:e.title,type:e.type,status:Fu(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),lc(a,e.limit,0)),{paging:{resume:"none"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(Yh,{semanticSearchHandler:()=>Zh});var Xh=V({"src/tools/semantic-search.ts"(){md(),Gt(),fh(),zc(),tp()}}),ey={};async function ty(e){try{if(e.baseline_id&&e.as_of)return Hc(_c("baseline_id and as_of are mutually exclusive"));const t=await ed();let n;if(e.baseline_id){const r=await dh(t,e.baseline_id);if(!r)return Hc(_c("Baseline not found"));if(r.project_id!==e.project_id)return Hc(_c("Baseline does not belong to this project"));n=An(e.baseline_id)}else e.as_of&&(n=Sn(ah(e.as_of)));const r=await _h(t,e.project_id,{domain:e.domain,level:e.level,moment:n}),{total:a,mitigators:i}=r,s=n?null:await gp(t,e.project_id),{covered:o,uncovered:l,coveredByDocument:c}=function(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}}}(r.covered,r.uncovered,s),d=$l(l,e.offset,e.limit),u=d.rows.map(e=>{const t=function(e,t){if(np(e))return[...t?.get(e.id)??[]]}(e,i);return{id:e.id,title:e.title,type:e.type,status:Fu(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,...t?{mitigated_by:t}:{}}});return Dc(oc({covered:o.length,uncovered:l.length,total:a,coverage_percent:kp(o.length,a),covered_via_mitigation:_p(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")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(ey,{getCoverageHandler:()=>ty});var ny,ry,ay=V({"src/tools/get-coverage.ts"(){md(),fh(),ih(),xr(),zc(),tp(),Rl(),$p(),yp(),jp()}}),iy=V({"src/core/accepted-readiness.ts"(){xr(),Vp(),Vf()}}),sy={};async function oy(e,t,n){const r=await Rn(()=>e.from("items").select("id").eq("project_id",t).eq("type","requirement").is("deleted_at",null),wn);return(await Hn(r.map(e=>e.id),r=>e.rpc("tcm_rerun_list",{p_project_id:t,p_release_id:n,p_requirement_ids:r}))).sort(ry)}async function ly(e){try{const t=await ed();let n=null;if(e.release_id){const r=await dh(t,e.release_id);if(!r)return Hc(_c(`Release ${e.release_id} not found`));if(r.project_id!==e.project_id)return Hc(_c("Release does not belong to this project"));if(null===r.release_version)return Hc(cc(`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 Hc(xc(a,{read:!0}));n=r,n||(n=await async function(e,t){return await bf(e,t)?Sf(e,t):null}(t,e.project_id))}const r=await gp(t,e.project_id);if(!n)return Dc(oc({release:null,rerun:await oy(t,e.project_id,null),...r?{document_closures:r}:{},hint:ny,...await Af(t,e.project_id,null),...await eh(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 Hc(xc(i,{read:!0}));const s=n.id,o=await Rn(()=>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(ry),r),c=await df(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 jf(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 Hn(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 Fp(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:mf(wp(a??{},o,r),o,d,new Set((r??[]).map(e=>e.requirement_id))),requirements:l,rerun:await oy(t,e.project_id,s),...await Af(t,e.project_id,n),...c?{accepted_failures:c}:{},...r?{document_closures:r}:{},...await eh(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 Rn(()=>t.rpc("verification_notrun_points",{p_project_id:e.project_id,p_release_id:s}),["tc_id","asset","point_key"])),Dc(oc(u),{complete:!0})}catch(e){return Hc(xc(e,{read:!0}))}}B(sy,{verificationStatusHandler:()=>ly});var cy=V({"src/tools/verification-status.ts"(){md(),fh(),xr(),Vf(),gf(),iy(),jp(),nh(),zc(),ny="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).",ry=(e,t)=>e.requirement_id<t.requirement_id?-1:e.requirement_id>t.requirement_id?1:0}}),dy={};async function uy(e){try{const t=await ed(),{rows:n,total:r}=await async function(e,t,n,r){const{data:a,error:i,count:s}=await 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}).limit(r+1);if(i)throw new Error(i.message);const o=a??[];return{rows:o,total:s??o.length}}(t,e.project_id,e.item_id,e.limit);if(n.length>0){const a=n,i=rf(a,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=tf(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}(t,e.project_id,e.item_id,a),await async function(e,t,n,r){const a=r.filter(e=>null===Z_(e.diff_summary)&&"user"!==nf(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!==Y_(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!==Z_(t.diff_summary)||"user"===nf(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}}(t,e.project_id,e.item_id,a));return Dc(oc(i.slice(0,e.limit),af(r,e.limit,Math.max(n.length,i.length))),{paging:{resume:"none"}})}const{rows:a,total:i}=await async function(e,t,n,r){const{data:a,error:i,count:s}=await e.from("change_history").select("*",{count:"exact"}).eq("item_id",n).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r+1);if(i)throw new Error(i.message);const o=a??[];return{rows:o,total:s??o.length}}(t,e.project_id,e.item_id,e.limit);return Dc(oc(a.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=Y_(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}:{}}}),af(i,e.limit,a.length)),{paging:{resume:"none"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(dy,{getHistoryHandler:()=>uy});var py=V({"src/tools/get-history.ts"(){md(),fh(),of(),zc()}});function my(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 _y(e){return`item_${e.replace(/[^A-Za-z0-9_]/g,"_")||"node"}`}function fy(e){const t=gy(`${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 hy(e){const t=_y(e.from_id),n=_y(e.to_id);return"child"===e.type?`${t} --\x3e ${n}`:"verified_by"===e.type?`${t} -.-> ${n}`:"related"===e.type?`${t} -.- ${n}`:"allocated_to"===e.type?`${t} -- allocated to --\x3e ${n}`:"allocated_from"===e.type?`${n} -- allocated to --\x3e ${t}`:"event_hazard"===e.type?`${t} -- hazard --\x3e ${n}`:"hazard_events"===e.type?`${n} -- hazard --\x3e ${t}`:"event_goal"===e.type?`${t} -- goal --\x3e ${n}`:"goal_events"===e.type?`${n} -- goal --\x3e ${t}`:null}function yy(e){return"allocated_from"===e.type?`${e.to_id}:allocated_to:${e.from_id}`:"hazard_events"===e.type?`${e.to_id}:event_hazard:${e.from_id}`:"goal_events"===e.type?`${e.to_id}:event_goal:${e.from_id}`:`${e.from_id}:${e.type}:${e.to_id}`}function gy(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,70)}var wy=V({"src/core/mermaid.ts"(){}}),vy={};async function by(e){try{if(e.baseline_id&&e.as_of)return Hc(_c("baseline_id and as_of are mutually exclusive"));const t=await ed();let n,r,a;if(e.baseline_id){const r=await dh(t,e.baseline_id);if(!r)return Hc(_c("Baseline not found"));if(r.project_id!==e.project_id)return Hc(_c("Baseline does not belong to this project"));n=An(e.baseline_id)}else e.as_of&&(n=Sn(ah(e.as_of)));if(n){r=(await ph(t,e.project_id,n)).map(uh).map(e=>({id:e.id,title:e.title,type:e.type,data:e.data})),a=qp(r,[])}else r=await Rn(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),wn),a=qp(r,await Rn(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),vn));return Dc(oc(function(e){const t=e.items,n=(e.relationships??[]).map(my),r=Math.max(0,e.depth);if(0===t.length)return{mermaid:`graph TD\n empty[${gy(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(` ${_y(t)}${fy(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=hy(c);if(!u)continue;const p=yy(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")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(vy,{exportMermaidHandler:()=>by});var jy,ky,Sy=V({"src/tools/export-mermaid.ts"(){md(),fh(),zc(),wy(),ih(),xr()}}),Ay=V({"src/core/item-types.ts"(){jy={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 $y(e){const t=function(e){return Object.prototype.hasOwnProperty.call(jy,e)?jy[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 Iy(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 xy(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>ky)throw new Error(`ID generation failed: at most ${ky} 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 qy=V({"src/core/item-id-reservation.ts"(){Ay(),ky=1e3}});async function Oy(e,t){const n=await Ha(e,t);return null===n?"unreadable":n?"ops":"main"}function Ey(){return Hc(Na())}async function Ry(e){const t=[...e.ops];let n=e.preFound??new Map;!e.preFound&&e.deterministic&&t.length>0&&(n=await Ga(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 Ah(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 Qa(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,...Da(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 ea(e.client,e.projectId,l)),{outcome:await da({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 My(e,t,n,r){if(0===e.not_applied.length)return Dc(oc({...t,...r??{},...ba(e),...n?.chunks?{chunks:n.chunks}:{}}));const{isError:a,result:i}=va(e,{...r??{},...$h(n??{})});return a?Hc(i):Dc(i)}function Ty(e,t,n){return e&&!t?Fa(e,n):null}function Cy(e){return null==e?[]:(Array.isArray(e)?[...e]:[e]).filter(e=>"string"==typeof e&&e.length>0)}function Dy(e){return e.some(e=>void 0!==e.acceptance_revoked&&null!==e.acceptance_revoked&&!1!==e.acceptance_revoked)}async function Hy(e){const t=await sa({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(ia(t.path));a&&r.push(la({op_id:ka(),kind:"set",item_id:e.itemId,path:[...t.path],value:t.value},a))}return{ops:r,refusals:t.refusals}}async function Ny(e){const t=ad(),n=qk(),r=qa(e.contents),a=[],i=[],s=e.key?await Promise.all(e.contents.map(e=>Wa(e))):e.contents.map(()=>{});for(let s=0;s<e.contents.length;s+=1)a.push(await ja(e.key?Aa({userId:t,projectId:e.projectId,family:xa(e.tool),key:e.key,itemIdOrK:s}):Sa({userId:t,projectId:e.projectId,content:e.contents[s],k:r[s],sessionId:n}))),i.push(await ja(e.key?Aa({userId:t,projectId:e.projectId,family:xa(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 Fy(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 Py(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 ta(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 Qr(t,"all"))}return{tokens:a,unread:!1}}async function zy(e){let t=0,n=0;for(;;){let r;try{r=await Ry({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 Uy(e,t,n){return e.answers.find(e=>e.status===t&&(void 0===n||e.reason===n))}var Ly,Wy,Vy=V({"src/tools/_ops.ts"(){md(),Rk(),si(),zc(),Dh()}});function By(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!!Oe(Qe(),t).require_confirmation_for.includes(e)}function Jy(e,t=Ly){const n=Date.now()+t,r={...e,exp:n},a=Buffer.from(JSON.stringify(r)).toString("base64url");return{token:`${a}.${p.createHmac("sha256",Wy).update(a).digest("base64url")}`,expires_at:new Date(n).toISOString(),expires_in_seconds:Math.round(t/1e3)}}function Gy(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=p.createHmac("sha256",Wy).update(n).digest("base64url"),i=Buffer.from(r,"utf8"),s=Buffer.from(a,"utf8");if(i.length!==s.length||!p.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 Qy(e){if(Array.isArray(e))return e.map(Qy);if(null!==e&&"object"==typeof e){const t={};for(const n of Object.keys(e).sort())t[n]=Qy(e[n]);return t}return e}function Ky(e){const t=JSON.stringify(Qy(e));return p.createHash("sha256").update(t).digest("base64url").slice(0,16)}var Yy,Zy=V({"src/middleware/confirmation.ts"(){Ze(),Me(),Ly=6e4,Wy=(()=>{const e=process.env.ATOMS_MCP_CONFIRMATION_SECRET;return e&&e.length>=16?e:p.randomBytes(32).toString("base64url")})()}});function Xy(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=>co(e)===co(i))??s.find(e=>r(e)===a)??t}function eg(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 tg=V({"src/core/levels.ts"(){cl(),wl(),Yy="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."}}),ng={};function rg(e){const t=sc(e??"");return"sub-system"===t?"subsystem":t}async function ag(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 ig(e,t){return{levels:await ag(e,t)}}async function sg(e,t){return(await Rn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),wn)).map(e=>e.data?.tags?.level)}async function og(e,t,n){const r=sc(n);return r?Xy(n,r,await ag(e,t),rg):r}async function lg(e,t,n){const r=sc(n??""),a=rg(r);if(!r)return"none";try{const{levels:n}=await ig(e,t);if(n.some(e=>rg(e)===a))return"present";if(!ne(Oe(Qe(),t),"atoms_create_level").allowed)return"locked";if(!0===await Ha(e,t)){const n={op_id:ka(),kind:"add",item_id:null,path:["taxonomy","levels"],value:r},{run:a}=await zy({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 cg(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 dg(e){try{const t=await ed(),{levels:n}=await ig(t,e.project_id),r=function(e,t,n){const r=new Set(e.map(e=>co(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(co(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 sg(t,e.project_id),rg),a=r.some(e=>void 0!==e.items_not_shown);return Dc(oc({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?` ${Yy}`:"")}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}async function ug(e,t){let n;try{const r=await ed();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const a=t??await Oy(r,e.project_id);if("unreadable"===a)return Ey();n=a;const{levels:i}=await ig(r,e.project_id),s=sc(e.name),o=rg(s);if(!s)return Hc(_c("Level name cannot be empty."));if(i.some(e=>rg(e)===o))return Hc(_c(`Level "${s}" already exists in this project.`));if("ops"===a){const t={op_id:ka(),kind:"add",item_id:null,path:["taxonomy","levels"],value:s},{run:n}=await zy({client:r,projectId:e.project_id,op:t});if(n.answers.some(e=>"noop"===e.status))return Hc(_c(`Level "${s}" already exists in this project.`));if(n.outcome.not_applied.length>0)return My(n.outcome,{},n);const a=(await ag(r,e.project_id)).findIndex(e=>rg(e)===o),l=`L${a>=0?a:i.length}`;return My(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=>rg(e)===o);if(void 0!==l){const e=`L${a.indexOf(l)}`;return Dc(oc({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 Dc(oc({level:{name:s,prefix:d},message:`Level "${s}" registered as ${d}. Tag items with level="${s}".`}))};return await l()}catch(r){const a=Ty(n,t,r);return a?ug(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}async function pg(e,t){let n;try{const r=await ed();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const a=t??await Oy(r,e.project_id);if("unreadable"===a)return Ey();n=a;const i=rg(Mc(e.name));if(!i)return Hc(_c("Level name cannot be empty."));const{levels:s}=await ig(r,e.project_id),o=s.filter(e=>rg(e)===i),l="ops"===a?0:(await sg(r,e.project_id)).filter(e=>rg(e)===i).length;if(0===o.length&&0===l&&"ops"!==a)return Hc(dc("Level",e.name));const c=o[0]??e.name;if(l>0)return Hc(_c(`Level "${c}" is used by ${l} item${l>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`));if(By("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=Jy(t);return Dc(oc({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=Gy(e.confirmation_token,t);if(!n.valid)return Hc(_c(`confirmation_token rejected: ${n.reason}`))}if("ops"===a){const t={op_id:ka(),kind:"remove",item_id:null,path:["taxonomy","levels"],value:c},{run:n}=await zy({client:r,projectId:e.project_id,op:t}),a=Uy(n,"invalid","level_in_use");if(a){const e="number"==typeof a.count?a.count:1;return Hc(_c(`Level "${c}" is used by ${e} item${e>1?"s":""}. Retag them with atoms_update_item (set a different level) before deleting.`))}if(Uy(n,"deleted"))return Hc(dc("Level",e.name));if(n.outcome.not_applied.length>0)return My(n.outcome,{},n);const i=await ag(r,e.project_id),o=uo(s,i);return My(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=uo(s,a);return Dc(oc({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=Ty(n,t,r);return a?pg(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}async function mg(e,t){let n;try{const r=await ed();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const a=t??await Oy(r,e.project_id);if("unreadable"===a)return Ey();n=a;const i=Array.isArray(e.names)?e.names.map(e=>Mc(String(e??"")).trim()).filter(e=>e.length>0):[];if(0===i.length)return Hc(_c("names must be a non-empty array of the project's existing levels, in the order you want them."));const{levels:s}=await ig(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=>co(t)===co(e))??a(t=>""!==n(t)&&n(t)===n(e));if(null===t)return null;i.push(t)}return i}(s,i,rg);if(!o)return Hc(_c(`names must list every existing level exactly once. Levels: ${s.length>0?s.join(", "):"(none)"}`));if("ops"===a){const t=cg(s,o);if(t.length>0){const n=t.map(e=>({op_id:ka(),kind:"move_row",item_id:null,path:["taxonomy","levels"],row_id:e.level,value:{after:e.after}})),a=await Ry({client:r,projectId:e.project_id,ops:n});if(Uy(a,"deleted"))return Hc(dc("Level",e.names.join(", ")));if(a.outcome.not_applied.length>0)return My(a.outcome,{},a)}const n=await ag(r,e.project_id),a=uo(s,n);return Dc(oc({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=uo(s,a);return Dc(oc({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=Ty(n,t,r);return a?mg(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}B(ng,{createLevelHandler:()=>ug,deleteLevelHandler:()=>pg,ensureLevelRegistered:()=>lg,getProjectLevels:()=>ag,levelKey:()=>rg,levelMoves:()=>cg,listLevelsHandler:()=>dg,reorderLevelsHandler:()=>mg,storedLevelSpelling:()=>og});var _g,fg,hg,yg,gg,wg,vg,bg,jg=V({"src/tools/levels.ts"(){md(),si(),Vy(),Zy(),zc(),cl(),ue(),Me(),Ze(),xr(),tg()}});function kg(e,t,n){const[r,a]="affects"===n?[e,t]:[t,e];return r.startsWith(yg)&&a.startsWith(gg)?null:`affects/affected_by links a security risk analysis row (${yg}n) to an ISO 14971 risk row (${gg}n) only: "${e}" -> "${t}" is not that pair.`}function Sg(e,t,n){const r=[t,n].filter(wg);if(0===r.length)return null;const a=`"${t.id}" -> "${n.id}"`;if(vg(e)){const r=wg(t)?n:t;return wg(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(wg(t)&&wg(n))return null;const r=wg(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 bg(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 Ag(e,t,n,r){return Sg("parent",{id:e,type:t},{id:n,type:r})}async function $g(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 Ig(e,t,n,r){const a=n.filter(e=>"add"===e.action),i=a.filter(e=>vg(e.type)||bg(e.type)||"parent"===e.type||"child"===e.type);if(0===i.length)return null;const s=e=>e.startsWith(_g),o=a.some(e=>vg(e.type));if(!o&&!i.some(e=>s(e.from_id)||s(e.to_id)))return null;if(o){const n=Gp(await Bp(e,t));if(n)return{toolError:n}}const l=await async function(e,t,n,r){const a=n.filter(e=>"add"===e.action&&(vg(e.type)||bg(e.type)||"parent"===e.type||"child"===e.type));if(0===a.length)return null;const i=await $g(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=Sg(e.type,t,n);if(r)return r}return null}(e,t,n,r);return l?{validation:l}:null}var xg=V({"src/core/link-pairs.ts"(){sm(),cl(),_g="FN-",fg=["allocated_to","allocated_from"],hg=["verifies","verified_by","mitigated_by","mitigates","affects","affected_by"],yg=`${Os.security_tir57}-`,gg=`${Os.hazard_iso14971}-`,wg=e=>"function"===e.type,vg=e=>fg.includes(e),bg=e=>hg.includes(e)}});async function qg(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 Rn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),wn);for(const e of i){const t=e.data?.fields;if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,n]of Object.entries(t)){const t=a.get(e.toLowerCase());t&&"string"==typeof n&&n.length>0&&(r[t]+=1)}}return r}var Og,Eg,Rg,Mg,Tg=V({"src/core/project-field-counts.ts"(){xr()}});function Cg(e){if(!Array.isArray(e))return;const t=new Set(e.filter(e=>"string"==typeof e&&Rg.has(e)));return 0!==t.size?Og.filter(e=>t.has(e)):void 0}var Dg,Hg,Ng,Fg=V({"src/core/field-scope.ts"(){Og=["requirement","test-case","note","table","function"],Eg=["requirement","test-case","note","table"],Rg=new Set(Og),Mg=e=>JSON.stringify({type:e.type,options:e.options??[],appliesTo:e.appliesTo??null})}}),Pg={};async function zg(e,t){const{data:n,error:r}=await e.from("metadata").select("fields").eq("project_id",t).maybeSingle();if(r)throw r;return Ug(n?.fields)}function Ug(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&&Hg.has(e.type)?e.type:"text",o=Array.isArray(e.options)?Xg(e.options):[],l=Cg(e.appliesTo??e.applies_to);t.push({name:a,type:s,..."select"===s?{options:o}:{},...l?{appliesTo:l}:{}})}return t}function Lg(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(!Hg.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=Xg(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 Wg(e,t){const n=new Set(e.map(e=>e.name.toLowerCase()));return Object.keys(t).filter(e=>!n.has(e.toLowerCase()))}function Vg(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 Bg(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 Jg(e,t,n=new Set,r){const a=Wg(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(Bg(r,e,a)){a.trim()&&(i[t.name]=a);continue}const o=Kg(t,a,n);if(o.error)return{error:o.error};o.value&&(i[t.name]=o.value)}return{fields:i}}function Gg(e){return/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function Qg(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 Kg(e,t,n){const r=t.trim();if(!r)return{value:""};if(r.length>Ng)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 Zg(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 Gg(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>Ng?{error:`${e.name} is too long.`}:{value:n}}}}async function Yg(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(Bg(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(!Zg(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:ad()});if(i)return{error:i.message};!0===a&&o.add(n)}return Jg(n,r,o,a)}function Zg(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 Xg(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 ew(e){try{const t=await ed(),n=await zg(t,e.project_id),r=await qg(t,e.project_id,n),a=$l(n,e.offset,e.limit);return Dc(oc({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")?Hc(fc()):Hc(xc(e,{read:!0}))}}async function tw(e,t){let n;try{const r=await ed();try{await dd(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Hc(cn("project"));throw e}const a=t??await Oy(r,e.project_id);if("unreadable"===a)return Ey();n=a;const{data:i}=await r.from("metadata").select("fields").eq("project_id",e.project_id).maybeSingle(),s=Ug(i?.fields),o=Cg(e.appliesTo),l={name:e.name.trim(),type:e.type??"text",..."select"===e.type?{options:Xg(e.options??[])}:{},...o?{appliesTo:o}:{}},c=Lg(l,function(e,t,n){if(!n)return e;const r=t.name.toLowerCase();return e.some(e=>e.name.toLowerCase()===r&&Mg(e)===Mg(t))?e.filter(e=>e.name.toLowerCase()!==r):e}(s,l,"ops"===a));if(c)return Hc(_c(c));const d=function(e,t){return"organization"!==e?null:t&&0!==t.length?Eg.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 Hc(_c(d));if(o?.includes("function")){const t=Gp(await Bp(r,e.project_id));if(t)return Hc(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:ad()}):await r.rpc("mutate_project_field_definition",{p_project_id:e.project_id,p_operation:"create",p_field:"ops"===a?{...l,op_id:ka()}:l,p_field_name:null,p_actor_user_id:ad()});if(p)throw p;return Dc(oc({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:Qg(l.name,u)}))}catch(r){const a=Ty(n,t,r);return a?tw(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(xc(r))}}async function nw(e,t){let n;try{const r=await ed();try{await dd(r,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Hc(cn("project"));throw e}const a=t??await Oy(r,e.project_id);if("unreadable"===a)return Ey();n=a;const i=e.name.trim();if(By("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 qg(r,e.project_id,[{name:i}]),a=Jy(t);return Dc(oc({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=Gy(e.confirmation_token,t);if(!n.valid)return Hc(_c(`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:ka()}:null,p_field_name:i,p_actor_user_id:ad()});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),Dc(oc({deleted:s?.deleted??i}))}catch(r){const a=Ty(n,t,r);return a?nw(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(xc(r))}}async function rw(e){try{const t=await ed();try{await dd(t,e.project_id)}catch(e){if(e instanceof Error&&"PROJECT_FIELD_ADMIN_OR_OWNER_REQUIRED"===e.message)return Hc(cn("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 Hc(_c("names must be a non-empty array of existing field names, in the order you want them"));const r=await zg(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 Hc(_c(`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:ad()});if(o)throw o;return Dc(oc({fields:Ug(s?.fields).map(e=>e.name)}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e))}}B(Pg,{PROJECT_FIELD_TYPES:()=>Dg,PROJECT_FIELD_VALUE_MAX:()=>Ng,canonicalizeFieldKeys:()=>Vg,createFieldHandler:()=>tw,createdFieldMessage:()=>Qg,deleteFieldHandler:()=>nw,findUnknownFieldNames:()=>Wg,getProjectFields:()=>zg,isProjectFieldNumber:()=>Gg,isStoredFieldValue:()=>Bg,listFieldsHandler:()=>ew,normalizeProjectFields:()=>Ug,reorderFieldsHandler:()=>rw,validateAndCanonicalizeFieldValues:()=>Jg,validateProjectFieldDefinition:()=>Lg,validateProjectFieldValuesForWrite:()=>Yg});var aw=V({"src/tools/fields.ts"(){md(),zc(),Rl(),Tg(),pn(),si(),Zy(),Vy(),sm(),Fg(),Dg=["text","long","bool","date","person","select","number","link"],Hg=new Set(Dg),Ng=2e3}}),iw={};async function sw(e){try{const t=await ed();try{await cd(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const n=await jh(t,e.project_id);if(null===n)return Hc(Na());if(e.type=r_(e.type),a_(e.type)){const n=await o_(t,e.project_id);if(n)return Hc(n);const r="goal"===e.type?h_(Object.keys(e.fields??{})):[];if(r.length>0)return Hc(_c(y_("A Safety goal",r),Yl))}e.title=Mc(e.title),void 0!==e.body&&(e.body=Mc(e.body)),void 0!==e.summary&&(e.summary=Mc(e.summary)),void 0!==e.level&&(e.level=Mc(e.level)),e.domains&&(e.domains=e.domains.map(e=>Mc(e)));const r=(e.domains??[]).map(sc).filter(e=>e.length>0),a=void 0!==e.level?await og(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=al(r,rl(n?.function_tags),sc);if(s.length>0)return Hc(_c(il(s),Yl));if(i.length>0){const e=new Set(i.map(sc).filter(e=>e.length>0)),t=r.filter(t=>!e.has(t));if(t.length>0)return Hc(_c(`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(()=>(aw(),Pg)),a=await n(t,e.project_id),s=await r(t,e.project_id,a,e.fields);if(s.error)return Hc(_c(s.error));i=s.fields}if(void 0!==e.req_type){const t=Rd(e.req_type,e.type);if(t)return Hc(_c(t,Yl))}if("function"===e.type){const n=Gp(await Bp(t,e.project_id));if(n)return Hc(n);const r=await async function(e,t,n,r,a){if(0===r.length)return null;const i=await $g(e,t,r,a);for(const e of r){const t=i.get(e);if(!t)continue;const r=Ag("the new item",n,t.id,t.type);if(r)return r}return null}(t,e.project_id,e.type,e.parent_ids??[],Hn);if(r)return Hc(_c(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=ad(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n,o=[...new Set(t.parent_ids??[])],l=Ea({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=xa("atoms_create_item"),u=await ja(c?Aa({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:[]}):Sa({userId:r,projectId:t.project_id,content:l,k:0,sessionId:qk()})),p=c?await Wa(l):void 0,m=(await Ga(e,t.project_id,[{op_id:u,content_hash:p}])).get(u);if(m&&("applied"===m.status||"noop"===m.status)&&m.item_id)return Dc(oc({id:m.item_id,type:t.type,title:t.title,project_id:t.project_id,replayed:!0,message:Sr,seq:m.seq??null}));const _=(await xy(e,t.project_id,{[$y(t.type)]:1}))[$y(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:c?await ja(Aa({userId:r,projectId:t.project_id,family:d,key:c,itemIdOrK:0,path:["relationships","parents","add",e]})):ka(),kind:"add",item_id:_,path:["relationships","parents"],value:e});const y=await Ah(e,t.project_id,h,{mode:"single"});if(void 0!==y.error&&0===y.results.length)throw y.error;const g=await Qa(e,t.project_id,y.answers,h),w=await xh({client:e,projectId:t.project_id,answers:g,ops:h,results:y.results,relooked:!0});await Eh(e,t.project_id,h,g,"created");const v=g.find(e=>e.op_id===u);if("invalid"===v?.status&&"op_id_reused"===v.reason)return Hc(cc(jr,["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 Oh(w,{id:_,type:t.type});const b=v?.item_id??_,j=!0===v?.replayed,k=v?.revision_id??null;let S,A;if(k){const n=await ta(e,t.project_id,[k]).then(e=>e.get(k),()=>null);null===n?A=kr:n&&(S=await Qr(n,"all"))}const $={id:b,type:t.type},I={...S?{base_token:S}:{},...ba(w),...j?{replayed:!0,message:Sr}:{},...A?{warning:A}:{}};return!1===t.echo?Dc(oc({...$,...I})):Dc(oc({...$,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,...I}))}(t,e,s):async function(e,t,n){const r=ad(),{sanitizedDomains:a,sanitizedLevel:i,canonicalFields:s}=n;{const n=$y(t.type),l=async()=>(await xy(e,t.project_id,{[n]:1}))[n][0],c=(new Date).toISOString(),d=e=>({id:e,type:t.type,title:t.title,summary:t.summary,body:t.body,...t.req_type?{req_type:t.req_type}:{},tags:{domains:a,level:i??""},ownership:{primary:null,additional:[]},relationships:{parents:t.parent_ids??[],children:[],related:[],verifies:[],verified_by:[]},links:[],...s?{fields:s}:{},metadata:{created_at:c,created_by:r,updated_at:c,updated_by:r}}),u=n=>e.rpc("save_item_with_revision",{p_item_id:n.id,p_project_id:t.project_id,p_type:t.type,p_title:t.title,p_data:n,p_user_id:r,p_event_source:"mcp",p_event_session_id:qk()??null,p_diff_summary:null});let p=await l(),m=d(p),{error:_}=await u(m);if(_&&(o=_)&&/^item_exists\b/.test(String(o.message??"").trim())&&(p=await l(),m=d(p),({error:_}=await u(m))),Sh("main",_),_)throw new Error(_.message);const f=i?eg(i,await lg(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 Tl(()=>e.rpc("apply_link_change",{p_project_id:t.project_id,p_from_id:p,p_to_id:n,p_type:"parent",p_action:"add",p_user_id:r,p_event_source:"mcp"}));a&&(process.stderr.write(`[atoms-mcp] Warning: parent link sync failed for ${n}: ${a.message}\n`),h.push({parent_id:n,message:a.message}))}const y=h.length>0?{link_warnings:h,warning:`${p} was created but could not be attached to ${h.map(e=>e.parent_id).join(", ")}. Repair: call atoms_link_items with type 'parent', from_id=${p}, to_id=<parent id>. Do not create the item again.`}:{};return await e.from("change_history").insert({item_id:p,project_id:t.project_id,changed_by:r,event_type:"created",old_data:null,new_data:m,actor:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===t.echo?Dc(oc({id:p,type:t.type,...f?{level_note:f}:{},...y})):Dc(oc({id:p,type:t.type,title:t.title,summary:t.summary??"",body:t.body??"",...t.req_type?{req_type:t.req_type}:{},domains:a,level:i??"",project_id:t.project_id,...f?{level_note:f}:{},...y}))}var o}(t,e,s))}catch(e){const t=qc(e);return Hc(t||xc(e))}}B(iw,{createItemHandler:()=>sw});var ow=V({"src/tools/create-item.ts"(){md(),qy(),Rk(),zc(),jg(),tg(),cl(),Hd(),sm(),N_(),xg(),xr(),Ul(),si(),Dh(),zc()}});function lw(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 cw(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 dw,uw=V({"src/core/change-control.ts"(){}});var pw,mw,_w=V({"src/core/content-ids.ts"(){dw={row:"r",column:"c",step:"st",param:"p"}}});function fw(e,t){const n=pw[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)+fw(e.slice(r),t.slice(r))}const r=e?pw.indexOf(e[0]):0,a=null!==t?pw.indexOf(t[0]):pw.length;return a-r>1?pw[Math.round(.5*(r+a))]:t&&t.length>1?t.slice(0,1):pw[r]+fw(e.slice(1),null)}function hw(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 yw(e){if(e.length!==hw(e[0]))throw new Error(`invalid integer part of order key: ${e}`)}function gw(e){const t=hw(e[0]);if(t>e.length)throw new Error(`invalid order key: ${e}`);return e.slice(0,t)}function ww(e){if(e===mw)throw new Error(`invalid order key: ${e}`);const t=gw(e);if(e.slice(t.length).slice(-1)===pw[0])throw new Error(`invalid order key: ${e}`)}function vw(e){yw(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=pw.indexOf(n[e])+1;t===pw.length?n[e]=pw[0]:(n[e]=pw[t],r=!1)}if(r){if("Z"===t)return`a${pw[0]}`;if("z"===t)return null;const e=String.fromCharCode(t.charCodeAt(0)+1);return e>"a"?n.push(pw[0]):n.pop(),e+n.join("")}return t+n.join("")}function bw(e,t){if(null!==e&&ww(e),null!==t&&ww(t),null!==e&&null!==t&&e>=t)throw new Error(`${e} >= ${t}`);if(null===e){if(null===t)return`a${pw[0]}`;const e=gw(t),n=t.slice(e.length);if(e===mw)return e+fw("",n);if(e<t)return e;const r=function(e){yw(e);const t=e[0],n=e.slice(1).split(""),r=pw[pw.length-1];let a=!0;for(let e=n.length-1;a&&e>=0;e-=1){const t=pw.indexOf(n[e])-1;-1===t?n[e]=r:(n[e]=pw[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=gw(e),n=e.slice(t.length),r=vw(t);return null===r?t+fw(n,null):r}const n=gw(e),r=e.slice(n.length),a=gw(t),i=t.slice(a.length);if(n===a)return n+fw(r,i);const s=vw(n);if(null===s)throw new Error("cannot increment any more");return s<t?s:n+fw(r,null)}function jw(e,t,n){return bw(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 kw,Sw,Aw=V({"src/core/order-key.ts"(){_w(),pw="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",mw=`A${"0".repeat(26)}`}});function $w(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Iw(e,t){return e<t?-1:e>t?1:0}function xw(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)=>xw(e,t[n]));if($w(e)&&$w(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=>xw(e[n],t[n]))}return!1}function qw(e){return $w(e)&&"string"==typeof e.id?`id:${e.id}`:`json:${Ow(e)}`}function Ow(e){return Array.isArray(e)?`[${e.map(Ow).join(",")}]`:$w(e)?`{${Object.keys(e).filter(t=>void 0!==e[t]).sort(Iw).map(t=>`${JSON.stringify(t)}:${Ow(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function Ew(e,t,n,r={}){if(r.skip?.(e))return[];if(1===e.length&&"relationships"===e[0]?($w(t)||(t={}),$w(n)||(n={})):2===e.length&&"relationships"===e[0]&&(Array.isArray(t)||(t=[]),Array.isArray(n)||(n=[])),xw(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(qw)),s=new Set(a.map(qw)),o=[];for(const t of r)s.has(qw(t))||o.push({kind:"remove",path:[...e],value:t});for(const t of a)i.has(qw(t))||o.push({kind:"add",path:[...e],value:t});return o}(e,t,n);if($w(t)&&$w(n)){const a=new Set([...Object.keys(t),...Object.keys(n)]),i=[];for(const s of[...a].sort(Iw))0===e.length&&r.ignoreKeys?.has(s)||i.push(...Ew([...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 Rw(e){const t={};for(const n of Object.keys(e))kw.has(n)||void 0===e[n]||(t[n]=e[n]);return t}function Mw(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[bw(null,t)];{let e=bw(null,t);const r=[e];for(let a=0;a<n-1;a+=1)e=bw(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`${dw[e]}_${n}`}(Sw[e])),p.add(r),r}),_=m.map(e=>u.get(e)??-1),f=_.flatMap((e,t)=>e>=0?[t]:[]),h=new Set(function(e){const t=[],n=new Array(e.length).fill(-1);for(let r=0;r<e.length;r+=1){let a=0,i=t.length;for(;a<i;){const n=a+i>>1;e[t[n]]<e[r]?a=n+1:i=n}a>0&&(n[r]=t[a-1]),t[a]=r}const r=[];for(let e=t.length?t[t.length-1]:-1;e>=0;e=n[e])r.push(e);return r.reverse()}(f.map(e=>_[e])).map(e=>f[e])),y=[],g=new Set(m);t.forEach((t,n)=>{""===d[n]||u.get(d[n])!==n||g.has(d[n])||y.push({kind:s,path:[e],base:t,row_id:d[n]})});const w=[...l],v=new Array(n.length).fill(null);for(let e=0;e<n.length;e+=1)h.has(e)&&(v[e]=l[_[e]]);for(let t=0;t<n.length;t+=1){if(null!==v[t])continue;const r=t>0?v[t-1]:null;let s=null;for(let e=t+1;e<n.length;e+=1)if(h.has(e)){s=v[e];break}const o=jw(w,r,s);w.push(o),v[t]=o,_[t]<0?y.push({kind:a,path:[e],value:Rw(n[t]),row_id:m[t],order_key:o}):y.push({kind:i,path:[e],base:l[_[t]],row_id:m[t],order_key:o})}for(let a=0;a<n.length;a+=1)_[a]<0||y.push(...Ew([e,m[a]],Rw(t[_[a]]),Rw(n[a]),{skip:r.skip}));return y}var Tw,Cw=V({"src/core/content-ops.ts"(){_w(),Aw(),kw=new Set(["id","order_key","created_seq"]),Sw={steps:"step",params:"param",rows:"row",columns:"column"}}});function Dw(e){const t=e?.analysis_props;return t&&"object"==typeof t&&!Array.isArray(t)?t:null}function Hw(e,t){if(!0!==Dw(e)?.approved)return!1;const n=Dw(t?.data);return null!==n&&!0!==n.approved}var Nw=V({"src/core/human-check.ts"(){Tw="approval cleared (a signature never covers content the approver did not see)"}}),Fw={};async function Pw(e){try{const n=await ed();try{await cd(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const r=await jh(n,e.project_id);if(null===r)return Hc(Na());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?Hc({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=ad(),r=Array.isArray(t.updates);if(!r&&!t.item_id)return Hc(_c("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($d(n));const a=await zw(e,t.project_id,n,c,s),d=Th(c.base_token??(r?t.base_token:void 0));if("entry"in a){o.push({itemId:n,tokens:d,intent:c.intent??t.intent??"edit",...a.entry});continue}const{message:u,path:p,notFound:m,long:_}=a.refusal;if(!r)return Hc(m?dc("Item",n):_c(u,_?Yl:void 0));if(!i)return Hc(_c(`Batch stopped at "${n}": ${u.replace(/\.$/,"")}. Nothing was saved.`,_?Yl: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 sa({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(ia(n));if(a)for(const t of Uw(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 ja(Aa({userId:n,projectId:t.project_id,family:xa("atoms_update_item"),key:t.idempotency_key,itemIdOrK:e.item_id??"",path:Mh(e)})):ka(),t.idempotency_key&&await Va(e),t.reason&&(e.reason=t.reason);let _={answers:[],results:[],notSent:[]};if(m.length>0&&(_=await Ah(e,t.project_id,m,{mode:c}),void 0!==_.error&&0===_.results.length))throw _.error;const f=[...l,...p,..._.answers,...Da(_.notSent)],h=new Map;for(const e of o)Array.isArray(e.steps)&&e.steps.forEach((e,t)=>{e?.id&&h.set(e.id,t+1)});const y=await xh({client:e,projectId:t.project_id,answers:f,ops:m,results:_.results,labels:{stepNumber:e=>h.get(e)}}),g=r?crypto.randomUUID():void 0;if(await Eh(e,t.project_id,m,_.answers,"updated",{batch_id:g,reason:t.reason}),y.not_applied.length>0)return Oh(y,{...r?{batch_id:g}:{id:t.item_id},...$h(_)});const w=new Map;for(const e of[...y.applied]){if(!e.item_id)continue;const t=Rh(e.path),n=w.get(e.item_id)??[];t&&!n.includes(t)&&n.push(t),w.set(e.item_id,n)}const v=new Map;for(const e of y.captured)e.item_id&&v.set(e.item_id,qh(e));const b=Dy(_.answers)?{acceptance_revoked:!0}:{},j=new Set(_.answers.filter(e=>!0===e.approval_cleared&&e.item_id).map(e=>e.item_id)),k=e=>j.has(e)?{approval_cleared:!0}:{};if(r){const e=o.map(e=>v.has(e.itemId)?null!==v.get(e.itemId)?lw(e.itemId,v.get(e.itemId)):cw(e.itemId):{id:e.itemId,updated_fields:w.get(e.itemId)??[],...k(e.itemId)});return Dc(oc({batch_id:g,updated:e.length,results:!1===t.echo?void 0:e,errors:[],...b,...ba(y),...$h(_)}))}const S=t.item_id;if(v.has(S)){const e=v.get(S);return Dc(oc(null!=e?lw(S,e):cw(S)))}const A=w.get(S)??[];if(!1===t.echo)return Dc(oc({id:S,updated_fields:A,...k(S),...b,...ba(y)}));const $=await ea(e,t.project_id,[S]).then(e=>e.get(S),()=>null);if(null===$)return Dc(oc({id:S,updated_fields:A,...k(S),...b,...ba(y),warning:kr}));const I=$?.fields_snapshot??{},x=I.data??{};return Dc(oc({id:S,type:I.type??o[0]?.type,title:I.title??x.title??"",summary:x.summary??"",body:x.body??"",domains:x.tags?.domains??[],level:x.tags?.level??"",...x.req_type?{req_type:x.req_type}:{},updated_fields:A,...$?{base_token:await Qr($,"core")}:{},...k(S),...b,...ba(y)}))}(n,e):async function(e,t){{const n=ad(),r=async(r,a,i,s)=>{const o=await lh(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&&Pu(o))return{updated_fields:[],error:zu(r)};if(void 0!==a.status&&Uu(o,a.status))return{updated_fields:[],error:Lu(r)};void 0!==a.title&&(a.title=Mc(a.title)),void 0!==a.body&&(a.body=Mc(a.body)),void 0!==a.summary&&(a.summary=Mc(a.summary)),void 0!==a.level&&(a.level=Mc(a.level)),void 0!==a.domains&&(a.domains=a.domains.map(e=>Mc(e))),void 0!==a.steps&&(a.steps=Du(a.steps,e=>Mc(e))),void 0!==a.params&&(a.params=Nu(Du(a.params,e=>Mc(e)),o.data.params));const c=void 0!==a.domains?a.domains.map(sc).filter(e=>e.length>0):void 0,d=void 0!==a.level?await og(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=al(c,rl(n?.function_tags),sc);if(i.length>0)return{updated_fields:[],error:il(i)};if(a.length>0){const e=new Set(a.map(sc).filter(e=>e.length>0)),t=c.filter(t=>!e.has(t));if(t.length>0)return{updated_fields:[],error:`Unknown domains: ${t.join(", ")}`}}}const u={...o.data},p={...o.data},m=[],_=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);if(void 0!==a.title&&_(o.data.title,a.title)&&(p.title=a.title,m.push("title")),void 0!==a.body&&_(o.data.body,a.body)&&(p.body=a.body,m.push("body")),void 0!==a.summary&&_(o.data.summary,a.summary)&&(p.summary=a.summary,m.push("summary")),void 0!==c&&_(o.data.tags?.domains??[],c)&&(p.tags={...p.tags,domains:c},m.push("domains")),void 0!==d&&_(o.data.tags?.level,d)&&(p.tags={...p.tags,level:d},m.push("level")),void 0!==a.status&&_(o.data.status,a.status)&&(p.status=a.status,m.push("status")),void 0!==a.req_type){const e=Rd(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?h_(Object.keys(a.fields)):[];if(n.length>0)return{updated_fields:[],error:y_(o.id,n)};const{getProjectFields:r,validateProjectFieldValuesForWrite:i,canonicalizeFieldKeys:s}=await Promise.resolve().then(()=>(aw(),Pg)),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;_(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 f=a.title??o.title,{data:h,error:y}=await e.rpc("save_item_with_revision",{p_item_id:r,p_project_id:t.project_id,p_type:o.type,p_title:f,p_data:p,p_user_id:n,p_event_source:"mcp",p_event_session_id:qk()??null,p_diff_summary:s?{reason:s}:null,p_expected_updated_at:a.expected_updated_at??o.updated_at});if(Sh("main",y),y)return{updated_fields:[],error:y};if(!h)return{updated_fields:[],error:`Update silently failed for "${r}" — RPC returned no row. Likely RLS policy denied the write; verify your role and project access.`};const g=m.includes("level")&&d?eg(d,await lg(e,t.project_id,d)):null,w=Hw(o.data,h);var v;w&&(p.analysis_props=(v=h,Dw(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:Ok(),session_id:qk()};i&&(b.batch_id=i);const j=function(e,t){return t?e?`${e}; ${Tw}`:Tw:e||void 0}(s,w);if(j&&(b.reason=j),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,...g?{levelNote:g}:{},...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(Oc(d))return Hc(xc(d));if(!n){const e=d instanceof Error?d.message:String("object"==typeof d&&d&&"message"in d?d.message??"":d),t=ae(e);return Hc(null!==t?{...t,message:`Batch stopped at "${s.item_id}": ${t.message} ${a.length} item(s) already updated.`}:_c(`Batch stopped at "${s.item_id}": ${e.replace(/\.$/,"")}. ${a.length} item(s) already updated.`,e.includes("Function-flagged tag")||Ed(e)?Yl:void 0))}i.push({item_id:s.item_id,error:String(d)})}else void 0!==l?a.push(lw(s.item_id,l)):c?a.push(cw(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 Dc(oc({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 Hc(_c("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")?Hc(dc("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(wu)||e.includes(vu)}(e)?Hc(_c(e,e.includes("Function-flagged tag")||Ed(e)?Yl:void 0)):jc(e)||Oc(c)?Hc(xc(c)):Hc(Ec(e))}if(void 0!==o)return Dc(oc(lw(t.item_id,o)));if(l)return Dc(oc(cw(t.item_id)));if(!1===t.echo)return Dc(oc({id:t.item_id,updated_fields:a,...d?{level_note:d}:{},...u?{approval_cleared:!0}:{}}));const p=i??{};return Dc(oc({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=qc(e);return Hc(t||xc(e))}var t}async function zw(e,t,n,r,a){const i=await lh(e,t,n);if(!i)return{refusal:{message:`Item "${n}" not found`,path:null,notFound:!0}};if(void 0!==r.status&&Pu(i))return{refusal:{message:zu(n),path:["status"]}};if(void 0!==r.status&&Uu(i,r.status))return{refusal:{message:Lu(n),path:["status"]}};const s=[],o=[],l=(e,t)=>{s.push(e),o.push(t)};if(void 0!==r.title&&l(["title"],Mc(r.title)),void 0!==r.summary&&l(["summary"],Mc(r.summary)),void 0!==r.body&&l(["body"],Mc(r.body)),void 0!==r.req_type){const e=Rd(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 og(e,t,Mc(r.level))),void 0!==r.domains){const e=r.domains.map(e=>sc(Mc(e))).filter(e=>e.length>0);if(e.length>0){const t=await a.read(),n=al(e,rl(t.function_tags),sc);if(n.length>0)return{refusal:{message:il(n),path:["tags","domains"],long:!0}};if(t.domains.length>0){const n=new Set(t.domains.map(sc).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?h_(Object.keys(r.fields)):[];if(a.length>0)return{refusal:{message:y_(n,a),path:["fields"],long:!0}};const{getProjectFields:s,validateProjectFieldValuesForWrite:o,canonicalizeFieldKeys:c}=await Promise.resolve().then(()=>(aw(),Pg)),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"],Du(r.steps,e=>Mc(e))),void 0!==r.params&&l(["params"],Du(r.params,e=>Mc(e))),{entry:{paths:s,values:o,type:i.type,steps:i.data.steps}}}function Uw(e,t,n){const r=e=>Array.isArray(e)?e:[];return 1===e.length&&"steps"===e[0]?function(e,t){return Mw("steps",e??[],t??[])}(r(t),r(n)):1===e.length&&"params"===e[0]?function(e,t){return Mw("params",e??[],t??[],{implicitIds:!0})}(r(t),r(Nu(n,t))):Ew([...e],void 0===t?null:t,n)}B(Fw,{updateItemHandler:()=>Pw});var Lw,Ww=V({"src/tools/update-item.ts"(){Od(),md(),fh(),Rk(),Hd(),ue(),tp(),zc(),jg(),tg(),uw(),cl(),si(),Cw(),Dh(),zc(),N_(),Vy(),Nw()}}),Vw={};async function Bw(e){try{const t=await ed();ad();try{await cd(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const n=await jh(t,e.project_id);if(null===n)return Hc(Na());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 Hc(dc("Item",e.item_id));if(r.deleted_at)return Hc(_c(`Item ${e.item_id} is already deleted`));if(By(Lw,e.project_id)){const t={tool:Lw,project_id:e.project_id,target:e.item_id};if(!e.confirmation_token){const n=Jy(t);return Dc(oc({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=Gy(e.confirmation_token,t);if(!n.valid)return Hc(_c(`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:ka(),kind:"trash_item",item_id:t.item_id,path:[]}],a=await Ah(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await xh({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await Eh(e,t.project_id,r,a.answers,"deleted"),i.not_applied.length>0?Oh(i,{id:t.item_id}):Dc(oc({...n,...ba(i)}))}(t,e,a):async function(e,t,n,r){const a=ad(),{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:Ok(),p_session_id:qk()});if(Sh("main",i),i)throw new Error(i.message);return Dc(oc(r))}(t,e,r,a))}catch(e){const t=qc(e);return Hc(t||xc(e))}}B(Vw,{deleteItemHandler:()=>Bw});var Jw=V({"src/tools/delete-item.ts"(){md(),fh(),Rk(),Zy(),zc(),si(),Dh(),zc(),Lw="atoms_delete_item"}}),Gw={};async function Qw(e){try{const t=await ed(),n=ad();try{await cd(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const r=await jh(t,e.project_id);if(null===r)return Hc(Na());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 Hc(dc("Item",e.item_id));if(!a.deleted_at){if(!r){const n=await Kw(t,e.project_id,e.item_id);if(n.error)return Hc(Wl(e.item_id,Yw(n)))}return Hc({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 Hc(Ll());if(!0!==e.confirm)return Dc(function(e){const t=e.days_in_trash??0;return{status:"needs_confirmation",message:`${e.item_id} "${e.title??""}" is in Trash. ${Vl(e)} moved it there on ${Bl(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:[...Fl],id:e.item_id,title:e.title??"",restored:!1,trashed_by:Vl(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:Jl(l,n)};return await Pa(r?"ops":"main",n=>"ops"===n?async function(e,t,n){const r=[{op_id:ka(),kind:"restore_item",item_id:t.item_id,path:[]}],a=await Ah(e,t.project_id,r,{mode:"single"});if(void 0!==a.error&&0===a.results.length)throw a.error;const i=await xh({client:e,projectId:t.project_id,answers:a.answers,ops:r,results:a.results});return await Eh(e,t.project_id,r,a.answers,"restored"),i.not_applied.length>0?Oh(i,{id:t.item_id}):Dc(oc({...n,...ba(i)}))}(t,e,c):async function(e,t,n,r){const a=ad(),{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:qk()??null});if(Sh("main",i),i)throw i;const s=await Kw(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:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),s.error?Hc(Wl(t.item_id,Yw(s))):Dc(oc(r))}(t,e,a,c))}catch(e){const t=qc(e);return Hc(t||xc(e))}}function Kw(e,t,n){return Cl(()=>e.rpc("repair_live_item_relationships_from_jsonb",{p_project_id:t,p_item_id:n}))}function Yw(e){return{message:e.error?.message??"",code:e.error?.code??null,status:e.status}}B(Gw,{restoreItemHandler:()=>Qw});var Zw,Xw=V({"src/tools/restore-item.ts"(){md(),Rk(),rc(),Ul(),zc(),si(),Dh(),zc()}}),ev=V({"src/core/batch-cycle.ts"(){xr()}}),tv={};async function nv(e){try{const t=await ed(),n=ad();try{await cd(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}let r;const a=async()=>void 0===r?r=await jh(t,e.project_id):r,i=async(r,a,i)=>{const s=await lh(t,e.project_id,r.from_id);if(!s)throw new Error(`Item "${r.from_id}" not found`);const o=await lh(t,e.project_id,r.to_id);if(!o)throw new Error(`Item "${r.to_id}" not found`);const{error:l}=await t.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:r.from_id,p_to_id:r.to_id,p_type:r.type,p_action:r.action,p_user_id:n,p_event_source:"mcp",p_expected_from_updated_at:r.expected_from_updated_at??s.updated_at,p_expected_to_updated_at:r.expected_to_updated_at??o.updated_at});if(Sh("main",l),l)throw new Error(l.message);if("affects"===r.type||"affected_by"===r.type)for(const r of[s,o]){const a=es(r.data);if(!a)continue;const i=await lh(t,e.project_id,a);if(!i)continue;const{revoked:s,parentProps:o}=ts(i.data);if(!s)continue;const l={...i.data,analysis_props:o},{error:c}=await t.rpc("save_item_with_revision",{p_item_id:i.id,p_project_id:e.project_id,p_type:i.type,p_title:i.title,p_data:l,p_user_id:n,p_event_source:"mcp",p_event_session_id:qk()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});c&&process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${i.id}': ${c.message}\n`)}const c={item_id:r.from_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:null,new_data:{relationship_change:{action:r.action,type:r.type,from:r.from_id,to:r.to_id}},actor:Ok(),session_id:qk()};a&&(c.batch_id=a),i&&(c.reason=i),await t.from("change_history").insert(c).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})};if(e.operations&&Array.isArray(e.operations)){for(const t of e.operations){if(t.from_id===t.to_id)return Hc(_c(`Self-reference in batch: "${t.from_id}"`));if("affects"===t.type||"affected_by"===t.type){const e=kg(t.from_id,t.to_id,t.type);if(e)return Hc(_c(e))}}const n=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],r=await Hn(n,n=>t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",n)),s=new Set(r.map(e=>e.id)),o=n.filter(e=>!s.has(e));if(o.length>0)return Hc(dc("Items",o.join(", ")));const l=await Ig(t,e.project_id,e.operations,Hn);if(l)return Hc("toolError"in l?l.toolError:_c(`${l.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 c=(n,r,a)=>Rn(()=>e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).eq("type",n).in(r,a),vn);for(;l.length>0;){for(const e of l)o.set(e,new Set);for(let e=0;e<l.length;e+=$n){const t=l.slice(e,e+$n);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(c)return Hc(_c(`Batch would create a cycle: ${c}. No changes applied.`));const d=e.operations,u=await a();return null===u?Hc(Na()):await Pa(u?"ops":"main",async n=>{if("ops"===n)return rv(t,e,d,!0);const r=crypto.randomUUID(),a=[...d.filter(e=>"remove"===e.action),...d.filter(e=>"add"===e.action)],s=[],o=e=>`${e.action} ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`;for(const t of a){try{await i(t,r,e.reason)}catch(e){if(Fa("main",e))throw e;const n=xc(e);return Hc({...n,message:`${n.message}\n\nThis batch is not atomic: its operations are applied one at a time. ${s.length} of ${a.length} operation(s) committed before this one failed and were NOT rolled back (batch ${r}). Committed: ${s.length?s.map(o).join("; "):"none"}. Failed: ${o(t)}.`,next_steps:dn(s.length,n)})}s.push(t)}return Dc(oc({batch_id:r,processed:d.length,operations:!1===e.echo?void 0:d}))})}if(!(e.from_id&&e.to_id&&e.type&&e.action))return Hc(_c("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."));if(e.from_id===e.to_id)return Hc(_c("Cannot create a relationship between an item and itself"));if("affects"===e.type||"affected_by"===e.type){const t=kg(e.from_id,e.to_id,e.type);if(t)return Hc(_c(t))}const s=await Ig(t,e.project_id,[{action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type}],Hn);if(s)return Hc("toolError"in s?s.toolError:_c(s.validation));const o={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},l=await a();return null===l?Hc(Na()):await Pa(l?"ops":"main",async n=>"ops"===n?rv(t,e,[o],!1):(await i(o,void 0,e.reason),!1===e.echo?Dc(oc({action:o.action,from_id:o.from_id,to_id:o.to_id})):Dc(oc({action:o.action,type:o.type,from_id:o.from_id,to_id:o.to_id,message:`Relationship ${"add"===o.action?"added":"removed"}: ${o.from_id} --[${o.type}]--\x3e ${o.to_id}`}))))}catch(e){const t=qc(e);return Hc(t||xc(e))}}async function rv(e,t,n,r){const a=ad(),i=[];for(const e of n){const n={op_id:"",kind:e.action,item_id:e.from_id,path:["relationships",Zw[e.type]],value:e.to_id};n.op_id=t.idempotency_key?await ja(Aa({userId:a,projectId:t.project_id,family:xa("atoms_link_items"),key:t.idempotency_key,itemIdOrK:e.from_id,path:Mh(n)})):ka(),t.reason&&(n.reason=t.reason),i.push(n)}const s=await Ah(e,t.project_id,i);if(void 0!==s.error&&0===s.results.length)throw s.error;const o=await xh({client:e,projectId:t.project_id,answers:[...s.answers,...Da(s.notSent)],ops:i,results:s.results}),l=r?crypto.randomUUID():void 0;if(await Eh(e,t.project_id,i,s.answers,"updated",{batch_id:l,reason:t.reason}),o.not_applied.length>0)return Oh(o,{...r?{batch_id:l}:{},...$h(s)});if(r)return Dc(oc({batch_id:l,processed:n.length,operations:!1===t.echo?void 0:n,...ba(o),...$h(s)}));const c=n[0];return!1===t.echo?Dc(oc({action:c.action,from_id:c.from_id,to_id:c.to_id,...ba(o)})):Dc(oc({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}`,...ba(o)}))}B(tv,{linkItemsHandler:()=>nv});var av,iv,sv=V({"src/tools/link-items.ts"(){md(),fh(),xr(),ev(),Rk(),ro(),pn(),zc(),si(),Dh(),zc(),xg(),Zw={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"}}}),ov=V({"src/core/bulk-parent-links.ts"(){Ul()}}),lv={};function cv(e){return new Set(["22023","23503","23505","23514"]).has(e.code??"")}function dv(e,t){return e.items.length>t?Hc(_c(`Maximum ${t} items per call (received ${e.items.length}). Split into multiple calls.`)):null}async function uv(e){try{if(!e.items||0===e.items.length)return Hc(_c("items array must contain at least 1 item"));const t=dv(e,av);if(t)return t;const n=await ed();try{await cd(n,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const r=await jh(n,e.project_id);if(null===r)return Hc(Na());if(!r){const t=dv(e,iv);if(t)return t}if(e.items.some(e=>"function"===e.type)){const t=Gp(await Bp(n,e.project_id));if(t)return Hc(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 $g(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=Ag("the new item",e.type,n.id,n.type);if(r)return{index:t,message:r}}return null}(n,e.project_id,e.items,Hn);if(r)return Hc(_c(`Nothing was imported. items[${r.index}]: ${r.message}`))}if(e.items=e.items.map(e=>({...e,type:r_(e.type)})),e.items.some(e=>a_(e.type))){const t=await o_(n,e.project_id);if(t)return Hc(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=rl(r?.function_tags),o=i.length>0?new Set(i.map(sc).filter(e=>e.length>0)):null,l=Ky(i.map(sc).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(sc).filter(e=>e.length>0);if(0===r.length)continue;const a=al(r,s,sc);if(a.length>0){d.add(e),c.push({index:e,title:t.title,error:il(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(By("atoms_bulk_import",e.project_id)){const t={tool:"atoms_bulk_import",project_id:e.project_id,target:Ky({items:e.items,registered_domain_hash:a.registeredDomainHash})};if(!e.confirmation_token){const n=Jy(t);return Dc(oc({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=Gy(e.confirmation_token,t);if(!n.valid)return Hc(_c(`confirmation_token rejected: ${n.reason}`))}return await Pa(r?"ops":"main",t=>"ops"===t?async function(e,t,n){const r=ad(),a=t.idempotency_key,i=xa("atoms_bulk_import"),s=t.items.some(e=>void 0!==e.level)?await ag(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(sc).filter(e=>e.length>0),r=void 0!==e.level?Xy(e.level,sc(e.level),s,rg):void 0;return{input:e,index:t,domains:n,level:r,content:Ea({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=qa(o.map(e=>e.content)),c=[];for(let e=0;e<o.length;e+=1)c.push(await ja(a?Aa({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:o[e].index,path:[]}):Sa({userId:r,projectId:t.project_id,content:o[e].content,k:l[e],sessionId:qk()})));const d=a?await Promise.all(o.map(e=>Wa(e.content))):[],u=await Ga(e,t.project_id,c.map((e,t)=>({op_id:e,content_hash:d[t]}))),p=[],m=[],_=[];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)):_.push({v:e,createId:c[t],contentHash:d[t]})});const f=[...n.errors],h=[],y=new Map;if(_.length>0){const n={};for(const{v:e}of _){const t=$y(e.input.type);n[t]=(n[t]??0)+1}const s=Iy(await xy(e,t.project_id,n));for(const{v:e,createId:n,contentHash:o}of _){const l=s($y(e.input.type));y.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 ja(Aa({userId:r,projectId:t.project_id,family:i,key:a,itemIdOrK:e.index,path:["relationships","parents","add",e.input.parent_id]})):ka(),kind:"add",item_id:l,path:["relationships","parents"],value:e.input.parent_id})}}let g={answers:[],results:[],notSent:[]};if(h.length>0&&(g=await Ah(e,t.project_id,h,{mode:"bulk"}),void 0!==g.error&&0===g.results.length))throw g.error;const w=[...await Qa(e,t.project_id,g.answers,h),...Da(g.notSent)],v=await xh({client:e,projectId:t.project_id,answers:w,ops:h,results:g.results,relooked:!0});await Eh(e,t.project_id,h,w,"created");const b=[...p],j=[...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=y.get(e.item_id);t&&(b.push({id:e.item_id,title:t.title,type:t.type,...e.replayed?{replayed:!0}:{}}),j.push(e))}const{tokens:k,unread:S}=await Py(e,t.project_id,j);for(const e of b){const t=k.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,...g.chunks?{chunks:g.chunks}:{},...void 0!==g.error?{error:xc(g.error).message}:{},...A?{replayed:!0,message:Sr}:{},...S?{warning:nr}:{}};return v.not_applied.length>0?Oh(b.length>0&&0===v.applied.length?{...v,applied:b.map(e=>({item_id:e.id,path:[],status:"applied",seq:null,replayed:!0}))}:v,$):Dc(oc({...$,...ba(v)}),{receipt:"items"})}(n,e,a):async function(e,t,n){const r=ad();{const a=(new Date).toISOString(),i=qk(),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=$y(e.type);d[t]=(d[t]??0)+1}let u=null,p=null;try{u=Iy(await xy(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($y(e))},_=t.items.some(e=>void 0!==e.level)?await ag(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(sc).filter(e=>e.length>0),i=void 0!==r.level?Xy(r.level,sc(r.level),_,rg):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 Dc(oc({created:0,items:[],errors:o}));const f=[],h=new Map;for(const{itemId:e,input:n,sanitizedDomains:i,sanitizedLevel:s}of l){const o={id:e,type:n.type,title:n.title,summary:n.summary,body:n.body,tags:{domains:i,level:s??""},ownership:{primary:null,additional:[]},relationships:{parents:n.parent_id?[n.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:a,created_by:r,updated_at:a,updated_by:r}};h.set(e,o),f.push({id:e,project_id:t.project_id,type:n.type,title:n.title,data:o,created_by:r,updated_by:r})}const y=f.map(e=>({id:e.id,type:e.type,title:e.title,data:e.data})),{error:g}=await e.rpc("bulk_save_items_with_revisions",{p_project_id:t.project_id,p_items:y,p_user_id:r,p_event_source:"mcp"});if(Sh("main",g),g&&cv(g))for(const{itemId:n,input:a,index:c}of l){const l=f.find(e=>e.id===n);if(!l)continue;const{error:d}=await e.rpc("save_item_with_revision",{p_item_id:l.id,p_project_id:t.project_id,p_type:l.type,p_title:l.title,p_data:l.data,p_user_id:r,p_event_source:"mcp",p_event_session_id:i,p_diff_summary:null});d?o.push({index:c,title:a.title,error:d.message}):s.push({id:n,title:a.title,type:a.type})}else{if(g)throw g;for(const{itemId:e,input:t}of l)s.push({id:e,title:t.title,type:t.type})}const w=l.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>s.some(t=>t.id===e)).map(({itemId:e,input:n})=>({from_id:e,to_id:n.parent_id,type:"parent",project_id:t.project_id}));await async function(e){for(const t of e.links){const{error:n}=await e.client.rpc("apply_link_change",{p_project_id:e.projectId,p_from_id:t.from,p_to_id:t.to,p_type:"parent",p_action:"add",p_user_id:e.userId,p_event_source:"mcp"});n&&e.warn(`bulk parent link sync failed for ${t.to}: ${n.message??"unknown error"}`)}}({client:e,projectId:t.project_id,links:w.map(e=>({from:e.from_id,to:e.to_id})),userId:r,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}),s.length>0&&await async function(e){try{const{data:t,error:n}=await Cl(()=>e.client.rpc("repair_project_link_rows_unless_busy",{p_project_id:e.projectId}));n?e.warn(`link repair after the import failed: ${n.message??"unknown error"}`):null==t&&e.warn("link repair after the import skipped: the project is being restored, moved to the Trash or relinked")}catch(t){e.warn(`link repair after the import failed: ${t instanceof Error?t.message:String(t)}`)}}({client:e,projectId:t.project_id,warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)});const v=s.map(e=>({item_id:e.id,project_id:t.project_id,changed_by:r,event_type:"created",old_data:null,new_data:h.get(e.id)??null,actor:Ok(),session_id:i}));v.length>0&&await e.from("change_history").insert(v).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)});const b=new Set(s.map(e=>e.id)),j=new Set(l.filter(({itemId:e,sanitizedLevel:t})=>t&&b.has(e)).map(({sanitizedLevel:e})=>e)),k=[];for(const n of j){const r=eg(n,await lg(e,t.project_id,n));r&&k.push(r)}return Dc(oc({created:s.length,items:s,errors:o.length>0?o:[],project_id:t.project_id,...k.length>0?{level_notes:k}:{}}),{receipt:"items"})}}(n,e,a))}catch(e){const t=qc(e);return Hc(t||xc(e))}}B(lv,{BULK_IMPORT_MAIN_MAX:()=>iv,BULK_IMPORT_MAX:()=>av,bulkImportHandler:()=>uv,canRetryBulkImportPerItem:()=>cv});var pv=V({"src/tools/bulk-import.ts"(){md(),qy(),Rk(),Zy(),zc(),ov(),jg(),tg(),cl(),si(),Dh(),zc(),Vy(),sm(),N_(),xg(),xr(),av=500,iv=100}}),mv={};async function _v(e){const t=ad(),n=e.idempotencyKey||await async function(e){return null==e.requestId||""===e.requestId?ka():ja(["append_run_key",e.sessionId,String(e.requestId)])}({sessionId:qk(),requestId:e.requestId}),r=await Promise.all(e.entries.map(e=>async function(e){return zr(Pr(Oa(e)))}(e))),a=qa(r),i=[];for(let s=0;s<e.entries.length;s+=1){const o=await ja($a({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 Ry({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 lh(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:Ru(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 fv(e,t){let n;try{const r=await ed(),a=ad(),i=id();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const s=t??await Oy(r,e.project_id);if("unreadable"===s)return Ey();n=s;const o=await lh(r,e.project_id,e.item_id);if(!o)return Hc(dc("Item",e.item_id));if("test-case"!==o.type)return Hc(_c(`Item '${e.item_id}' is a ${o.type}, not a test-case`));const l=(e.asset??"").trim(),c=Hu({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=>Mc(e)),d=Ou([e]).length>0?{release_note:su}:{};if("ops"===s){const t=await _v({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 Hc(_c(t.refusal,Yl));const n=t.runs[0],s=l?` (asset: ${l})`:"",o=n.result;return My(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?Ar:`Test result '${o??"recorded"}' recorded for ${e.item_id}${s}`,...null!==o&&o!==e.result?{verdict_note:Tu([0],!0)}:{},...void 0!==e.date&&null!==e.date?{warning:ou}:{},...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:Ru(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:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const p=l?` (asset: ${l})`:"";return Dc(oc({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:Tu([0],!0)}:{},...void 0!==e.date&&null!==e.date?{warning:ou}:{},...d}))};return await u()}catch(r){const a=Ty(n,t,r);return a?fv(e,a):Hc(xc(r))}}B(mv,{recordRunsByOps:()=>_v,recordTestResultHandler:()=>fv});var hv=V({"src/tools/record-test-result.ts"(){md(),fh(),Rk(),zc(),tp(),si(),Vy(),si()}}),yv={};async function gv(e,t){let n;try{const r=await ed(),a=ad(),i=id();if(!Array.isArray(e.results)||0===e.results.length)return Hc(_c("results must be a non-empty array"));if(e.results.length>100)return Hc(_c(`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?Au(e.date):NaN;Number.isNaN(a)||(a<n?t.push(r):n=a)}),t}(e.results);if(s.length>0)return Hc(_c(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),Yl));try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const o=t??await Oy(r,e.project_id);if("unreadable"===o)return Ey();n=o;const l=await lh(r,e.project_id,e.item_id);if(!l)return Hc(dc("Item",e.item_id));if("test-case"!==l.type)return Hc(_c(`Item '${e.item_id}' is a ${l.type}, not a test-case`));if("ops"===o){const t=e.results.map(e=>{const t=Hu(e,e=>Mc(e)),{date:n,...r}=t;return r}),n=await _v({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 Hc(_c(n.refusal,Yl));const a=xu(e.results),i=Ou(e.results),s=Mu(e.results,n.runs);return My(n.run.outcome,{item_id:e.item_id,count:e.results.length,results:n.runs,...s.length>0?{verdict_note:Tu(s),verdict_differs_entries:s}:{},message:n.run.outcome.replayed?Ar:`Recorded ${e.results.length} test results for ${e.item_id}`,...a.length>0?{warning:qu(a),ignored_date_entries:a}:{},...i.length>0?{release_note:Eu(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=>Hu(e,e=>Mc(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:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const s=xu(e.results),o=Ou(e.results),l=Mu(e.results,t);return Dc(oc({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:Tu(l),verdict_differs_entries:l}:{},...s.length>0?{warning:qu(s),ignored_date_entries:s}:{},...o.length>0?{release_note:Eu(o),no_release_entries:o}:{}}))};return await c()}catch(r){const a=Ty(n,t,r);return a?gv(e,a):Hc(xc(r))}}B(yv,{recordTestResultsBulkHandler:()=>gv});var wv=V({"src/tools/record-test-results-bulk.ts"(){md(),fh(),Rk(),zc(),hv(),si(),Vy(),tp()}}),vv={};async function bv(e){try{const t=U_(e.depth),n=await ed(),r=await lh(n,e.project_id,e.item_id);if(!r)return Hc(dc("Item",e.item_id));const a=await Rn(()=>n.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),wn),i=qp(a,await Rn(()=>n.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),vn)),s=function(e,t=0,n){const{rows:r,meta:a}=$l(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=U_(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=P_(t,s),a=r.type;if(n||!E_.includes(a)){if(("upstream"===e.direction||"both"===e.direction)&&(!q_.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),O_.has(a))){const e=R_[a]??a;n&&!n.has(e)||i(r.to_id,r.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(!O_.has(a)||n&&!n.has(a)||i(r.from_id,r.to_id,a),q_.has(a))){const e=R_[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(;d.length>0&&l.length<x_;){const{id:e,depth:n,relType:i,from:s}=d.shift();if(o.has(e)||n>t)continue;o.add(e);const u=r.get(e);if(u&&(l.push({id:e,title:F_(u),type:u.type,relationship:i,depth:n,from:s,...z_(u,r)}),c.push({from:s,to:e,type:i}),n<t))for(const t of a.get(e)??[])o.has(t.neighbor)||d.push({id:t.neighbor,depth:n+1,relType:t.relType,from:e})}const u={id:e.rootItemId,title:F_(e.rootItem),type:e.rootItem.type,relationship:"root",depth:0,from:e.rootItemId,...z_(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,...l.length>=x_?{truncated:!0,truncation_message:`Results capped at ${x_} items. Use a smaller depth or filter by relationship_types.`}:{}}}({projectId:e.project_id,rootItemId:e.item_id,rootItem:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown",data:r.data},items:a,relationships:i??[],direction:e.direction,depth:t,relationshipTypes:e.relationship_types}),e.offset,e.limit);return Dc(oc(s.data,s.meta),{paging:s.paging})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(vv,{traceHandler:()=>bv});var jv=V({"src/tools/trace.ts"(){md(),fh(),xr(),K_(),zc()}}),kv={};async function Sv(e){try{const t=await ed(),n=await Rn(()=>{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)},bn);return Dc(oc({assets:n,total:n.length}),{complete:!0})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(kv,{listAssetsHandler:()=>Sv});var Av,$v=V({"src/tools/assets.ts"(){md(),xr(),zc()}});function Iv(e){const t=e.data?.body;return"string"==typeof t?t.toLowerCase():""}function xv(e,t){return"string"==typeof e&&e.toLowerCase().includes(`{${t.toLowerCase()}}`)}async function qv(e,t,n){const r=new Map,a=[...new Set(n.map(e=>e.toLowerCase()))];if(0===a.length)return r;if(a.length<=Av)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 Rn(()=>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=>xv(t.body,e)).length);return r}function Ov(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 Ev,Rv,Mv=V({"src/core/variable-refs.ts"(){xr(),Av=10}}),Tv={};async function Cv(e,t,n,r){if(n&&r)throw new Zt("baseline_id and as_of are mutually exclusive");if(r)return Sn(ah(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 Zt("Baseline not found for this project");return An(n)}async function Dv(e,t,n){return n?Dn(e,t,n):Rn(()=>e.from("project_variables").select("*").eq("project_id",t),jn)}async function Hv(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 Nv(e,t,n){if(0===n.length||!0!==await Ha(e,t))return n;const r=await ea(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 Qr(t,"variable","variable")}:e}))}async function Fv(e,t,n,r){const a=ad(),i=xa("atoms_create_variable");return n?{rowId:await ja(Aa({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables","row_id"]})),opId:await ja(Aa({userId:a,projectId:e,family:i,key:n,itemIdOrK:r,path:["variables"]}))}:{rowId:await ja(Ia({userId:a,projectId:e,name:t,what:"variable"})),opId:await ja(Ia({userId:a,projectId:e,name:t,what:"create_variable"}))}}async function Pv(e){try{const t=await ed(),n=await Cv(t,e.project_id,e.baseline_id,e.as_of),r=await Dv(t,e.project_id,n),a=e.limit??50,i=e.offset??0,s=r.slice(i,i+a);return Dc(oc({variables:null===n?await Nv(t,e.project_id,s):s,total:r.length},lc(r.length,a,i)),{paging:{list:"variables"}})}catch(e){return Hc(xc(e,{read:!0}))}}async function zv(e){try{const t=await ed(),n=await Cv(t,e.project_id,e.baseline_id,e.as_of),r=(await Dv(t,e.project_id,n)).find(t=>t.name===e.variable_name)??null;if(!r)return Hc(dc("Variable",e.variable_name));const a=(await Rn(()=>t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),wn)).filter(t=>xv(t.data?.body,e.variable_name)),[i]=null===n?await Nv(t,e.project_id,[r]):[r];return Dc(oc({variable:i,referenced_by:a.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:a.length}))}catch(e){return Hc(xc(e,{read:!0}))}}async function Uv(e,t){let n;try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();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 Hc(dc("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 sa({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:t,tokens:Cy(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(ia(a[t]));n&&l.push(la({op_id:ka(),kind:"set",item_id:null,path:a[t],value:e},n))});const c=await Ry({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 My(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 Hv(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?Dc(oc({name:e.variable_name,updated:!0})):Dc(oc({variable:l}))}catch(r){const a=Ty(n,t,r);return a?Uv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}async function Lv(e,t){let n;try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();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 Hc(_c(`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 Hc(_c(`Duplicate names in batch (case-insensitive): ${[...new Set(l)].join(", ")}`));const c=await Dv(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 Hc(_c(`Variable(s) already exist (case-insensitive): ${u.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const p=Ov(e.variables,await qv(r,e.project_id,n));if("ops"===i){const t=e.variables,n=await Promise.all(t.map((t,n)=>Fv(e.project_id,t.name,e.idempotency_key,n))),a=await Promise.all(t.map((t,r)=>Ev(Rv(n[r],t),e.idempotency_key))),i=crypto.randomUUID(),s=await Ry({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 My(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{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 Dc(oc({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 Hc(_c("Provide either (name, value) for single variable or variables[] for batch."));if(!s.test(e.name))return Hc(_c(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const o=(await Dv(r,e.project_id,null)).find(t=>t.name.toLowerCase()===e.name.toLowerCase());if(o)return Hc(_c(`Variable "${o.name}" already exists in this project (names are unique regardless of case).`));const l=Ov([e],await qv(r,e.project_id,[e.name]));if("ops"===i){const t=await Fv(e.project_id,e.name,e.idempotency_key,0),n=await Ry({client:r,projectId:e.project_id,ops:[await Ev(Rv(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 My(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 Hv(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?Dc(oc({name:e.name,...l})):Dc(oc({variable:c,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`,...l}))}catch(r){const a=Ty(n,t,r);return a?Lv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}async function Wv(e,t){let n;try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();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 Hc(dc("Variable",e.name));const o=(await qv(r,e.project_id,[e.name])).get(e.name.toLowerCase())??0;if(o>0&&!e.force)return Hc(_c(`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(By("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=Jy(t);return Dc(oc({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=Gy(e.confirmation_token,t);if(!n.valid)return Hc(_c(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t=["variables",String(s.id)],n=await sa({client:r,projectId:e.project_id,kind:"variable",mode:"single",requests:[{itemId:String(s.id),tokens:Cy(e.base_token),paths:[t],values:[null],name:e.name}]}),a=n.items.get(String(s.id))?.bases.get(ia(t)),i=a?[la({op_id:ka(),kind:"remove",item_id:null,path:["variables"],row_id:String(s.id),value:null},a)]:[],l=await Ry({client:r,projectId:e.project_id,ops:i,refusals:n.refusals});return My(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?Dc(oc({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})):Hc(dc("Variable",e.name))}catch(r){const a=Ty(n,t,r);return a?Wv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}B(Tv,{createVariableHandler:()=>Lv,deleteVariableHandler:()=>Wv,getVariableHandler:()=>zv,listVariablesHandler:()=>Pv,updateVariableHandler:()=>Uv});var Vv,Bv,Jv=V({"src/tools/variables.ts"(){md(),si(),Vy(),xr(),ih(),Mv(),pn(),Zy(),zc(),Ev=async(e,t)=>t?Va(e):e,Rv=(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}})}}),Gv={};async function Qv(e,t,n,r,a){let i=0,s=Vv;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)>=Bv){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 Kv(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 Yv(e){try{const t=await ed(),{domains:n,functionTags:r}=await Kv(t,e.project_id),a=al(n,r),i=new Set(a.map(Oo)),s=new Set(r.map(Oo)),o=n.filter(e=>!i.has(Oo(e))),{counts:l,orphans:c}=await async function(e,t,n){const r=await Rn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),wn),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(Oo(e))).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),p=[...d,...u];return Dc(oc({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")?Hc(fc()):Hc(xc(e,{read:!0}))}}async function Zv(e,t){let n;try{const r=await ed();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const a=t??await Oy(r,e.project_id);if("unreadable"===a)return Ey();n=a;const i=Mc(e.name).trim().toLowerCase();if(!i)return Hc(_c("Domain name cannot be empty."));const s=await Kv(r,e.project_id);if(null!==Eo(i,s.functionTags))return Hc(_c(ml(i,!0),Yl));const o=Eo(i,s.domains);if(null!==o)return Hc(_c(ml(o,!1),Yl));if("ops"===a){const t={op_id:ka(),kind:"add",item_id:null,path:["taxonomy","domains"],value:i},{run:n}=await zy({client:r,projectId:e.project_id,op:t});return n.answers.some(e=>"noop"===e.status)?Hc(_c(ml(i,!1),Yl)):My(n.outcome,{domain:{name:i},message:pl(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 Kv(r,e.project_id),n=null!==Eo(i,t);return Hc(_c(ml(i,n),Yl))}return Dc(oc({domain:{name:i},message:pl(i)}))};return await l()}catch(r){const a=Ty(n,t,r);return a?Zv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}async function Xv(e,t){let n;const r=mm("atoms_update_domain",e);if(r)return Hc(r);try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();if(n=i,"string"!=typeof e.new_name)return Hc(_c("Pass new_name, the domain's new name."));const{domains:s,functionTags:o}=await Kv(r,e.project_id),l=Mc(e.name).trim(),c=function(e,t){const n=e.trim();return"ops"===t?n:n.toLowerCase()}(Mc(e.new_name),"ops"===i?"ops":"main");if(!c)return Hc(_c("new_name cannot be empty."));const{spelling:d,registered:u}=await dl(r,e.project_id,l,s);if(null===d)return Hc(dc("Domain",l.toLowerCase()));if(null!==Eo(c,[d]))return Hc(_c(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!==Eo(t,[e]))return null;const a=Eo(t,r);if(null!==a)return{kind:"function",name:a};const i=Eo(t,n);return null!==i?{kind:"domain",name:i}:null}(d,c,s,o);if("function"===p?.kind)return Hc(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:ll,functions:[n]}}}(d,c,p.name));if("domain"===p?.kind&&u)return Hc(_c(_l(p.name)));const m="domain"===p?.kind&&!u,_=m&&p?p.name:c,f=await ul(r,e.project_id,[d]);if(e.dry_run)return Dc(oc({dry_run:!0,rename:{from:d,to:_},items_affected:f,message:m?`Dry run: "${d}" is not registered and "${_}" is, so the ${f} item${1!==f?"s":""} carrying "${d}" would be merged into the registered domain "${_}" (the registry is not changed). Call again with dry_run=false to apply.`:`Dry run: renaming "${d}" → "${c}" would update ${f} item${1!==f?"s":""}. Call again with dry_run=false to apply.`}));if("ops"===i){const t={op_id:ka(),kind:"rename",item_id:null,path:["taxonomy","domains"],value:_,base:d},{run:n,retagged:a}=await zy({client:r,projectId:e.project_id,op:t,repeat:!0});return Uy(n,"deleted")?Hc(dc("Domain",d.toLowerCase())):Uy(n,"invalid","name_taken")?Hc(_c(_l(_))):My(n.outcome,{domain:{name:_},renamed_from:d,items_updated:a,message:m?`Domain "${d}" merged into the registered domain "${_}". ${a} item${1!==a?"s":""} updated.`:`Domain renamed "${d}" → "${c}". ${a} item${1!==a?"s":""} updated.`},n)}const h=async()=>{const t=await Qv(r,e.project_id,d,_,a);return m?Dc(oc({domain:{name:_},renamed_from:d,items_updated:t,message:`Domain "${d}" 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,d,c),Dc(oc({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=Ty(n,t,r);return a?Xv(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}async function eb(e,t){let n;try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();n=i;const{domains:s}=await Kv(r,e.project_id),o=Mc(e.name).trim(),{spelling:l,registered:c}=await dl(r,e.project_id,o,s),d=l??o.toLowerCase(),u=null===l?0:await ul(r,e.project_id,[l]);if(!c&&0===u)return Hc(dc("Domain",d));if(u>0&&!e.force)return Hc(_c(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(By("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=Jy(t);return Dc(oc({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=Gy(e.confirmation_token,t);if(!n.valid)return Hc(_c(`confirmation_token rejected: ${n.reason}`))}if("ops"===i){const t={op_id:ka(),kind:"remove",item_id:null,path:["taxonomy","domains"],value:d},{run:n,retagged:a}=await zy({client:r,projectId:e.project_id,op:t,repeat:!0});return Uy(n,"deleted")?Hc(dc("Domain",d)):My(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 Qv(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 Dc(oc({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=Ty(n,t,r);return a?eb(e,a):r instanceof Error&&r.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(r instanceof Error?r.message:String(r)))}}B(Gv,{DOMAIN_CHANGE_BATCH:()=>Vv,DOMAIN_CHANGE_BATCH_FLOOR:()=>Bv,createDomainHandler:()=>Zv,deleteDomainHandler:()=>eb,listDomainsHandler:()=>Yv,updateDomainHandler:()=>Xv});var tb=V({"src/tools/domains.ts"(){md(),xr(),Zy(),zc(),cl(),si(),Vy(),wl(),Om(),Vv=50,Bv=10}}),nb={};async function rb(e){try{const t=await ed(),{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 Rn(()=>t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null),wn);if(!a&&0===s.length){if(i)throw new Error(i);return Hc(dc("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 Bp(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=Fu(n);"passed"===e?t.passed++:"failed"===e?t.failed++:"blocked"===e?t.blocked++:t.not_run++}return t}(s),u=qp(s,await Rn(()=>t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),vn)),p=rp(s,u),m=c.filter(e=>p.has(e.id)).length,_=c.length,f={covered:m,uncovered:_-m,total:_,percent:kp(m,_),via_mitigation:fp(c.map(e=>e.id),p,ip(s,u))},h=await Np(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"===Fu(t)&&r++;return{requirements:new Set(t.map(e=>e.requirement_id)).size,test_cases:r}}(s,await Fp(t,e.project_id,p,h.releaseId)),g=new Map;for(const e of c){const t=e.domains.length>0?e.domains:["(untagged)"],n=p.has(e.id);for(const e of t){g.has(e)||g.set(e,{covered:0,total:0});const t=g.get(e);t.total++,n&&t.covered++}}const w=Array.from(g.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:kp(t.covered,t.total)})),v=new Date;v.setDate(v.getDate()-7);const b=!0===await jh(t,e.project_id),{count:j,error:k}=b?await t.from("project_changes").select("seq",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("committed_at",v.toISOString()):await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",v.toISOString());if(k)throw new Error(k.message);return Dc(oc({project_id:e.project_id,project_name:a??`Project ${e.project_id.slice(0,8)}`,counts:o,test_status:d,coverage:f,coverage_by_domain:w,rerun:y,rerun_scope:h.label,recent_changes:j??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(nb,{projectSummaryHandler:()=>rb});var ab=V({"src/tools/project-summary.ts"(){md(),fh(),$p(),Vp(),yp(),xr(),zc(),Dh(),sm()}}),ib={};async function sb(e){try{const t=await ed();let n,r;if(e.query&&e.query.trim().length>0){const a=await mh(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:Fu(e),domains:e.data?.tags?.domains??[],level:e.data?.tags?.level,req_type:e.data?.req_type})),r=a.totalCount}else{const a=await oh(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:Fu(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 Rn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null),wn),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 Dc(oc({items:n,filters:{domains:a.domains,levels:a.levels,types:Jp(await Bp(t,e.project_id))},project_id:e.project_id},lc(r,e.limit,e.offset)),{paging:{list:"items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(ib,{browseHandler:()=>sb});var ob,lb=V({"src/tools/browse.ts"(){md(),fh(),zc(),tp(),sm()}}),cb={};async function db(e){try{const t=e.direction??"downstream",n=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await ed(),a=await lh(r,e.project_id,e.item_id);if(!a)return Hc(dc("Item",e.item_id));const i=await Rn(()=>r.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null),wn),s=qp(i,await Rn(()=>r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),vn)),o=new Map;for(const e of i)o.set(e.id,{title:F_(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=P_(e,e=>o.get(e)?.type),r=n.type;"upstream"!==t&&"both"!==t||(M_.includes(r)&&c(n.from_id,n.to_id,r),T_.includes(r)&&c(n.to_id,n.from_id,C_[r]??r)),"downstream"!==t&&"both"!==t||(T_.includes(r)&&c(n.from_id,n.to_id,r),M_.includes(r)&&c(n.to_id,n.from_id,C_[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(;m.length>0&&u.length<ob;){const{id:e,depth:t,path:r}=m.shift();if(d.has(e))continue;if(null!==n&&t>n)continue;d.add(e);const a=o.get(e);if(a&&(u.push({item_id:e,title:a.title,type:a.type,depth:t,relationship_path:r,shared_variables:[]}),t>p&&(p=t),null===n||t<n))for(const n of l.get(e)??[])d.has(n.neighbor)||m.push({id:n.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:n.neighbor,relationship_type:n.relType}]})}let _=0;if(e.include_variable_refs){const t=await Rn(()=>r.from("project_variables").select("id, name").eq("project_id",e.project_id),jn),n=function(e,t,n){const r=new Map,a=t.find(t=>t.id===e);if(!a)return r;const i=Iv(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=Iv(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}if(u.length>=ob)break;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),y=$l(u,e.offset,e.limit);return Dc(oc({root:{item_id:e.item_id,title:h?.title??a.title,type:h?.type??a.type},impacted_items:y.rows,summary:{total_impacted:u.length,by_type:f,max_depth_reached:p,..._>0?{variable_impact_count:_}:{},...u.length>=ob?{truncated:!0}:{}}},y.meta),{paging:{list:"impacted_items"}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}B(cb,{impactAnalysisHandler:()=>db});var ub,pb,mb,_b,fb,hb,yb,gb,wb,vb,bb,jb,kb,Sb=V({"src/tools/impact-analysis.ts"(){md(),fh(),K_(),xr(),Mv(),Rl(),zc(),ob=200}});function Ab(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function $b(e){return null==e?"":String(e)}function Ib(e){if(null==e||""===e)return"null";if(Array.isArray(e))return 0===e.length?"null":`[${e.map(Ib).join(",")}]`;if("object"==typeof e){const t=e,n=Object.keys(t).filter(e=>"null"!==Ib(t[e])).sort();return 0===n.length?"null":`{${n.map(e=>`${JSON.stringify(e)}:${Ib(t[e])}`).join(",")}}`}return JSON.stringify(e)}function xb(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function qb(e){return null==e||""===e?null:e}function Ob(e,t=!0){const n=qb(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=>Ob(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)}:${Ob(r[e],t)}`).join(",")}}`}function Eb(e,t){return e.some(e=>!t.includes(e))||t.some(t=>!e.includes(t))}function Rb(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 Mb(e){const t=Object.prototype.hasOwnProperty.call(e,"parent"),n=Object.prototype.hasOwnProperty.call(e,"child");if(!t&&!n)return e.relationships;const r=xb(e.relationships);return{...r,parent:[...Rb(r.parent),...Rb(e.parent)],child:[...Rb(r.child),...Rb(e.child)]}}function Tb(e,t){const n=xb(e),r="parents"===t?n.parent:"children"===t?n.child:void 0;return Array.from(new Set([...Rb(n[t]),...Rb(r)])).sort()}function Cb(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){const e=xb(n);if("string"!=typeof e.date||!e.date.trim())continue;const r={};for(const t of yb){const n=qb(e[t]);null!==n&&(r[t]=n)}t.set(e.date,r)}return t}function Db(e,t){const n=Cb(e),r=Cb(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&&yb.every(e=>Ob(t[e])===Ob(a[e])))});return[Object.fromEntries(a.map(e=>[e,n.get(e)??null])),Object.fromEntries(a.map(e=>[e,r.get(e)??null]))]}function Hb(e,t){const n=[];qb(e.title)!==qb(t.title)&&n.push({path:"title"}),qb(e.type)!==qb(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 fb)qb(r[e])!==qb(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)?Eb(t,n):Ob(t)!==Ob(n))&&i("tags",e)}const l=xb(r.analysis_props),c=xb(a.analysis_props);for(const e of Array.from(new Set([...Object.keys(l),...Object.keys(c)])).sort())!ub.has(e)&&Ab(l[e])&&Ab(c[e])&&$b(l[e])!==$b(c[e])&&i("analysis_props",e);Ob(r.ownership)!==Ob(a.ownership)&&i("ownership");for(const e of hb)Eb(Tb(Mb(r),e),Tb(Mb(a),e))&&i("relationships",e);Object.keys(Db(r.runs,a.runs)[0]).length>0&&i("runs");for(const e of Array.from(new Set([...Object.keys(r),...Object.keys(a)])).sort())gb.has(e)||Ob(r[e],!1)!==Ob(a[e],!1)&&i(e);return n}function Nb(e,t){const n=Hb(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"),(Fb(e)||Fb(t)?qb(zb(e))!==qb(zb(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=xb(e),r=xb(t),a=[],i=xb(n.analysis_props),s=xb(r.analysis_props),o=Array.from(new Set([...Object.keys(i),...Object.keys(s)])).sort();for(const e of o){if(ub.has(e))continue;const t=i[e],n=s[e];Ab(t)&&Ab(n)?$b(t)!==$b(n)&&a.push(`analysis_props.${e}`):Ib(t)!==Ib(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(xb(n.fields)),d=l(xb(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 Fb(e){return"test-case"===e.type}function Pb(e){const t=xb(e.data);return Fb(e)?Vu(t):t.runs}function zb(e){const t=xb(e.data);return Fb(e)?Fu({type:"test-case",data:t})??null:t.status??null}function Ub(e,t){for(const[n,r]of Object.entries(e))if(n.toLowerCase()===t)return"string"==typeof r?r:null;return null}function Lb(e,t,n){const r=xb(e.data),a=xb(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:zb(e),to:zb(t)};else if("tags.level"===o)s[o]={from:xb(r.tags).level??null,to:xb(a.tags).level??null};else if("tags.domains"===o)s[o]={from:xb(r.tags).domains??null,to:xb(a.tags).domains??null};else if(o.startsWith("analysis_props.")){const e=o.slice(15);s[o]={from:xb(r.analysis_props)[e]??null,to:xb(a.analysis_props)[e]??null}}else if(o.startsWith("fields.")){const e=o.slice(7).toLowerCase();s[o]={from:Ub(xb(r.fields),e),to:Ub(xb(a.fields),e)}}else if("data"===o){const n=Hb(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=Fb(e)||Fb(t);for(const n of c){if("status"===n&&p)continue;const[s,o]="runs"===n?Vb(n,Pb(e),Pb(t),i,l):"relationships"===n?Vb(n,Mb(r),Mb(a),i,l):Vb(n,r[n],a[n],i,l);Ib(s)!==Ib(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 Wb(e,t){return null===e||"object"!=typeof e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).filter(([e])=>!t(e)))}function Vb(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[Wb(t,e),Wb(n,e)]}if("relationships"===e){const e=hb.filter(e=>a.has(`data.relationships.${e}`)),r=t=>Object.fromEntries(e.map(e=>[e,Tb(t,e)]));return[r(t),r(n)]}if("runs"===e)return Db(t,n);if("analysis_props"===e){const e=e=>r.has(`analysis_props.${e}`);return[Wb(t,e),Wb(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[Wb(t,e),Wb(n,e)]}return Array.isArray(t)&&Array.isArray(n)?function(e,t){const n={},r={},a=Bb(e),i=Bb(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;Ib(t)!==Ib(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++)Ib(e[a])!==Ib(t[a])&&(n[a]=e[a]??null,r[a]=t[a]??null);return[n,r]}(t,n):[t,n]}function Bb(e){const t=[];for(const n of e){const e=xb(n).id;if("string"!=typeof e||"order"===e)return null;t.push(e)}return new Set(t).size===t.length?t:null}function Jb(e){return"string"==typeof e?1:Array.isArray(e)?e.reduce((e,t)=>e+Jb(t),0):null!==e&&"object"==typeof e?Object.values(e).reduce((e,t)=>e+Jb(t),0):0}function Gb(e){const t=JSON.stringify(e,null,2),n=t.split("\n").length;return t.length+n*bb+vb*Jb(e.diff)+2}function Qb(e,t,n){if("string"==typeof e){if(e.length<=t+kb)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=>Qb(e,t,n)):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Qb(r,t,n)])):e}function Kb(e,t){const n=e.diff??{};for(const r of jb){const a={n:0},i=Qb(n,r,a),s={...e,diff:i,...a.n>0?{diff_clipped:!0}:{}};if(Gb(s)<=t)return s}const r={n:0},a=Qb(n,jb[jb.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(Gb(c)>t)break;o=r,l=c}return 0===l.diff_omitted&&delete l.diff_omitted,l}var Yb,Zb=V({"src/core/baseline-diff.ts"(){tp(),ub=new Set(["field_source","approved","approved_at","approved_by","approved_note"]),pb=["approval_state","approver_user_id","rev_label","approved_at","requires_impacted_approval"],mb=["id","title","type","metadata",...pb],_b=["parent","child"],fb=["body","summary","status","level","isLocked","lockedBy","lockedAt"],hb=["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"],yb=["result","by","note","asset"],gb=new Set(["tags","ownership","relationships","runs",...fb,...mb,..._b]),wb=2e4,vb=29,bb=6,jb=[1e3,400,160,60,20],kb=40}});function Xb(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 Yb){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 ej(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 tj,nj,rj,aj,ij=V({"src/core/restore-preview.ts"(){Yb=[{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"}]}}),sj={};function oj(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):null}async function lj(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 cj(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 dj(e,t,n){const{data:r,error:a}=await e.from("projects").select("org_id, deleted_at").eq("id",t).maybeSingle();if(a)return Hc(Ec(a.message));if(!r)return Hc(dc("Project",t));if(r.deleted_at)return Hc(Rr());const{data:i,error:s}=await e.from("organizations").select("feature_flags").eq("id",r.org_id).maybeSingle();return s?Hc(Ec(s.message)):!0!==(i?.feature_flags??{})[n]?Hc(cc(`Feature '${n}' is not enabled for this organization`,["Ask an org admin to enable the flag in Org Settings."])):null}async function uj(e){try{const t=await ed(),n=await async function(e,t){const{data:n,error:r}=await e.from("baselines").select("id, project_id, name, description, field_definitions_snapshot, snapshot_at, created_at, created_by, locked_at, locked_by, release_version, release_status").eq("project_id",t).is("deleted_at",null).order("snapshot_at",{ascending:!1}).order("id",{ascending:!1});if(r)throw new Error(`listBaselines: ${r.message}`);return n??[]}(t,e.project_id),r=Math.max(e.offset??0,0),a=Math.min(Math.max(e.limit??50,1),100);return Dc(oc({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},lc(n.length,a,r)),{paging:{list:"baselines"}})}catch(e){return oj(e)??Hc(xc(e,{read:!0}))}}async function pj(e){try{const t=await ed(),n=await dj(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?Hc(cc(`Baseline name "${e.name}" already exists in this project`,["Pick a different name"])):Hc(xc(a)):Dc(oc({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 oj(e)??Hc(xc(e))}}async function mj(e){try{const t=await ed(),n=await dh(t,e.baseline_id);if(!n)return Hc(dc("Baseline",e.baseline_id));const r=await dj(t,n.project_id,"baselines_enabled");if(r)return r;if(null!==n.locked_at)return Hc(cc("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 Hc(dc("Project",n.project_id));const{data:i,error:s}=await t.auth.getUser();if(Ht(s))return Hc(Nt());const o=i?.user?.id;if(!o)return Hc(fc());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 Hc(cc("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?Hc(xc(d)):Dc(oc({id:c.id,locked_at:c.locked_at,locked_by:c.locked_by}))}catch(e){return oj(e)??Hc(xc(e))}}async function _j(e){try{const t=await ed(),[n,r]=await Promise.all([dh(t,e.baseline_a_id),dh(t,e.baseline_b_id)]);if(!n||!r)return Hc(dc("Baseline","one of the baseline_ids"));if(n.project_id!==r.project_id)return Hc(cc("Both baselines must belong to the same project",["Verify both baseline_ids are from the same project_id"]));const[a,i]=await Promise.all([ph(t,n.project_id,An(n.id)),ph(t,r.project_id,An(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=Nb(t,n);r.length>0&&(p++,c.push({item_id:e,change_type:"modified",fields_changed:r}))}}const m=Math.max(e.offset??0,0),_=Math.min(Math.max(e.limit??50,1),200);let f=c.slice(m,m+_);const h={offset:m,limit:_,total:c.length};if(!0===e.detail){const e=function(e,t,n,r,a={}){const i=a.budget??wb,s=a.diffOf??Lb,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=Gb(e);if(l+a>i){if(o.length>0)break;e=Kb(e,i),a=Gb(e)}e.diff_clipped&&(c=!0),e.diff_omitted&&(d=!0),o.push(e),l+=a}if(o.length===e.length&&!c&&!d)return{items:o,pageInfo:{}};const u={returned:o.length,truncated:!0},p=[];return o.length<e.length&&(u.next_offset=r+o.length,p.push(`Response bounded to ${i} characters of items: returned ${o.length} of the ${e.length} items on this page. Call again with offset=${u.next_offset} for the rest, or omit detail to get only the names of the changed fields.`)),c&&p.push('Long values in an item were clipped to fit, each marked "[clipped, N more characters]".'),d&&p.push("diff_omitted counts the changed fields of an item whose values did not fit; their names are still in fields_changed."),(c||d)&&p.push("Compare the two snapshots in the app to see every value in full."),u.truncation_message=p.join(" "),{items:o,pageInfo:u}}(f,s,o,m);f=e.items,Object.assign(h,e.pageInfo)}return Dc(oc({summary:{added:d,removed:u,modified:p,total_compared:l.length},items:f,page_info:h,baselines:{a:{id:n.id,name:n.name,snapshot_at:n.snapshot_at},b:{id:r.id,name:r.name,snapshot_at:r.snapshot_at}}}),{paging:{list:"items",resume:e=>({data:{page_info:{...h,returned:e,next_offset:m+e,truncated:!0}},next:`offset=${m+e}`})}})}catch(e){return oj(e)??Hc(xc(e,{read:!0}))}}async function fj(e,t){let n;try{const o=await ed(),l=await dh(o,e.baseline_id);if(!l)return Hc(dc("Baseline",e.baseline_id));const c=await dj(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 Hc(dc("Project",l.project_id));const{data:u,error:p}=await o.auth.getUser();if(Ht(p))return Hc(Nt());const m=u?.user?.id;if(!m)return Hc(fc());const{data:_}=await o.from("org_members").select("role").eq("user_id",m).eq("org_id",d.org_id).maybeSingle();if(!_||"admin"!==_.role)return Hc(cc("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 Hc(cc("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 Oy(o,l.project_id);if("unreadable"===h)return Ey();n=h;const y=await ph(o,l.project_id,An(l.id)),g=await Hn(y.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}]})}(y,g),v=await Dn(o,l.project_id,An(l.id)),b={tool:"atoms_restore_baseline",project_id:l.project_id,target:l.id},j=By(b.tool,l.project_id);if(j&&!0===e.confirm&&e.confirmation_token){const t=Gy(e.confirmation_token,b);if(!t.valid)return Hc(_c(`confirmation_token rejected: ${t.reason}`))}if(!0!==e.confirm||j&&!e.confirmation_token){const e="ops"===h?await na(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=j?Jy(b):null;return Dc(oc({...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,tj).map(e=>({id:e.id,type:e.type,title:e.title,changed_fields:e.diff_summary?.changed_fields??[]})),...w.length>tj?{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?Hc(_c("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.",nj)):await async function(e,t){const n=Date.now();let r=t.bulkId??ka(),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=pi(e),m=p&&t.bulkId?await async function(e,t,n,r=ri){try{if(!e.supabaseUrl||!e.accessToken||!n)return null;const a=e.fetch??fetch,i=await a(`${ui(e,t,n)}&seq=not.is.null&select=seq&order=seq.desc&limit=1`,{method:"GET",headers:li(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 Tl(()=>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:aj}),El);if(p&&Ml(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<rj)}finally{p&&mi(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=`${ui(e,t,n)}&item_id=not.is.null`+(null!==s?`&seq=gt.${s}`:"")+`&select=seq,kind,item_id,path&order=seq.asc&limit=${ni}`,o=await a(r,{method:"GET",headers:li(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(l.length<ni||!Number.isFinite(c))break;s=c}const o=di(i);o.length>0&&await ci(e,t,o)}catch(e){console.error("[embed-on-save] embed failed:",e instanceof Error?e.message:e)}}(p,t.projectId,r,m))}const _=ej({items_restored:o.restored,items_trashed:o.trashed,variables_archived:o.archived}),f=function(e,t=[],n=!1){return[Xb(e,"item"),Xb(t,"variable"),n?"The field definitions were left as someone changed them after the preview.":""].filter(Boolean).join(" ")}(c,d,l),h=f?` ${f}`:"",y=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 Dc(oc({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:y}))}(o,{baselineId:l.id,projectId:l.project_id,userId:m,sourceSeq:e.source_seq,bulkId:e.bulk_id,afterId:e.after_id});const k=await lj(o,{baselineId:l.id,projectId:l.project_id,userId:m});return function(e,t,n){const r=pi(e);r&&0!==n.length&&mi(ci(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&&oi(e.data)===oi(t.data)||r.add(t.id)}return[...r]}(y,g)),Dc(oc({ok:!0,items_restored:k.items_restored,variables_restored:k.variables_restored,field_definitions_restored:k.field_definitions.length,items_trashed:k.items_trashed,variables_archived:k.variables_archived,summary:ej(k)}))}catch(r){const a=Ty(n,t,r);return a?fj(e,a):oj(r)??Hc(xc(r))}var r,a,i,s}B(sj,{RESTORE_CALL_BUDGET_MS:()=>rj,createBaselineHandler:()=>pj,diffBaselinesHandler:()=>_j,listBaselinesHandler:()=>uj,lockBaselineHandler:()=>mj,restoreBaselineHandler:()=>fj,restoreBaselineStateAtomicallyViaMain:()=>lj,syncRestoredItemRelationships:()=>cj});var hj,yj,gj,wj,vj=V({"src/tools/baselines.ts"(){md(),si(),Ul(),Vy(),zt(),Rk(),zc(),fh(),Cp(),Zb(),ij(),Zy(),xr(),bi(),tj=200,nj=400,rj=2e4,aj=200}});function bj(e){return"string"==typeof e}function jj(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:bj(n.by)?n.by:null,on:bj(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:bj(e.by)?e.by:"",on:bj(e.on)?e.on:"",count:"number"==typeof e.count&&Number.isFinite(e.count)?e.count:0})):[]}}}function kj(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>gj)return{ok:!1,error:`scenario_catalogs accepts at most ${gj} 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(!bj(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),!bj(e.name)||!e.name.trim())return{ok:!1,error:`catalog "${e.id}" must carry a non-empty name`};if(e.name.length>yj)return{ok:!1,error:`catalog "${e.id}" name must be at most ${yj} characters`};if(!Array.isArray(e.entries))return{ok:!1,error:`catalog "${e.id}" entries must be an array`};if(e.entries.length>hj)return{ok:!1,error:`catalog "${e.id}" accepts at most ${hj} 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(!bj(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=bj(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>yj)return{ok:!1,error:`an entry of catalog "${e.id}" must be at most ${yj} characters`};const s=Array.isArray(n.function_tags)?n.function_tags.filter(bj).map(e=>e.trim()).filter(Boolean):[],o=Array.isArray(n.function_ids)?n.function_ids.filter(bj).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=jj(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 Sj,Aj=V({"src/core/catalogs.ts"(){hj=50,yj=100,gj=200,wj=["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]}}),$j={};function Ij(e){return"safety-goal"===e?"hara":"failure-mode"===e?"dfmea":null}function xj(e){const t=e?.relationships?.mitigated_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function qj(e){const t=e?.relationships?.verified_by;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}function Oj(e){return JSON.parse(JSON.stringify(e??{}))}async function Ej(e,t,n,r){const a=await Sm(n,Object.keys(r),()=>Bp(e,t));if(a)return{ok:!1,result:Hc(_c(a,Yl))};if(!(Zp in r))return{ok:!0,rest:r,writes:{},answer:{}};const{[Zp]: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 Bp(e,t);if(!r&&"tags"===a)return{ok:!1,error:{status:"error",message:rm,next_steps:[...am],code:"function_items_off",retryable:!1}};const i=await wm(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:Hc(o.error)}}async function Rj(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 ao(n)}function Mj(e){const t=e?.relationships?.parents;return Array.isArray(t)?t.filter(e=>"string"==typeof e)[0]??null:null}function Tj(e){return Hc("tool"===e.kind?e.error:_c(e.message,Yl))}function Cj(e,t,n){return m_(t,n).map(t=>({op_id:ka(),kind:t.kind,item_id:e,path:[...t.path],value:t.value}))}async function Dj(e,t,n,r){const a=Mj(r);if(!a)return!1;const i=await lh(e,t,a);return w_(n,i?.data)}async function Hj(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:io(n,a,a?null:await Rj(e,t))}}async function Nj(e,t,n,r){const a=Mj(r),i=a?await lh(e,t,a):null;return Hj(e,t,n,i?.data)}function Fj(e,t,n,r={}){const a=r.where?`${r.where}: `:"",i=function(e,t){const n=bs[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([...vs[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=>Gs.includes(e));if(l.length>0)return{ok:!1,message:`${a}${Uo(e,l)}`};const c=Lo(e);if(c&&o.includes(c.field))return{ok:!1,message:`${a}${Wo(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=ws[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=po(t,r,i);if(e)return{ok:!1,message:`${a}${e}`};p[r]=i}}return{ok:!0,writes:p}}async function Pj(e,t){let n;const r=mm("atoms_create_analysis",e);if(r)return Hc(r);try{const r=await ed(),i=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const s=t??await Oy(r,e.project_id);if("unreadable"===s)return Ey();n=s;const o="string"==typeof(a=e.subtype)&&Object.prototype.hasOwnProperty.call(Cs,a)?Cs[a]:null;if(!o)return Hc(_c(function(e){return`subtype must be one of: ${Ds.join(", ")} (got ${JSON.stringify(e)})`}(e.subtype)));const l=e.source_req_ids??[],c=e.source_function_ids??[],d=(e.source_assets??[]).map(e=>Mc(e));if("hara"===o&&l.length>0)return Hc(_c("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 Hc(_c("source_function_ids and source_assets apply to hara only; seed a DFMEA with source_req_ids"));if(l.length>50)return Hc(_c("source_req_ids supports at most 50 entries per call"));if(c.length>im||d.length>im)return Hc(_c(`source_function_ids and source_assets support at most ${im} 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 Hc(dc("Source requirement(s)",i.join(", ")));const s=l.filter(e=>{const t=a.get(e);return"requirement"!==t.type||Sj.has(t.data?.req_type)});if(s.length>0)return Hc(_c(`source_req_ids must reference plain requirements (type='requirement', not analysis rows): ${s.join(", ")}`))}if(void 0!==e.variant&&!So(e.subtype).includes(e.variant))return Hc(_c(function(e,t){const n=So(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 Rj(r,e.project_id),p=e.variant??function(e,t){return"medical"===t?Ns[e]:Hs[e]}(e.subtype,u),m=await async function(e,t,n,r){const a=n??"automotive";return ji(a).includes(r)||"automotive"===a&&await ki(e,t,a)?null:function(e,t){return`Cannot create a ${hi[t]}: this project's industry is ${yi[e]}, which offers ${function(e){const t=e.map(e=>hi[e]);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}(ji(e))}. Analyses already in the project keep working. Create one of the offered analyses instead, or change the industry on the project settings page (allowed while no analysis in the project would end up outside the new industry).`}(a,r)}(r,e.project_id,u,p);if(m)return Hc(_c(m,Yl));const _=io(o,p),f=so(_),h=_o(_),y={},g=[];for(const t of[...js,...Is]){const n=e[t];"string"==typeof n&&""!==n&&(g.push(t),h.includes(t)&&(y[t]=Mc(n)))}const w=g.filter(e=>!h.includes(e));if(w.length>0)return Hc(_c(vo(_,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=>om(e)===om(t))&&i.push(t)}if("security_tir57"===n)return a?{ok:!1,error:Am("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(!km(n))return a||i.length>0?{ok:!1,error:Am(`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:Am(`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 ${Kp}`])};if(!a)return{ok:!0,seeds:[]};const s=await gm(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:c,assets:d});if(!t.ok)return Hc(t.error);v=t.seeds}const b="hara"===o?v:l.map(e=>({text:e,functionId:null})),j=l_({...void 0!==e.hazard_id?{hazard_id:e.hazard_id}:{},...void 0!==e.goal_id?{goal_id:e.goal_id}:{}});if(j.error)return Hc(_c(j.error));let k=!1;if("hara_iso26262"===_&&("ops"===s||c_(j.picks))){const t=await i_(r,e.project_id);if(null===t)return Hc(s_(null));if(k=function(e,t){return"hara_iso26262"===e&&null!==t&&null===Si(t)}(_,t),!k&&c_(j.picks))return Hc(s_(t))}const S=await __(r,e.project_id,"atoms_create_analysis",_,k,j.picks,null,t=>lh(r,e.project_id,t));if(S)return Tj(S);if("ops"===s)return await async function(e){const{client:t,projectId:n,subtype:r,schemeId:a,seeds:i}=e,s=qs[r],o=Es[a],l=ko(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?bm(e):{source_req:e.text},u=f_(null,e.picks),p=[Ea({type:"analysis",title:e.title,fields:{...c,...u}}),...i.map(e=>Ea({type:"requirement",title:"",req_type:s,fields:{...d(e),...u}}))],m=await Ny({projectId:n,tool:"atoms_create_analysis",key:e.key,contents:p}),_=await Ga(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 y=Object.keys(f).length>0?Iy(await xy(t,n,f)):null,g=_.get(m.create[0])?.item_id??y(o),w=m.create.slice(1).map(e=>_.get(e)?.item_id??y(l)),v=[{op_id:m.create[0],kind:"create_item",item_id:g,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,...bm(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:g,path:["relationships","children"],value:e})});for(const t of w)v.push(...Cj(t,null,e.picks));const b=await Ry({client:t,projectId:n,ops:Fy(v,m),preFound:_,labels:Uj(a)}),j=m.create.map(e=>b.answers.find(t=>t.op_id===e)),{tokens:k,unread:S}=await Py(t,n,j.filter(e=>!!e)),A=j[0]?.item_id??g,$=i.map((t,n)=>{const a=j[n+1]?.item_id??w[n];return{..."hara"===r?jm(a,t):{id:a,source_req:t.text},...c_(e.picks)?f_(null,e.picks):{},...k.get(a)?{base_token:k.get(a)}:{}}});return My(b.outcome,{id:A,subtype:r,title:e.title,revision:e.revision,scheme:a,variant:e.variant,labels:g_(a,e.stamp?"hazard_goal":"legacy"),...e.stamp?{event_model:"hazard_goal"}:{},...e.schemeStandard?{standard:e.schemeStandard}:{},...k.get(A)?{base_token:k.get(A)}:{},rows:$,...b.outcome.replayed?{message:Sr}:{},...S?{warning:nr}:{}},b)}({client:r,projectId:e.project_id,userId:i,subtype:o,schemeId:_,variant:p,schemeStandard:f,scopeInput:y,seeds:b,title:e.title??`New ${Vo(_).parent}`,revision:e.revision??"1.0",key:e.idempotency_key,stamp:k,picks:j.picks});const A=async()=>{const t=Es[_],n=ko(_,"legacy"),a={[t]:1};a[n]=(a[n]??0)+b.length;const s=Iy(await xy(r,e.project_id,a)),l=s(t),c=`New ${Vo(_).parent}`,d=e.title??c,u=e.revision??"1.0",m=qs[o],h=(new Date).toISOString(),g={id:l,type:"analysis",title:d,body:"",tags:{domains:[],level:""},ownership:{primary:null,additional:[]},relationships:{parents:[],children:[],related:[],verifies:[],verified_by:[]},links:[],analysis:{subtype:o,scheme:_,revision:u,...f?{standard:f}:{}},analysis_props:{variant:p,...y},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:g,p_user_id:i,p_event_source:"mcp",p_event_session_id:qk()??null,p_diff_summary:null});if(w)throw new Error(w.message);const v=(e,t)=>"hara"===o?jm(e,t):{id:e,source_req:t.text},j=[],k=[];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,...bm(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:qk()??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`),k.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:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),j.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:g,actor:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Dc(oc({id:l,subtype:o,title:d,revision:u,scheme:_,variant:p,labels:Vo(_),...f?{standard:f}:{},rows:j,...k.length>0?{link_warnings:k,warning:`${k.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=Ty(n,t,r);return a?Pj(e,a):Hc(xc(r))}var a}function zj(e){for(const t of Object.keys(e)){const n=e[t];"string"==typeof n&&(e[t]=Mc(n))}}function Uj(e){const t=new Map(Ao(e).map(e=>[e.key,e.label]));return{analysisLabel:e=>t.get(e)??null}}function Lj(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 Wj(e,t,n){const r=n.data,a=new Map;for(const n of xj(r)){const r=await lh(e,t,n);r&&a.set(n,r)}const i=await cp(e,t,{id:n.id,type:n.type,data:r},[...a.values()]),s=[];for(const r of i){const a=await lh(e,t,r);a?.data?.asil_source===n.id&&s.push(r)}return s}async function Vj(e,t){let n;try{const s=await ed(),o=ad();try{await cd(s,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const l=t??await Oy(s,e.project_id);if("unreadable"===l)return Ey();n=l;const c=await lh(s,e.project_id,e.row_id);if(!c)return Hc(dc("Analysis row",e.row_id));const d=c.data;if("goal"===c.type){const t=h_(Object.keys(e.fields??{}));if(t.length>0)return Hc(_c(y_(c.id,t),Yl))}if("analysis"===c.type)return async function(e,t,n,r,a,i,s){const{schemeId:o}=await Hj(e,n,function(e){return"dfmea"===e?.analysis?.subtype?"dfmea":"hara"}(a),a),l=function(e,t){const n=_o(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,Ji.includes(t)||Gi.includes(t);var t});if(a.length>0)return{ok:!1,message:Yi(a)};const i=r.filter(e=>!n.includes(e));if(i.length>0)return{ok:!1,message:vo(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=fo(e);if("overall_residual_risk"===n&&""!==r&&!a.includes(r))return{ok:!1,message:bo(n,r,a)};if("software_safety_class"===n&&""!==r&&!$s.includes(r))return{ok:!1,message:bo(n,r,$s)};s[n]=r}return{ok:!0,writes:s}}(o,i);if(!l.ok)return Hc(_c(l.message));const c=l.writes;if(zj(c),s){const{ops:t,refusals:i}=await Hy({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 Ry({client:e,projectId:n,ops:t,refusals:i,labels:Uj(o)}),d={...a.analysis_props??{},...c};return My(l.outcome,{analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:yo(d),overall:go(d,fo(o))},l)}return await(async()=>{const i=Oj(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:qk()??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:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),Dc(oc({analysis_id:r.id,scheme:o,written_fields:Object.keys(c),scope:yo(s),overall:go(s,fo(o))}))):Hc(cc(`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:Cy(e.base_token)}:void 0);const u=Ij(d?.req_type);if(!u)return Hc(_c(k_(e.row_id,c.type,"atoms_fill_row"),Yl));const{schemeId:p}=await Nj(s,e.project_id,u,d),m=await Sm(p,Object.keys(e.fields??{}),()=>Bp(s,e.project_id));if(m)return Hc(_c(m,Yl));const{[Zp]:_,...f}=e.fields??{},h=l_(f);if(h.error)return Hc(_c(h.error));const y=h.rest,g=void 0!==_,w=c_(h.picks),v=(g||w)&&0===Object.keys(y).length?{ok:!0,writes:{}}:Fj(p,u,y,{extraKeys:"hara"===u?["effect","title"]:["effect"]});if(!v.ok)return Hc(_c(v.message));const b=v.writes;zj(b);const j=p_(c.id,d?.relationships,Object.keys(b),h.picks);if(j)return Hc(_c(j,Yl));if(w){const t=await __(s,e.project_id,c.id,p,await Dj(s,e.project_id,p,d),h.picks,d?.relationships,t=>lh(s,e.project_id,t));if(t)return Tj(t)}let k={};if(g){const t=await Ej(s,e.project_id,p,{[Zp]:_});if(!t.ok)return t.result;Object.assign(b,t.writes),k=t.answer}const S=d?.analysis_props??null;if("ops"===l){const{ops:t,refusals:n}=await Hy({client:s,projectId:e.project_id,itemId:c.id,tokens:Cy(e.base_token),cells:Lj(u,b)}),o=Cj(c.id,d?.relationships,h.picks),l=await Ry({client:s,projectId:e.project_id,ops:[...t,...o],refusals:n,labels:Uj(p)}),m={...S??{}};for(const[e,t]of Object.entries(b))"effect"!==e&&"title"!==e&&(m[e]=t);const _=Object.keys(b).length>0&&tl({...m})||(r=S,a=d?.relationships,i=h.picks,!0===r?.approved&&m_(a,i).length>0),f=Fo(p,m),y=Rm(d?.relationships,"event_goal").length>0||void 0!==h.picks.event_goal,g=0===l.outcome.not_applied.length&&"hara_iso26262"===p?[...new Set([...await Wj(s,e.project_id,c),...y?await I_(s,e.project_id,(await lh(s,e.project_id,c.id))?.data?.relationships,t=>lh(s,e.project_id,t)):[]])].sort():[];return My(l.outcome,{row_id:c.id,subtype:u,written_fields:Object.keys(b),written_columns:$o(p,Object.keys(b)),computed_level:f,..."hara_iso26262"===p?{asil_propagated_to:g}:{},..._?{approval_cleared:!0}:{},acceptance_revoked:Dy(l.answers),...k,...w?f_(d?.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]&&m_(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 Dc(oc({row_id:c.id,subtype:u,written_fields:[],written_columns:[],computed_level:Fo(p,S),..."hara_iso26262"===p?{asil_propagated_to:[]}:{},acceptance_revoked:!1,...k,...w?f_(d?.relationships,h.picks):{}}));const n=Oj(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=tl(r),l=(new Date).toISOString();n.metadata={...n.metadata??{},updated_at:l,updated_by:o};const m=Fo(p,r),_=Fo(p,S),f=[];if("hara_iso26262"===p&&function(e,t,n){return t!==ds&&(t!==n||e.some(e=>Yu.includes(e)))}(Object.keys(b),m,_)){const t=new Map;for(const r of xj(n)){const n=await lh(s,e.project_id,r);n&&t.set(r,n)}const r=await cp(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 lh(s,e.project_id,n);r&&dp(r.data,c.id,m,m!==_)&&f.push(r)}}const{data:y,error:g}=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:qk()??null,p_diff_summary:null,p_expected_updated_at:c.updated_at});if(g)throw new Error(g.message);if(!y)return Hc(cc(`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:Ok(),session_id:qk(),...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=Mj(d),j=v?await ns(v,"The row was",{readParent:()=>lh(s,e.project_id,v),saveParent:(t,n)=>Tl(()=>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:qk()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at})),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},A=j.revoked,$=[],I=[];for(const t of f){const n=t.data,r=n?.asil??null,a=n?.asil_source??null,i=Oj(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:qk()??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:Ok(),session_id:qk(),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`),I.push(t.id))}const x=[j.warning,I.length>0?(q=c.id,O=I,`${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 Dc(oc({row_id:c.id,subtype:u,written_fields:Object.keys(b),written_columns:$o(p,Object.keys(b)),computed_level:m,...$.length>0?{asil_propagated_to:$}:{},...I.length>0?{asil_propagation_failed:I}:{},...i?{approval_cleared:!0}:{},acceptance_revoked:A,...x.length>0?{warning:x.join(" ")}:{},...k,...w?f_(d?.relationships,h.picks):{}}))};return await A()}catch(r){const a=Ty(n,t,r);return a?Vj(e,a):Hc(xc(r))}var r,a,i}function Bj(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 Jj(e,t,n,r=!1){const a=await lh(e,t,n);if(!a)return{ok:!1,result:Hc(dc("Analysis",n))};if("analysis"!==a.type)return{ok:!1,result:Hc(_c(`Item ${n} is not an analysis (type='${a.type}')`))};const i=a.data,s=Ij("hara"===i?.analysis?.subtype?"safety-goal":"dfmea"===i?.analysis?.subtype?"failure-mode":null);if(!s)return{ok:!1,result:Hc(_c(`Analysis ${n} is missing a valid analysis.subtype`))};const o=qs[s],{variant:l,schemeId:c}=await Hj(e,t,s,i),d=w_(c,i),u=Array.isArray(i?.relationships?.children)?i.relationships.children.filter(e=>"string"==typeof e):[],p=r?await ea(e,t,[a.id,...u]):new Map;let m=[];if(u.length>0){const{data:n,error:r}=await e.from("items").select("*").eq("project_id",t).is("deleted_at",null).in("id",u);if(r)throw new Error(r.message);const a=new Map((n??[]).filter(e=>!e.deleted_at&&u.includes(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 xj(e.data))_.add(t);for(const t of qj(e.data))_.add(t);for(const t of Mm(e.data?.relationships))_.add(t)}const f=new Map,h=new Map;let y=[];if(_.size>0){const{data:n,error:r}=await e.from("items").select(Bu).eq("project_id",t).is("deleted_at",null).in("id",[..._]);if(r)throw new Error(r.message);y=n??[];for(const e of y)f.set(e.id,e.updated_at),h.set(e.id,e.content_changed_at??e.updated_at)}const g=m.length>0?lp(m,[...y,...await op(e,t)]):new Map,w=await vm(e,t,function(e){return fm(e.map(e=>lm(e).source_function_id))}(m.map(e=>({analysis_props:e.data?.analysis_props??null})))),v=d?await $_(e,t):null,b=v?A_(v):null,j="security_tir57"===c?await async function(e,t,n){const r=e=>up(e.data?.relationships?.affects),a=[...new Set(n.flatMap(r))];if(0===a.length)return new Set;const i=await Hn(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,k=new Map,S=m.map(e=>{const t=e.data?.analysis_props??{},n=g.get(e.id)??[],r=xj(e.data).filter(e=>f.has(e)),a=qj(e.data).filter(e=>f.has(e)),i=n.length>0,s=Fo(c,t),o=Mm(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=Ro(t);return"QM"===e||e===ds?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=Co(t);return"Low"!==e&&e!==ds?`${e.toLowerCase()} risk uncontrolled`:null}if("security_tir57"===e){const e=Ho(t);return Bi(e)?`${e.toLowerCase()} security risk uncontrolled`:null}const a=parseInt(Fo(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);k.set(e.id,{props:t,affectsLinked:j.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:qo(c,s),is_gap:null!==u,gap_rule:u,is_critical:Po(c,t,i,d),is_stale:zo(t,r,e=>(l.has(e)?h.get(e):f.get(e))??null,um({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?Do(t):"security_tir57"===c?No(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 vs[c])p[e]=t[e]??null;return Object.assign(p,function(e,t){const n=cm(lm(e).source_function_id).trim();if(!n)return{};const r=dm(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{...v_(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:so(c)??null,variant:l,labels:g_(c,d?"hazard_goal":"legacy"),...d?{event_model:"hazard_goal"}:{},acceptability:xo(c),definitions:Io(c),control_types:Jo(c),field_labels:Ao(c),scope:_o(c).length>0?yo(i?.analysis_props):null,overall:_o(c).length>0?go(i?.analysis_props,fo(c)):null,threat_model:"security_tir57"===c?Bj(i?.analysis_props):null,acceptance:Xi(i?.analysis_props)},schemeId:c,parentProps:i?.analysis_props??null,revisions:p,rows:S,gapFacts:k,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 Gj(e){try{return await async function(e,t=fl){let n;const r=new Promise((e,r)=>{n=setTimeout(()=>r(new gl(t)),t)});try{return await Promise.race([e(),r])}finally{clearTimeout(n)}}(()=>async function(e){const t=await ed(),n=!0===await Ha(t,e.project_id),r=await Jj(t,e.project_id,e.analysis_id,n);if(!r.ok)return r.result;const a=$l(r.rows,e.offset,e.limit),i={paging:{list:"rows"}};if(!n)return Dc(oc({analysis:r.analysis,rows:a.rows,counts:r.counts},a.meta),i);const s=async e=>{const t=r.revisions.get(e);return t?Qr(t,"analysis"):void 0},o=new Map(Ao(r.schemeId).map(e=>[e.key,e.label])),l=await ra(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 Dc(oc({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 Hc(xc(e,{read:!0}))}}async function Qj(e,t,n,r){const a=Mj(n);if(!a)return;const i=await lh(e,t,a);if(!i)return;const{revoked:s,parentProps:o}=ts(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:qk()??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 Kj(e,t,n,r){return!0===r?.analysis_props?.approved&&Hw(r,await lh(e,t,n))}async function Yj(e,t){let n;try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();if(n=i,e.row_id===e.req_id)return Hc(_c("row_id and req_id must be different items"));const s=await lh(r,e.project_id,e.row_id);if(!s)return Hc(dc("Analysis row",e.row_id));const o=s.data;if("goal"===s.type)return await Zj(r,e,s,i,null);const l=Ij(o?.req_type);if(!l)return Hc(_c(k_(e.row_id,s.type,"atoms_link_mitigation"),Yl));if("remove"!==e.action&&Rm(o?.relationships,"event_goal").length>0){const{schemeId:t}=await Nj(r,e.project_id,l,o),n=await Dj(r,e.project_id,t,o),a=n?await lh(r,e.project_id,Rm(o?.relationships,"event_goal")[0]):null,c=function(e,t,n){if(!e)return null;const r=Rm(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 Zj(r,e,a,i,s.id)}const c=await lh(r,e.project_id,e.req_id);if(!c)return Hc(dc("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 Hc(_c(Zu));if(!pp(e.row_id,o,e.req_id,d))return Hc(_c(mp(e.row_id,e.req_id),Yl));const{schemeId:t}=await Nj(r,e.project_id,l,o);if("ops"===i){const n={op_id:ka(),kind:"remove",item_id:e.row_id,path:["relationships","mitigated_by"],value:e.req_id},a=await Ry({client:r,projectId:e.project_id,ops:[n],labels:Uj(t)});return My(a.outcome,{row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,...await Kj(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},acceptance_revoked:Dy(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:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await Qj(r,e.project_id,o,a);const i=await lh(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=Oj(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:qk()??null,p_diff_summary:null,p_expected_updated_at:i.updated_at});if(n)throw new Error(n.message)}return Dc(oc({row_id:e.row_id,req_id:e.req_id,type:"mitigated_by",action:"remove",scheme:t,...await Kj(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{}}))};return await n()}if("requirement"!==c.type||Sj.has(d?.req_type))return Hc(_c(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${e.req_id}`));const{schemeId:u}=await Nj(r,e.project_id,l,o);if(Go(u)&&d?.req_type!==ss)return Hc(_c(Qo(e.req_id,u)));const p=Bo(u);if(0===p.length&&void 0!==e.control_type)return Hc(_c(Ko(u)));if(p.length>0&&!e.control_type)return Hc(_c(Yo(u)));if(!(void 0===e.control_type||oo(e.control_type)&&function(e,t){return Bo(e).some(e=>e.id===t)}(u,e.control_type)))return Hc(_c(Yo(u)));if("dfmea"===l&&!e.role)return Hc(_c(`role is required for dfmea mitigation links. Choose one of: ${us.join(", ")}`));if("hara"===l&&e.role)return Hc(_c("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:ka(),kind:"add",item_id:e.row_id,path:["relationships","mitigated_by"],value:n},i=await Ry({client:r,projectId:e.project_id,ops:[a],labels:Uj(u)});return My(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 Kj(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{},acceptance_revoked:Dy(i.answers)},i)}const m=async()=>{let t=ds;if("hara_iso26262"===u){t=Fo(u,o?.analysis_props);const r=d?.asil;if(t!==ds&&"string"==typeof r&&r.length>0&&r!==t&&!0!==e.override)return Hc((i=t,{...cc(`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:c.updated_at,p_role:m});if(_)throw new Error(_.message);let f,h;if(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:Ok(),session_id:qk()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),await Qj(r,e.project_id,o,a),e.control_type&&oo(e.control_type)){const t=await lh(r,e.project_id,e.row_id)??s,n=Oj(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:qk()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at});if(l)throw new Error(l.message);f=e.control_type}if("hara_iso26262"===u&&t!==ds){const n=await lh(r,e.project_id,e.req_id);if(n){const i=n.data,o=i?.asil??null,l=i?.asil_source??null,c=Oj(i);c.asil=t,c.asil_source=s.id;const d=(new Date).toISOString();c.metadata={...c.metadata??{},updated_at:d,updated_by:a};const{error:u}=await 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:c,p_user_id:a,p_event_source:"mcp",p_event_session_id:qk()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at});if(u)throw new Error(u.message);await r.from("change_history").insert({item_id:n.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{asil:o,asil_source:l},new_data:{asil:t,asil_source:s.id},actor:Ok(),session_id:qk(),reason:!0===e.override?`ASIL override accepted via atoms_link_mitigation (was '${o??"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 Dc(oc({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 Kj(r,e.project_id,e.row_id,o)?{approval_cleared:!0}:{}}))};return await m()}catch(r){const a=Ty(n,t,r);return a?Yj(e,a):Hc(xc(r))}}async function Zj(e,t,n,r,a){const i="hara_iso26262";if(void 0!==t.role)return Hc(_c("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 Hc(_c(Ko(i)));if(t.req_id===n.id)return Hc(_c("row_id and req_id must be different items"));const s=await lh(e,t.project_id,t.req_id);if(!s)return Hc(dc("Requirement",t.req_id));const o=s.data,l="remove"===t.action?"remove":"add";if("remove"===l){if(void 0!==t.override)return Hc(_c(Zu));if(!pp(n.id,n.data,t.req_id,o))return Hc(_c(mp(n.id,t.req_id),Yl))}else{if("requirement"!==s.type||Sj.has(o?.req_type))return Hc(_c(`req_id must reference a plain requirement (type='requirement', not an analysis row): ${t.req_id}`));if(Go(i)&&o?.req_type!==ss)return Hc(_c(Qo(t.req_id,i)))}if("ops"!==r)return Hc(Ti());const c={op_id:ka(),kind:l,item_id:n.id,path:["relationships","mitigated_by"],value:t.req_id},d=await Ry({client:e,projectId:t.project_id,ops:[c],labels:Uj(i)}),u=await lh(e,t.project_id,t.req_id),p=u?.data??{};return My(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:Dy(d.answers)},d)}async function Xj(e){try{const n=await ed(),r=await Jj(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=lo(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=el(r.schemeId).some(e=>"requirement"===e.scope)?await async function(e,t,n){const r=(await Rn(()=>e.from("items").select("id, data").eq("project_id",t).is("deleted_at",null).eq("type","requirement"),wn)).filter(e=>e.data?.req_type===ss&&function(e,t){const n=co(e);return n.length>0&&n===co(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 Hn([...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??ds,severity:Zo(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=kj(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:wo(e),overallJudged:""!==go(e,a?Ni:As).residual_risk,everyRowSettled:t.every(e=>e.linked&&e.residualLevel!==ds),catalogsDraft:r,accepted:"accepted"===e?.acceptance_state}}(r.parentProps,o,r.schemeId,l),d=await async function(e,t,n,r){if(!km(n))return[];if("items"!==await Bp(e,t))return[];const a=await Rn(()=>e.from("items").select("id, type, title").eq("project_id",t).eq("type","function").is("deleted_at",null),wn),{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(!km(e))return[];const a=new Map(n.map(e=>[e.id,e])),i=new Set,s=[];for(const n of t){const t=dm(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=[...nl(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!==ds&&"QM"!==e&&Em(e)>0,r=[],a=[],i=[],s=new Map,o=[],l=new Set;for(const c of t){const t=Ro(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,Ro(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,S_(n))).map(e=>{const t=no.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 Dc(oc({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 Hc(xc(e,{read:!0}))}var t}async function ek(e,t){let n;const r=mm("atoms_propose_rows",e);if(r)return Hc(r);try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();n=i;const s=await lh(r,e.project_id,e.analysis_id);if(!s)return Hc(dc("Analysis",e.analysis_id));if("analysis"!==s.type)return Hc(_c(`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 Hc(_c(`Analysis ${e.analysis_id} is missing a valid analysis.subtype`));const{variant:d,schemeId:u}=await Hj(r,e.project_id,c,o);if("hara"===c&&e.source_req)return Hc(_c("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 Hc(_c("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 Hc(_c("rows must contain at least one drafted row"));if(p.length>ls)return Hc(_c(`Propose rows accepts at most ${ls} 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 Sm(u,Object.keys(p[t]??{}),()=>Bp(r,e.project_id));if(n)return Hc(_c(`row ${t+1}: ${n}`,Yl));const a=l_(p[t]??{});if(a.error)return Hc(_c(`row ${t+1}: ${a.error}`));const i=Fj(u,c,a.rest,{extraKeys:"hara"===c?["effect","title"]:["effect"],where:`row ${t+1}`});if(!i.ok)return Hc(_c(i.message));zj(i.writes);const s=p_(`row ${t+1}`,null,Object.keys(i.writes),a.picks);if(s)return Hc(_c(s,Yl));m.push(i.writes),_.push(a.picks)}const f=jo(o);for(let t=0;t<_.length;t++){const n=await __(r,e.project_id,`row ${t+1}`,u,w_(u,o),_[t],null,t=>lh(r,e.project_id,t));if(n)return Tj(n)}const h=await async function(e,t,n,r){if(void 0===r)return{ok:!0,seed:null};const a=await Sm(n,[Zp],()=>Bp(e,t));if(a)return{ok:!1,error:Am(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 gm(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 Hc(h.error);const y=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=qs[r],l=ko(a,e.model),c=i.map((t,a)=>function(e,t,n,r,a){return function(e,t){return Pr({analysis_id:e,writes:Oa(t)})}(e,{...t,__seed:"hara"===n?r?r.functionId??r.text:"":a??null})}(n.analysis_id,{...t,...f_(null,e.rowPicks[a]??{})},r,e.seed,n.source_req)),d=await Ny({projectId:s,tool:"atoms_propose_rows",key:n.idempotency_key,contents:c}),u=await Ga(t,s,[...d.createRefs,...d.link]),p=d.create.filter(e=>!u.has(e)).length,m=p>0?Iy(await xy(t,s,{[l]:p})):null,_=d.create.map(e=>u.get(e)?.item_id??m(l)),f=[],h=[];i.forEach((t,a)=>{const i={source_req:"dfmea"===r?n.source_req??null:null,..."hara"===r?$m(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=mo(t)),h.push({writes:t,props:i}),f.push({op_id:d.create[a],kind:"create_item",item_id:_[a],path:[],value:{type:"requirement",title:l,data:{body:s,req_type:o,analysis_props:i}}})}),_.forEach((e,t)=>{f.push({op_id:d.link[t],kind:"add",item_id:n.analysis_id,path:["relationships","children"],value:e})}),_.forEach((t,n)=>f.push(...Cj(t,null,e.rowPicks[n]??{})));const y=await Ry({client:t,projectId:s,ops:Fy(f,d),preFound:u,labels:Uj(a)}),g=d.create.map(e=>y.answers.find(t=>t.op_id===e)),{tokens:w,unread:v}=await Py(t,s,g.filter(e=>!!e)),b=h.map((t,n)=>{const r=g[n]?.item_id??_[n];return{id:r,written_fields:Object.keys(t.writes),written_columns:$o(a,Object.keys(t.writes)),computed_level:Fo(a,t.props),...c_(e.rowPicks[n]??{})?f_(null,e.rowPicks[n]):{},...w.get(r)?{base_token:w.get(r)}:{}}});return My(y.outcome,{analysis_id:n.analysis_id,subtype:r,scheme:a,...e.variant?{variant:e.variant}:{},labels:g_(a,e.model),...Im(r,e.seed,n.source_req),rows:b,count:b.length,max_rows:ls,approved:!1,acceptance_revoked:Dy(y.answers),...y.outcome.replayed?{message:Sr}:{},...v?{warning:nr}:{}},y)}({client:r,params:e,parent:s,subtype:c,schemeId:u,variant:d,validatedRows:m,seed:y,model:f,rowPicks:_});const g=async()=>{const t=(new Date).toISOString(),n=qs[c],i=[],s=[],o=ko(u,f),l=Iy(await xy(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?$m(y):{},approved:!1,approved_at:null,approved_by:null,field_source:{}};let _="",f="";for(const[e,t]of Object.entries(d))"effect"===e?_=t:"title"===e?f=t:(m[e]=t,"failure_mode"===e&&"dfmea"===c&&(f=t)),m.field_source[e]="mcp";f||(f=mo(d));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:g}=await Tl(()=>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:qk()??null,p_diff_summary:null}));if(g)throw new Error(g.message);const{error:w}=await Tl(()=>r.rpc("apply_link_change",{p_project_id:e.project_id,p_from_id:p,p_to_id:e.analysis_id,p_type:"parent",p_action:"add",p_user_id:a,p_event_source:"mcp"}));w&&(process.stderr.write(`[atoms-mcp] Warning: proposed row parent link sync failed for ${p}: ${w.message}\n`),s.push({row_id:p,message:w.message})),await r.from("change_history").insert({item_id:p,project_id:e.project_id,changed_by:a,event_type:"created",old_data:null,new_data:h,actor:Ok(),session_id:qk(),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:$o(u,Object.keys(d)),computed_level:Fo(u,m)})}let p=!1,_=null;if(i.length>0)try{for(let t=0;t<3;t+=1){const n=await lh(r,e.project_id,e.analysis_id);if(!n)break;const i=n.data,{revoked:s,parentProps:o}=ts(i);if(!s)break;const l={...i,analysis_props:o},{error:c}=await Tl(()=>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:qk()??null,p_diff_summary:null,p_expected_updated_at:n.updated_at}));if(!c){p=!0;break}if(!(t<2&&/stale_item_write/i.test(c.message??""))){process.stderr.write(`[atoms-mcp] Warning: acceptance revoke save failed for '${n.id}': ${c.message}\n`),_=`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 Dc(oc({analysis_id:e.analysis_id,subtype:c,scheme:u,...d?{variant:d}:{},labels:g_(u,f),...Im(c,y,e.source_req),rows:i,count:i.length,max_rows:ls,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 g()}catch(r){const a=Ty(n,t,r);return a?ek(e,a):Hc(xc(r))}}async function tk(e,t){let n;try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();n=i;const s=await lh(r,e.project_id,e.row_id);if(!s)return Hc(dc("Analysis row",e.row_id));const o=s.data,l=Ij(o?.req_type);if(!l)return Hc(_c(k_(e.row_id,s.type,"atoms_suggest_field"),Yl));const{schemeId:c}=await Nj(r,e.project_id,l,o),d=e.rationale?function(e,t){return ws[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 Hc(_c(`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 Ej(r,e.project_id,c,u);if(!p.ok)return p.result;const m=0===Object.keys(p.rest).length?{ok:!0,writes:{}}:Fj(c,l,p.rest,{extraKeys:"hara"===l?["effect","title"]:["effect"]});if(!m.ok)return Hc(_c(m.message));const _=m.writes;zj(_),Object.assign(_,p.writes);const f=p.answer;if("ops"===i){const{ops:t,refusals:n}=await Hy({client:r,projectId:e.project_id,itemId:s.id,tokens:Cy(e.base_token),cells:Lj(l,_)}),a=await Ry({client:r,projectId:e.project_id,ops:t,refusals:n,labels:Uj(c)}),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=tl({...i}),m=Object.entries(u).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return My(a.outcome,{row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(_),written_columns:$o(c,Object.keys(_)),...d?{rationale_field:d}:{},...p?{approval_cleared:!0}:{},row:{id:s.id,computed_level:Fo(c,i),approved:!0===i.approved&&!p,mcp_fields:m,...Object.fromEntries(vs[c].map(e=>[e,i[e]??null])),...f},acceptance_revoked:Dy(a.answers),...f},a)}const h=async()=>{const t=Oj(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=tl(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:qk()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(h)throw new Error(h.message);if(!m)return Hc(cc(`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:Ok(),session_id:qk(),reason:`${e.field} suggested through atoms_suggest_field (machine-proposed, unapproved)`+(u?"; approval cleared (a signature never covers content the approver did not see)":"")}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const y=Mj(o),g=y?await ns(y,"The suggestion was",{readParent:()=>lh(r,e.project_id,y),saveParent:(t,n)=>Tl(()=>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:qk()??null,p_diff_summary:null,p_expected_updated_at:t.updated_at})),warn:e=>process.stderr.write(`[atoms-mcp] Warning: ${e}\n`)}):{revoked:!1,warning:null},w=Object.entries(n.field_source).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return Dc(oc({row_id:s.id,subtype:l,scheme:c,field:e.field,field_source:"mcp",written_fields:Object.keys(_),written_columns:$o(c,Object.keys(_)),...d?{rationale_field:d}:{},...u?{approval_cleared:!0}:{},acceptance_revoked:g.revoked,...g.warning?{warning:g.warning}:{},row:{id:s.id,computed_level:Fo(c,n),approved:!0===n.approved,mcp_fields:w,...Object.fromEntries(vs[c].map(e=>[e,n[e]??null])),...f},...f}))};return await h()}catch(r){const a=Ty(n,t,r);return a?tk(e,a):Hc(xc(r))}}async function nk(e,t){let n;try{const r=await ed(),a=ad();try{await cd(r,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}const i=t??await Oy(r,e.project_id);if("unreadable"===i)return Ey();n=i;const s=await lh(r,e.project_id,e.row_id);if(!s)return Hc(dc("Analysis row",e.row_id));const o=s.data,l=Ij(o?.req_type);if(!l)return Hc(_c(k_(e.row_id,s.type,"atoms_approve_row"),Yl));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 Hc(_c(`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 Hc(_c(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 Nj(r,e.project_id,l,o),p=o?.analysis_props??{},m=Fo(u,p);if(m===ds)return Hc(_c(`${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=Mc(e.note??""),n=(new Date).toISOString(),{ops:a,refusals:i}=await Hy({client:r,projectId:e.project_id,itemId:s.id,tokens:Cy(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 Ry({client:r,projectId:e.project_id,ops:a,refusals:i,labels:Uj(u)}),_=Object.entries(p.field_source??{}).filter(([,e])=>"mcp"===e).map(([e])=>e).sort();return My(o.outcome,{row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:c,approved_at:n,approved_note:t,approver_role:d,computed_level:m,cleared_markers:_,acceptance_revoked:Dy(o.answers)},o)}const _=async()=>{const t=Oj(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=Mc(e.note??""),_=(new Date).toISOString();n.approved=!0,n.approved_at=_,n.approved_by=c,n.approved_note=i;const f=[];for(const[e,t]of Object.entries(n.field_source))"mcp"===t&&(n.field_source[e]="user",f.push(e));f.sort(),t.metadata={...t.metadata??{},updated_at:_,updated_by:a};const{data:h,error:y}=await r.rpc("save_item_with_revision",{p_item_id:s.id,p_project_id:e.project_id,p_type:s.type,p_title:s.title,p_data:t,p_user_id:a,p_event_source:"mcp",p_event_session_id:qk()??null,p_diff_summary:null,p_expected_updated_at:s.updated_at});if(y)throw new Error(y.message);if(!h)return Hc(cc(`Approval silently failed for '${e.row_id}': save RPC returned no row. Likely RLS denied the write.`,["Verify you have editor or admin role in this project","Retry after checking project access"]));await r.from("change_history").insert({item_id:s.id,project_id:e.project_id,changed_by:a,event_type:"updated",old_data:{approved:!0===p.approved,approved_at:p.approved_at??null,approved_by:p.approved_by??null,approved_note:p.approved_note??""},new_data:{approved:!0,approved_at:_,approved_by:c,approved_note:i},actor:Ok(),session_id:qk(),reason:`${e.row_id} approved by ${c} via atoms_approve_row`}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)});const g=Mj(o);if(g){const t=await lh(r,e.project_id,g);if(t){const{revoked:n,parentProps:i}=ts(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:qk()??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 Dc(oc({row_id:s.id,subtype:l,scheme:u,approved:!0,approved_by:c,approved_at:_,approved_note:i,approver_role:d,computed_level:m,cleared_markers:f}))};return await _()}catch(r){const a=Ty(n,t,r);return a?nk(e,a):Hc(xc(r))}}B($j,{approveRowHandler:()=>nk,createAnalysisHandler:()=>Pj,fillRowHandler:()=>Vj,getAnalysisHandler:()=>Gj,getGapsHandler:()=>Xj,linkMitigationHandler:()=>Yj,proposeRowsHandler:()=>ek,suggestFieldHandler:()=>tk});var rk=V({"src/tools/analysis.ts"(){md(),je(),fh(),Nw(),qy(),Ul(),Rl(),Rk(),zc(),si(),Vy(),si(),Al(),cl(),Om(),sm(),Aj(),Oi(),N_(),n_(),Wi(),yp(),ro(),Sj=new Set(["safety-goal","failure-mode"])}}),ak={};async function ik(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=kj(n?.scenario_catalogs??[]);return a.ok?a.value:[]}async function sk(e){try{const t=await ed(),n=Math.min(Math.max(e.limit??50,1),200),r=Math.max(e.offset??0,0),a=await ik(t,e.project_id);return Dc(oc(a.slice(r,r+n),lc(a.length,n,r)),{paging:{}})}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(xc(e,{read:!0}))}}async function ok(e){const t=mm("atoms_mutate_scenario_catalog",e);if(t)return Hc(t);try{const t=await ed();ad();try{await cd(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return Hc(mc("Viewer"));throw e}if("string"!=typeof(n=e.op)||!wj.includes(n))return Hc(_c("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 ik(t,e.project_id)).length>=gj)return Hc(_c(`This project already carries the maximum of ${gj} 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=Mc(e.name)),void 0!==e.entry_id&&(a.entry_id=e.entry_id),void 0!==e.text&&(a.text=Mc(e.text)),void 0!==e.function_ids){const n=await async function(e,t,n){const r=await Bp(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:tm,next_steps:[...nm],code:"function_items_off",retryable:!1}};const a=await wm(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 Hc(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?Hc(ae(s.message)??_c(s.message)):Dc(oc({scenario_catalogs:i?.scenario_catalogs??[]}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?Hc(fc()):Hc(Ec(e instanceof Error?e.message:String(e)))}var n}B(ak,{listScenarioCatalogsHandler:()=>sk,mutateScenarioCatalogHandler:()=>ok});var lk,ck,dk,uk,pk,mk,_k,fk,hk,yk,gk,wk,vk,bk,jk,kk=V({"src/tools/catalogs.ts"(){md(),ue(),zc(),Om(),Aj()}}),Sk={};function Ak(t){tt(t.toolName)&&function(t,n){const r=`ui://${n.toolName}/${n.htmlFile}`,a=function(e,t){const n=h(import.meta.url),r=l.dirname(n);return l.resolve(r,"apps","src","apps",e,t)}(n.appName,n.htmlFile),i=[...th.resourceDomains,...n.extraResourceDomains??[]];w(t,n.toolName,{title:n.title,description:n.description,inputSchema:n.inputSchema,annotations:n.annotations,_meta:{ui:{resourceUri:r}}},n.handler),v(t,`${n.title} UI`,r,{mimeType:b},async()=>{const t=await e.readFile(a,"utf-8");return{contents:[{uri:r,mimeType:b,text:t,_meta:{ui:{csp:{resourceDomains:i}}}}]}})}(pk,t)}function $k(e){return void 0===e?.requestId?void 0:String(e.requestId)}function Ik(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 Tt||/^auth_unavailable:/.test(r)?Hc(Nt()):an(r)?Hc(wc()):/not authenticated/i.test(r)?Hc(fc()):Ic(t)||sn(r)?Hc(hc()):Hc(n())}function xk(e,t){return async(n,r)=>{let a="",i=null,s=!1;try{i=await ed(),a=ad()}catch(e){i=null,s=e instanceof Tt}if(i){const e=await async function(e,t){let n;try{n=await Uc(e,t)}catch(e){return process.stderr.write(`[atoms-mcp] platform_status lookup failed: ${e instanceof Error?e.message:String(e?.message??e)}\n`),Ic(e)?hc():cc("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?uc("account"):"pending"===n?cc("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 Hc(e)}if(i&&await Ye(i,a),Le)return Hc({status:"error",message:K,next_steps:["Wait a few seconds, then retry the same call"],code:"policy_unavailable",retryable:!0,retry_after_seconds:2});if(!Ue&&I.has(e))return Hc(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}:fc());if(!de.has(e)){let t;try{t=await rd(async()=>(i=await ed(),a=ad(),async function(e,t,n,r){if(de.has(n))return{refused:!1};const a=await pe(e,t);if(me(a))return{refused:!0,reason:"viewer_everywhere"};const i=_e(a);if(0===i.size)return{refused:!1};const{projectIds:s}=await fe(e,r);for(const t of s){const n=await he(e,t);if(n&&i.has(n))return{refused:!0,reason:"viewer_in_org"}}return{refused:!1}}(i,a,e,n)))}catch(e){return Ik("viewer gate",e,ge)}if(t.refused)return Hc((o=t.reason,{status:"error",message:oe,next_steps:[..."viewer_everywhere"===o?ce:le]}))}var o;{let t;try{t=await rd(async()=>{let t=null,r=null;try{t=await ed(),i=t,a=ad()}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=>xe(e,t,n))||!!a(e=>e.require_confirmation_for.includes(t))||ve.has(t)&&a(e=>ne(e,"atoms_create_level").allowed)}(a,n,r)){const e=a.orgs[0]?.effective??G,s=xe(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 we.some(e=>"string"==typeof l[e])&&(i||null!==e.project_scope)&&(c=await fe(t,r)),i&&(c.unresolved>0||c.projectIds.some(e=>e!==i))?o(i):ie(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 we){const n=r[t];if("string"!=typeof n)continue;const s=await ye(e,n);s?a.push(s):i++}const s=[];for(const n of a)s.push({projectId:n,orgId:await qe(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:Ae(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:$e(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=xe(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=ie(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:Qe(),toolName:e,params:n,envProjectId:Te(),envProjectRefusal:yc,envOrgId:Ce(),envOrgRefusal:gc,reload:t?()=>async function(e,t){return Fe=0,await Ye(e,t),Ne}(t,a):void 0});var s})}catch(e){return Ik("project scope",e,se)}if(t)return Hc(t)}if(!i)return t(n,r);const l=await async function(e,t){const n=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||Pd,r=new Date,a=new Date(r.getTime()-zd);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())+zd-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*zd);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 Hc(wc(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(()=>(md(),Xc));await t(i,e)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message){const{accessDeniedError:e}=await Promise.resolve().then(()=>(zc(),ac));return Hc(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 nu(e,uk)}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:_k,client_name:Ek(),client_version:uk};try{!function(e,t,n){const r=Fd(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 ed(),a,t)}catch{}}}}function qk(){return _k}function Ok(){return Kt(Ek())}function Ek(){const e=process.env.ATOMS_CLIENT_NAME;return Qt(e&&e.trim()?e:pk.server.getClientVersion()?.name)}B(Sk,{ATOMS_MCP_SERVER_VERSION:()=>uk,getMcpActor:()=>Ok,getMcpClientName:()=>Ek,getMcpSessionId:()=>qk,server:()=>pk});var Rk=V({"src/server.ts"(){Od(),Hd(),Gd(),Qd(),at(),De(),Ze(),ju(),ue(),Me(),rn(),ku(),cl(),ee(),cf(),of(),Vf(),nh(),Om(),tp(),si(),rc(),N_(),md(),Zc(),je(),zc(),ue(),pn(),zt(),rh(),lk=k.string().datetime({offset:!0}),ck=S(import.meta.url),dk=ck("../package.json"),uk=dk.version,function(e){const t=e=>e.endsWith(U)?e:`${e}\n\n${U}`;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)}}(pk=new j({name:"atoms-mcp-server",version:uk})),function(e){Ve=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&&We.set(e,r),r}}(pk),mk=(e,t,n)=>{if(tt(e))return pk.registerTool(e,t,n)},_k=m(),mk("atoms_status",{title:"ATOMS MCP Health Check",description:sf.atoms_status,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>ru(await(async()=>{const e=(e,t)=>async function(e,t,n){try{const e=await(async()=>async function(e,t){Fc.delete(t);const n=await Uc(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=me(await pe(e,t))}catch{s=null}return{platform_status:n,org_suspended:r,viewer_only:s}}(await ed(),ad()))();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:oe,next_steps:[...ce]}:{status:"authenticated",email:t,message:(e.org_suspended??[]).length>0?Pc: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(()=>(wt(),it)),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(()=>(Gt(),Ut)),{email:n}=await t(),{invalidateClient:r}=await Promise.resolve().then(()=>(md(),Xc));return r(),{content:[{type:"text",text:Lc(await e(n,"Token was expired but has been refreshed. You're good to go!"))}]}}catch(e){return e instanceof Tt?{content:[{type:"text",text:JSON.stringify({...Nt(),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:Lc(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)}]}}})(),uk)),mk("atoms_list_projects",{title:"List ATOMS Projects",description:sf.atoms_list_projects,inputSchema:{offset:k.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:k.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_projects",async e=>{const{listProjectsHandler:t}=await Promise.resolve().then(()=>(gh(),hh));return t(e)})),mk("atoms_list_items",{title:"List ATOMS Items",description:sf.atoms_list_items,inputSchema:{project_id:k.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:k.enum(Bm).optional().describe("Filter by item type"),domain:k.string().max(64).optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:k.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),limit:k.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:k.number().int().min(0).default(0).describe("Pagination offset (default 0)"),after:k.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:k.string().uuid().optional().describe("Optional baseline UUID. Returns items as they were at that baseline's moment. Mutually exclusive with as_of."),as_of:lk.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}},xk("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(bh(),wh));return t(e)})),mk("atoms_get_item",{title:"Get ATOMS Item Details",description:sf.atoms_get_item,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).describe("Item ID (e.g., REQ-001)"),baseline_id:k.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:lk.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}},xk("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(Uh(),Hh));return t(e)})),mk("atoms_list_changes",{title:"List ATOMS Changes",description:z,inputSchema:{project_id:k.string().uuid(),since_seq:k.number().int().min(0).optional(),limit:k.number().int().min(1).max(500).default(100)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_changes",async e=>{const{listChangesHandler:t}=await Promise.resolve().then(()=>(Bh(),Lh));return t(e)})),mk("atoms_search",{title:"Search ATOMS Items",description:sf.atoms_search,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),query:k.string().min(1).max(1e3).describe("Search text"),type:k.enum(Bm).optional().describe("Filter by item type"),asset:k.string().max(200).optional().describe("Filter to items with at least one run on this asset (case-sensitive exact)"),limit:k.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),baseline_id:k.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}},xk("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(Kh(),Gh));return t(e)})),mk("atoms_semantic_search",{title:"Semantic Search ATOMS Items",description:sf.atoms_semantic_search,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),query:k.string().min(1).max(1e3).describe("Natural-language concept query"),type:k.enum(Bm).optional().describe("Filter by item type"),limit:k.number().int().min(1).max(50).default(10).describe("Max results (default 10, max 50)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_semantic_search",async e=>{const{semanticSearchHandler:t}=await Promise.resolve().then(()=>(Xh(),Yh));return t(e)})),Ak({appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:sf.atoms_get_coverage,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),domain:k.string().max(64).optional().describe("Filter by domain tag"),level:k.string().max(32).optional().describe("Filter by level"),baseline_id:k.string().uuid().optional().describe("Compute coverage as of this baseline's snapshot moment"),as_of:lk.optional().describe("Compute coverage as of this ISO 8601 moment"),offset:k.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:k.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:xk("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(ay(),ey));return t(e)})}),mk("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${yf}\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${Wf}\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:k.string().uuid().describe("UUID of the project"),release_id:k.string().uuid().optional().describe("Formal Release (baselines row) UUID; defaults to the project's current Release"),include_gaps:k.boolean().default(!1).describe("Include the not-run (test x unit x value) points for the Release"),include_report:k.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}},xk("atoms_verification_status",async e=>{const{verificationStatusHandler:t}=await Promise.resolve().then(()=>(cy(),sy));return t(e)})),mk("atoms_get_history",{title:"Get Item Change History",description:sf.atoms_get_history,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).describe("Item ID"),limit:k.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(py(),dy));return t(e)})),Ak({appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:sf.atoms_export_mermaid,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),root_item_id:k.string().max(20).optional().describe("Root item ID to start from"),depth:k.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:k.boolean().default(!0).describe("Include test case links"),baseline_id:k.string().uuid().optional().describe("Render the graph as of this baseline's snapshot moment"),as_of:lk.optional().describe("Render the graph as of this ISO 8601 moment")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:xk("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(Sy(),vy));return t(e)})}),hk=()=>k.string().max(128).optional().describe(C),yk=()=>k.enum(["edit","apply_mine"]).describe(D).optional(),gk=()=>k.string().min(1).max(600).optional().describe(N),wk=(fk=()=>k.union([k.string().min(1).max(Gn),k.array(k.string().min(1).max(Gn)).min(1).max(Qn)]).describe(T).optional())(),vk=hk(),mk("atoms_create_item",{title:"Create ATOMS Item",description:sf.atoms_create_item,inputSchema:{project_id:k.string().uuid().describe("UUID of the target project"),type:k.enum(Hm).describe(Nm),title:k.string().min(1).max(500).describe("Item title"),req_type:k.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe(qd),body:k.string().max(5e4).optional().describe("Rich text body"),summary:k.string().max(2e3).optional().describe("Brief summary"),domains:k.array(k.string().max(64)).max(20).optional().describe("Domain tags"),level:k.string().max(32).optional().describe("System|Subsystem|Component"),parent_ids:k.array(k.string().max(20)).max(50).optional().describe("Parent item IDs to link"),fields:k.record(k.string().max(60),k.string().max(2e3)).optional().describe("Project-field values keyed by defined field name"),echo:k.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens"),idempotency_key:hk()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(ow(),iw));return t(e)})),bk={steps:k.array(k.object({id:k.string().describe(hu),instruction:k.string().describe("What the tester does"),test_data:k.string().optional().describe("Optional test data for the step"),expected:k.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. "+hu),params:k.array(k.object({name:k.string().describe("Parameter name; steps reference it as {name}"),unit:k.string().optional().describe("Optional unit (e.g. km/h, V, m)"),values:k.array(k.union([k.string(),k.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. "+fu)},mk("atoms_update_item",{title:"Update ATOMS Item",description:sf.atoms_update_item,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).optional().describe("Item ID (single form)"),title:k.string().min(1).max(500).optional().describe("New title"),body:k.string().max(5e4).optional().describe("New body"),summary:k.string().max(2e3).optional().describe("New summary"),domains:k.array(k.string().max(64)).max(20).optional().describe("New domain tags (a function tag is not a domain and is rejected)"),level:k.string().max(32).optional().describe("New level"),status:k.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:k.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional().describe(qd),fields:k.record(k.string().max(60),k.string().max(2e3)).optional().describe('Project-field values keyed by defined field name; "" clears a key'),...bk,expected_updated_at:lk.optional().describe(`metadata.updated_at value from atoms_get_item; rejects stale writes. ${F}`),base_token:fk(),intent:yk(),asil_confirm_lower:k.string().max(8).optional().describe(jd),widget_proof:gk(),echo:k.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:k.string().max(500).optional().describe(L_),updates:k.array(k.object({item_id:k.string().min(1).max(20),title:k.string().min(1).max(500).optional(),body:k.string().max(5e4).optional(),summary:k.string().max(2e3).optional(),domains:k.array(k.string().max(64)).max(20).optional(),level:k.string().max(32).optional(),status:k.enum(["passed","failed","blocked","not-run"]).optional(),req_type:k.enum(["functional","interface","performance","safety","safety-goal","failure-mode"]).optional(),fields:k.record(k.string().max(60),k.string().max(2e3)).optional(),...bk,expected_updated_at:lk.optional(),base_token:fk(),intent:yk(),asil_confirm_lower:k.string().max(8).optional().describe(jd)})).optional().describe("Array form: update many items in one call"),idempotency_key:hk(),continue_on_error:k.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(Ww(),Fw));return t(e)})),mk("atoms_delete_item",{title:"Delete ATOMS Item",description:sf.atoms_delete_item,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).describe("Item ID to soft-delete"),confirmation_token:k.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}},xk("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Jw(),Vw));return t(e)})),mk("atoms_restore_item",{title:"Restore ATOMS Item",description:Pl,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().max(256).describe("ID of the item in Trash"),confirm:k.boolean().optional().describe(zl)},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_restore_item",async e=>{const{restoreItemHandler:t}=await Promise.resolve().then(()=>(Xw(),Gw));return t(e)})),mk("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 applied one at a time (removes before adds), NOT in a single transaction: a mid-batch failure leaves earlier operations committed and names which ones\n - reason?, idempotency_key? supported\n\nidempotency_key: ${C}`,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),from_id:k.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:k.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:k.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]).optional().describe("Relationship type"),action:k.enum(["add","remove"]).optional().describe("Add or remove"),expected_from_updated_at:lk.optional().describe("metadata.updated_at for from_id from atoms_get_item"),expected_to_updated_at:lk.optional().describe("metadata.updated_at for to_id from atoms_get_item"),echo:k.boolean().optional().describe("false → lean response"),reason:k.string().max(500).optional().describe(L_),operations:k.array(k.object({action:k.enum(["add","remove"]),from_id:k.string().min(1).max(20),to_id:k.string().min(1).max(20),type:k.enum(["parent","child","related","verifies","verified_by","affects","affected_by","allocated_to","allocated_from"]),expected_from_updated_at:lk.optional(),expected_to_updated_at:lk.optional()})).optional().describe("Array form: batch relationship ops, DAG-validated as a whole then applied in sequence (not one transaction); a mid-batch failure reports which ops committed."),idempotency_key:hk()},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},xk("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(sv(),tv));return t(e)})),Ak({appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:sf.atoms_bulk_import,inputSchema:{project_id:k.string().uuid().describe("UUID of the target project"),items:k.array(k.object({type:k.enum(Hm).describe(Nm),title:k.string().min(1).max(500).describe("Item title"),body:k.string().max(5e4).optional().describe("Rich text body"),summary:k.string().max(2e3).optional().describe("Brief summary"),domains:k.array(k.string().max(64)).max(20).optional().describe("Domain tags"),level:k.string().max(32).optional().describe("System|Subsystem|Component"),parent_id:k.string().max(20).optional().describe("Parent item ID to link")})).min(1).max(500).describe("Items to create (1-100; 1-500 on a project that saves one field at a time)"),confirmation_token:k.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),idempotency_key:hk()},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:xk("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(pv(),lv));return t(e)})}),jk={point:k.record(k.string(),k.union([k.string(),k.number()])).optional().describe('Matrix point this run executed, e.g. {"speed": 40}'),release_id:k.string().uuid().optional().describe("Formal Release to bind this run to (a baseline with a release_version)"),build:k.string().optional().describe("Free-text build label"),environment:k.string().optional().describe("Structured environment field, distinct from build"),tooling:k.string().optional().describe("Structured tooling field, distinct from build"),steps_rev:k.string().optional().describe(pu),evidence_url:k.string().optional().describe(_u),step_results:k.array(k.object({step_id:k.string().describe("Step id from atoms_get_item steps[].id"),status:k.enum(["passed","failed","blocked","skipped"]).describe("Per-step status"),actual:k.string().optional().describe("Actual-result note"),evidence_url:k.string().optional().describe(mu)}).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.")},mk("atoms_record_test_result",{title:"Record Test Result",description:sf.atoms_record_test_result,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:k.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:k.string().max(500).optional().describe("Reason or comment for this result"),asset:k.string().max(200).optional().describe("Asset identifier this run was executed against (VIN, module ID, lot, etc). Auto-registered if new."),date:k.string().optional().describe(lu),...jk,idempotency_key:vk},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_record_test_result",async(e,t)=>{const{recordTestResultHandler:n}=await Promise.resolve().then(()=>(hv(),mv));return n({...e,request_id:$k(t)})})),mk("atoms_record_test_results",{title:"Record Test Results (bulk)",description:sf.atoms_record_test_results,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),results:k.array(k.object({asset:k.string().max(200).optional().describe("Asset identifier this run was executed against. Auto-registered if new."),result:k.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:k.string().max(500).optional().describe("Run note"),date:k.string().optional().describe("Ignored: runs are stamped with server time. A supplied date is reported in the response warning, never stored."),...jk})).min(1).max(100).describe("1 to 100 result entries on this test case"),idempotency_key:vk},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_record_test_results",async(e,t)=>{const{recordTestResultsBulkHandler:n}=await Promise.resolve().then(()=>(wv(),yv));return n({...e,request_id:$k(t)})})),Ak({appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:sf.atoms_trace,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).describe("Starting item ID"),direction:k.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:k.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:k.array(k.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:k.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:k.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:xk("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(jv(),vv));return t(e)})}),mk("atoms_list_assets",{title:"List Project Assets",description:sf.atoms_list_assets,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),include_archived:k.boolean().optional().describe("Include archived assets (default false)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_assets",async e=>{const{listAssetsHandler:t}=await Promise.resolve().then(()=>($v(),kv));return t(e)})),mk("atoms_list_variables",{title:"List Project Variables",description:sf.atoms_list_variables,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),baseline_id:k.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:lk.optional().describe("Optional ISO timestamp for time-travel reads"),limit:k.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:k.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(Jv(),Tv));return t(e)})),mk("atoms_get_variable",{title:"Get Project Variable",description:sf.atoms_get_variable,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),variable_name:k.string().min(1).max(64).describe("Variable name"),baseline_id:k.string().uuid().optional().describe("Optional baseline UUID for time-travel reads"),as_of:lk.optional().describe("Optional ISO timestamp for time-travel reads")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(Jv(),Tv));return t(e)})),mk("atoms_update_variable",{title:"Update Project Variable",description:sf.atoms_update_variable,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),variable_name:k.string().min(1).max(64).describe("Variable name"),value:k.string().max(500).optional().describe("New value"),unit:k.string().max(32).optional().describe("Unit abbreviation"),description:k.string().max(2e3).optional().describe("Description"),echo:k.boolean().optional(),base_token:wk},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(Jv(),Tv));return t(e)})),mk("atoms_create_variable",{title:"Create Project Variable",description:sf.atoms_create_variable,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(64).optional().describe("Variable name (single form)"),value:k.string().min(1).max(500).optional().describe("Initial value (single form)"),unit:k.string().max(32).optional().describe("Unit abbreviation"),description:k.string().max(2e3).optional().describe("Description"),echo:k.boolean().optional().describe("false → lean response (default true)"),variables:k.array(k.object({name:k.string().min(1).max(64).describe("Variable name"),value:k.string().min(1).max(500).describe("Initial value"),unit:k.string().max(32).optional().describe("Unit abbreviation"),description:k.string().max(2e3).optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:k.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(Jv(),Tv));return t(e)})),mk("atoms_delete_variable",{title:"Delete Project Variable",description:sf.atoms_delete_variable,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(64).describe("Variable name to delete"),force:k.boolean().optional().describe("Delete even if items reference it (default false)"),confirmation_token:k.string().max(500).optional().describe("Token from a prior preview call (only used when ATOMS_MCP_REQUIRE_CONFIRMATION is set)"),base_token:wk},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},xk("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(Jv(),Tv));return t(e)})),mk("atoms_list_domains",{title:"List Project Domains",description:sf.atoms_list_domains,inputSchema:{project_id:k.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(tb(),Gv));return t(e)})),mk("atoms_create_domain",{title:"Create Project Domain",description:sf.atoms_create_domain,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(tb(),Gv));return t(e)})),mk("atoms_list_levels",{title:"List Project Levels",description:sf.atoms_list_levels,inputSchema:{project_id:k.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_levels",async e=>{const{listLevelsHandler:t}=await Promise.resolve().then(()=>(jg(),ng));return t(e)})),mk("atoms_create_level",{title:"Create Project Level",description:sf.atoms_create_level,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(64).describe("Level name (user-defined label)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_create_level",async e=>{const{createLevelHandler:t}=await Promise.resolve().then(()=>(jg(),ng));return t(e)})),mk("atoms_delete_level",{title:"Delete Project Level",description:sf.atoms_delete_level,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(64).describe("Level name to delete"),confirmation_token:k.string().optional().describe("Token from the first (preview) call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},xk("atoms_delete_level",async e=>{const{deleteLevelHandler:t}=await Promise.resolve().then(()=>(jg(),ng));return t(e)})),mk("atoms_reorder_levels",{title:"Reorder Project Levels",description:sf.atoms_reorder_levels,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),names:k.array(k.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}},xk("atoms_reorder_levels",async e=>{const{reorderLevelsHandler:t}=await Promise.resolve().then(()=>(jg(),ng));return t(e)})),mk("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${lf("fields")}`,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),offset:k.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:k.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_fields",async e=>{const{listFieldsHandler:t}=await Promise.resolve().then(()=>(aw(),Pg));return t(e)})),mk("atoms_create_field",{title:"Create Project Field",description:sf.atoms_create_field,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(60).describe("Field name (display name, 1-60 chars)"),type:k.enum(["text","long","bool","date","person","select","number","link"]).optional().describe("Field type, defaults to text"),options:k.array(k.string().min(1).max(120)).max(100).optional().describe("Allowed values for select fields"),scope:k.enum(["project","organization"]).optional().describe("Create in this project or copy to every project in the organization"),appliesTo:k.array(k.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}},xk("atoms_create_field",async e=>{const{createFieldHandler:t}=await Promise.resolve().then(()=>(aw(),Pg));return t(e)})),mk("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:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(60).describe("Field name"),confirmation_token:k.string().max(500).optional().describe("Token from the preview call, when confirmation is required")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},xk("atoms_delete_field",async e=>{const{deleteFieldHandler:t}=await Promise.resolve().then(()=>(aw(),Pg));return t(e)})),mk("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:k.string().uuid().describe("UUID of the project"),names:k.array(k.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}},xk("atoms_reorder_fields",async e=>{const{reorderFieldsHandler:t}=await Promise.resolve().then(()=>(aw(),Pg));return t(e)})),mk("atoms_update_domain",{title:"Update Project Domain",description:sf.atoms_update_domain,inputSchema:k.object({project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(64).describe("Current domain name"),new_name:k.string().min(1).max(64).describe("New domain name"),dry_run:k.boolean().optional().describe("Preview impact without applying (default false)")},{errorMap:_m("atoms_update_domain")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(tb(),Gv));return t(e)})),mk("atoms_delete_domain",{title:"Delete Project Domain",description:sf.atoms_delete_domain,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(64).describe("Domain name to delete"),force:k.boolean().optional().describe("Strip from all items and delete (default false)"),confirmation_token:k.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}},xk("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(tb(),Gv));return t(e)})),Ak({appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:sf.atoms_project_summary,inputSchema:{project_id:k.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:xk("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(ab(),nb));return t(e)})}),Ak({appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:sf.atoms_browse,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),type:k.enum(Bm).optional().describe("Filter by item type"),domain:k.string().max(64).optional().describe("Filter by domain tag"),level:k.string().max(32).optional().describe("Filter by level (System, Subsystem, Component)"),query:k.string().max(1e3).optional().describe("Full-text search query"),limit:k.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:k.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:xk("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(lb(),ib));return t(e)})}),mk("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:sf.atoms_impact_analysis,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),item_id:k.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:k.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:k.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:k.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:k.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:k.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(Sb(),cb));return t(e)})),mk("atoms_list_baselines",{title:"List ATOMS Baselines",description:sf.atoms_list_baselines,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),limit:k.number().int().min(1).max(100).default(50).describe("Max results (default 50, max 100)"),offset:k.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_baselines",async e=>{const{listBaselinesHandler:t}=await Promise.resolve().then(()=>(vj(),sj));return t(e)})),mk("atoms_create_baseline",{title:"Create ATOMS Baseline",description:sf.atoms_create_baseline,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),name:k.string().min(1).max(200).describe("Baseline name (1-200 chars, unique per project)"),description:k.string().max(2e3).optional().describe("Optional description (max 2000 chars)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_create_baseline",async e=>{const{createBaselineHandler:t}=await Promise.resolve().then(()=>(vj(),sj));return t(e)})),mk("atoms_lock_baseline",{title:"Lock ATOMS Baseline",description:sf.atoms_lock_baseline,inputSchema:{baseline_id:k.string().uuid().describe("UUID of the baseline to lock")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_lock_baseline",async e=>{const{lockBaselineHandler:t}=await Promise.resolve().then(()=>(vj(),sj));return t(e)})),mk("atoms_diff_baselines",{title:"Diff ATOMS Baselines",description:sf.atoms_diff_baselines,inputSchema:{baseline_a_id:k.string().uuid().describe("UUID of the first (older) baseline"),baseline_b_id:k.string().uuid().describe("UUID of the second (newer) baseline"),detail:k.boolean().default(!1).describe("Add a per-field from/to diff object to each modified item (default false)"),limit:k.number().int().min(1).max(200).default(50).describe("Max items per page (default 50)"),offset:k.number().int().min(0).default(0).describe("Pagination offset")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_diff_baselines",async e=>{const{diffBaselinesHandler:t}=await Promise.resolve().then(()=>(vj(),sj));return t(e)})),mk("atoms_restore_baseline",{title:"Restore from ATOMS Baseline",description:sf.atoms_restore_baseline,inputSchema:{baseline_id:k.string().uuid().describe("UUID of the baseline to restore from"),confirm:k.boolean().default(!1).describe("Set true to execute; false (default) returns a preview"),source_seq:k.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:k.string().uuid().optional().describe(H),after_id:k.string().min(1).max(64).optional().describe(H),confirmation_token:k.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}},xk("atoms_restore_baseline",async e=>{const{restoreBaselineHandler:t}=await Promise.resolve().then(()=>(vj(),sj));return t(e)})),mk("atoms_create_analysis",{title:"Create Analysis (HARA, Risk analysis, FMEA)",description:sf.atoms_create_analysis,inputSchema:k.object({project_id:k.string().uuid().describe("UUID of the target project"),subtype:k.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:k.string().min(1).max(500).optional().describe("Analysis title"),source_function_ids:k.array(k.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:k.array(k.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:k.array(k.string().min(1).max(20)).max(50).optional().describe("dfmea only: requirement IDs to seed rows from (0-50)"),revision:k.string().min(1).max(32).optional().describe("Revision label (default 1.0)"),variant:k.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:k.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:k.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:k.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:k.string().max(1e4).optional().describe("Security risk analysis only: the threat modeling methodology used, e.g. STRIDE."),threat_model_rationale:k.string().max(1e4).optional().describe("Security risk analysis only: why that methodology was chosen."),environment_assumptions:k.string().max(1e4).optional().describe("Security risk analysis only: assumptions about the operating environment, one per line."),attack_surfaces:k.string().max(1e4).optional().describe("Security risk analysis only: interfaces and entry points considered, one per line."),related_documents:k.string().max(1e4).optional().describe("Security risk analysis only: where the SBOM, the security testing report and the architecture views live."),idempotency_key:vk,hazard_id:k.string().max(20).optional().describe(Fm),goal_id:k.string().max(20).optional().describe(Pm)},{errorMap:_m("atoms_create_analysis")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_create_analysis",async e=>{const{createAnalysisHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("atoms_fill_row",{title:"Fill Analysis Row Fields",description:sf.atoms_fill_row,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),row_id:k.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:k.record(k.string().max(64),k.union([k.string().max(5e4),k.number()])).describe("Field name to value map (see description for allowed keys per subtype)"),base_token:wk},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_fill_row",async e=>{const{fillRowHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("atoms_get_analysis",{title:"Get Analysis",description:sf.atoms_get_analysis,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),analysis_id:k.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),offset:k.number().int().min(0).optional().describe("Entries to skip (default 0); pass meta.next_offset to read the next page"),limit:k.number().int().min(1).max(1e3).optional().describe("Page size (default 1000)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_get_analysis",async e=>{const{getAnalysisHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("atoms_link_mitigation",{title:"Link Analysis Row to Mitigating Requirement",description:sf.atoms_link_mitigation,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),row_id:k.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),req_id:k.string().min(1).max(20).describe("Target requirement ID (e.g. REQ-042)"),role:k.enum(["prevention","detection","mitigation"]).optional().describe("Mitigation role. Required for dfmea rows (every FMEA); must be omitted for hara rows."),override:k.boolean().optional().describe("hara only: apply the row's level (ASIL or Risk) over a conflicting existing value (history-logged)"),control_type:k.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:k.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}},xk("atoms_link_mitigation",async e=>{const{linkMitigationHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("atoms_get_gaps",{title:"Get Analysis Gap Rows",description:sf.atoms_get_gaps,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),analysis_id:k.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}},xk("atoms_get_gaps",async e=>{const{getGapsHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("atoms_propose_rows",{title:"Write Proposed Analysis Rows",description:sf.atoms_propose_rows,inputSchema:k.object({project_id:k.string().uuid().describe("UUID of the project"),analysis_id:k.string().min(1).max(20).describe("Analysis ID (e.g. HARA-001, RA-001, PFMEA-002)"),rows:k.array(k.record(k.string().max(64),k.union([k.string().max(5e4),k.number()]))).min(1).max(ls).describe(`The drafted rows (1-${ls}), each a scheme field name to value map`),source_function_id:k.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:k.string().min(1).max(20).optional().describe("FMEA only: the requirement these rows analyse"),idempotency_key:vk},{errorMap:_m("atoms_propose_rows")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_propose_rows",async e=>{const{proposeRowsHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("atoms_suggest_field",{title:"Write a Suggested Value for One Analysis Field",description:sf.atoms_suggest_field,inputSchema:{project_id:k.string().uuid().describe("UUID of the project"),row_id:k.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),field:k.string().min(1).max(64).describe("The field to fill (a scheme key of this row)"),value:k.union([k.string().max(5e4),k.number()]).describe("The suggested value"),rationale:k.string().max(5e4).optional().describe("The evidence behind a suggested rating; written to the scheme's evidence field"),base_token:wk},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_suggest_field",async e=>{const{suggestFieldHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("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:k.string().uuid().describe("UUID of the project"),row_id:k.string().min(1).max(20).describe("Analysis row ID (e.g. SG-001, FM-003)"),approver_id:k.string().uuid().optional().describe("The approving project member; defaults to the calling user"),note:k.string().max(2e3).optional().describe("Optional note captured with the approval"),base_token:wk},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_approve_row",async e=>{const{approveRowHandler:t}=await Promise.resolve().then(()=>(rk(),$j));return t(e)})),mk("atoms_list_scenario_catalogs",{title:"List Operational Scenario Catalogs",description:sf.atoms_list_scenario_catalogs,inputSchema:{project_id:k.string().uuid("Must be a valid project UUID").describe("UUID of the project"),limit:k.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:k.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},xk("atoms_list_scenario_catalogs",async e=>{const{listScenarioCatalogsHandler:t}=await Promise.resolve().then(()=>(kk(),ak));return t(e)})),mk("atoms_mutate_scenario_catalog",{title:"Mutate an Operational Scenario Catalog",description:sf.atoms_mutate_scenario_catalog,inputSchema:k.object({project_id:k.string().uuid().describe("UUID of the project"),op:k.enum(["create_catalog","rename_catalog","delete_catalog","add_entry","edit_entry","remove_entry","tag_entry","accept_catalog"]).describe("The mutation to apply"),catalog_id:k.string().min(1).max(64).optional().describe("The catalog id (optional for create_catalog: generated when omitted)"),name:k.string().min(1).max(100).optional().describe("The catalog name (create_catalog, rename_catalog)"),entry_id:k.string().min(1).max(64).optional().describe("The entry id (caller-generated for add_entry)"),text:k.string().min(1).max(100).optional().describe("The entry's operational scenario text"),function_ids:k.array(k.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:k.string().min(1).max(200).optional().describe("The accepter's name (accept_catalog)"),on:k.string().min(1).max(32).optional().describe("The acceptance date (accept_catalog)")},{errorMap:_m("atoms_mutate_scenario_catalog")}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},xk("atoms_mutate_scenario_catalog",async e=>{const{mutateScenarioCatalogHandler:t}=await Promise.resolve().then(()=>(kk(),ak));return t(e)})),Ke()}});at(),Ze(),md();var Mk=S(import.meta.url)("../package.json"),Tk=process.argv.slice(2)[0];(async function(){switch(Tk){case"login":{const{login:e}=await Promise.resolve().then(()=>(yd(),_d));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(()=>(Gt(),Ut));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(()=>(wt(),it));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${Mk.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(()=>(kd(),gd)),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 ed(),t=ad();await async function(e,t){try{const n=await He(e,t);!function(e){Ne=e,Fe=Date.now(),Ue=!0,Le=!1}(n),Je(n)}catch(e){Ue=!1,Le=e instanceof be,process.stderr.write(`[atoms-mcp] Could not resolve session policy (${e instanceof Error?e.message:String(e)}). `+(Le?"No tool runs until it loads.\n":"Changes are paused until it loads; RLS still enforces row-level access.\n"))}}(e,t)}catch(e){Ge(),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 Ge(),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=et(),t=Xe(),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(()=>(Rk(),Sk)),n=new A;await t.connect(n);const{startUpdateCheck:r}=await Promise.resolve().then(()=>(ju(),Kd));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)});
|