authoring-cli 0.1.8 → 0.1.9

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/HELP.md CHANGED
@@ -143,9 +143,11 @@ authoring-cli validate-review-concepts
143
143
  - `authoring-cli set-case-significance --id SCTID --description-id ID --case-significance VALUE` — Set case significance
144
144
  - `authoring-cli set-acceptability --id SCTID --description-id ID [--us VALUE] [--gb VALUE]` — Set acceptability
145
145
  - `authoring-cli set-acceptability --id SCTID --entries '[...]'` — Set multiple acceptabilities atomically
146
- - `authoring-cli inactivate-description --id SCTID --description-id ID --indicator VALUE [--association-refset ID --association-target SCTID]` — Inactivate versioned description
146
+ - `authoring-cli inactivate-description --id SCTID --description-id ID --indicator VALUE [--association-target SCTID]` — Inactivate versioned description (association is always REFERS_TO)
147
147
  - `authoring-cli restore-description --id SCTID --description-id ID [--lang CODE] [--us VALUE] [--gb VALUE]` — Reactivate a synonym/PT inactivated above; requires at least one of `--lang`/`--us`/`--gb` (auto-demotes the dialect's current PT to ACCEPTABLE if restoring as PREFERRED)
148
148
  - `authoring-cli restore-description --id SCTID --description-id ID [--indicator VALUE]` — Reactivate an FSN instead (no `--lang`/`--us`/`--gb`); if another FSN is currently active, a never-versioned one is dropped for free, a published one needs `--indicator` to retire it in the same save
149
+ - `authoring-cli replace-fsn --id SCTID --term "TERM" --indicator VALUE [--description-id ID] [--association-target SCTID]` — Retire the current FSN and add its replacement in one save
150
+ - `authoring-cli set-description-inactivation-reason --id SCTID --description-id ID --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id SCTID]` — Assign or retarget the reason on an already-inactive description (`--target-id` required only for `NOT_SEMANTICALLY_EQUIVALENT`); 409s if the description is still active or if the current reason has already been published
149
151
 
150
152
  ### Relationships & Axioms
151
153
  - `authoring-cli add-relationship --id SCTID --type SCTID --target SCTID [--group N]` — Add relationship
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var dr=Object.create;var ne=Object.defineProperty;var ur=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var pr=Object.getPrototypeOf,mr=Object.prototype.hasOwnProperty;var fr=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},dt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lr(t))!mr.call(e,o)&&o!==r&&ne(e,o,{get:()=>t[o],enumerable:!(n=ur(t,o))||n.enumerable});return e};var T=(e,t,r)=>(r=e!=null?dr(pr(e)):{},dt(t||!e||!e.__esModule?ne(r,"default",{value:e,enumerable:!0}):r,e)),gr=e=>dt(ne({},"__esModule",{value:!0}),e);var Os={};fr(Os,{COMMANDS:()=>ct,main:()=>cr,parsePositionals:()=>ir});module.exports=gr(Os);var q={production:{imsEndpoint:"https://authoring.ihtsdotools.org/",terminologyServerEndpoint:"https://authoring.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://authoring.ihtsdotools.org/authoring-services/",cookieName:"ims-ihtsdo"},uat:{imsEndpoint:"https://uat-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://uat-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://uat-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"uat-ims-ihtsdo"},dev:{imsEndpoint:"https://dev-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://dev-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://dev-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"dev-ims-ihtsdo"}},yr={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},re=Object.keys(q);function ut(e){return yr[e.trim().toLowerCase()]??null}var Q="uat",Ks=q.uat.imsEndpoint,Ls=q.uat.terminologyServerEndpoint,Bs=q.uat.authoringServicesEndpoint;var kr=T(require("http")),hr=T(require("https"));function I(e,t={}){let{method:r="GET",cookie:n,body:o,headers:s={},timeoutMs:i=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(h){c(h);return}let u=d.protocol==="https:"?hr:kr,l=o!==void 0?JSON.stringify(o):void 0,p={accept:"application/json",...s};if(l!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(l))),n){let h=n.replace(/[^\x20-\x7e\t]/g,"");h&&(p.cookie=h)}let g=!1,y=u.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:p},h=>{let S="";h.on("data",$=>{S+=$}),h.on("end",()=>{if(g)return;g=!0,clearTimeout(k);let $=h.statusCode??0,P=(h.headers["content-type"]??"").includes("application/json"),O=null,U=!1;if(S)try{O=JSON.parse(S)}catch{U=!P}a({statusCode:$,body:O,rawBody:S,sessionExpired:U})})});y.on("error",h=>{g||(g=!0,clearTimeout(k),c(h))});let k=setTimeout(()=>{g||(g=!0,y.destroy(),c(new Error(`Request to ${e} timed out after ${i}ms`)))},i);l!==void 0&&y.write(l),y.end()})}var F="900000000000509007",V="900000000000508004";var lt={[F]:"en-us",[V]:"en-gb"},pt={[F]:"true",[V]:"true"},Cr={},Ir={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:lt,dialectDefaults:pt,readOnlyDialects:Cr,defaultLanguage:"en"};function mt(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Ir;let t={[F]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let u=d[1];t[String(e[c])]=u,o.length===0&&o.push(u)}}let s=e.requiredLanguageRefsets;if(Array.isArray(s))for(let c of s){if(typeof c!="object"||c===null)continue;let d=null,u=null;for(let[y,k]of Object.entries(c))y.length===2&&(d=y,u=String(k));if(!d||!u)continue;let l=c.dialectName;t[u]=typeof l=="string"?l:d;let p=c.default;p==="true"&&!o.includes(d)&&o.push(d),p!=null&&(r[u]=String(p));let g=c.readOnly;g!=null&&(n[u]=String(g))}let i=e.optionalLanguageRefsets;if(Array.isArray(i))for(let c of i)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?lt:t,dialectDefaults:a?pt:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function we(e,t,r,n){let o={};for(let s of Object.keys(e.dialects)){let i=e.dialects[s];e.isExtension&&!r?i.includes(n)?o[s]="PREFERRED":i.includes(e.defaultLanguage)&&(o[s]="ACCEPTABLE"):i.includes(n)&&(o[s]=t),e.dialectDefaults[s]==="false"&&!r&&delete o[s],e.readOnlyDialects[s]==="true"&&delete o[s]}return o}function se(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[F]:"PREFERRED"}:we(e,"PREFERRED",t,"en")}var xr="900000000000207008";function ft(e){return e.replace(/\/$/,"")}function R(e){return ft(e.terminologyServerEndpoint)}function A(e){return ft(e.authoringServicesEndpoint)}function gt(e){return`${new URL(A(e)).origin}/authoring-traceability-service`}function J(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,s=!t.projectKey&&!t.taskKey,i=t.branchPath||(s?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(i||(i=await br(e,n,o)??void 0),i?{ok:!0,projectKey:n,taskKey:o,branchPath:i}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function G(e,t){let r=R(e),n=await I(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${n.statusCode}).`};let o=t.split("/").filter(Boolean),s=o[o.length-1],i=o.slice(0,-1).join("/");if(!s||!i)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await I(`${r}/branches`,{method:"POST",body:{parent:i,name:s},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function br(e,t,r){let n=`${A(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body?.branchPath??null}async function yt(e,t,r){let n=r?.get(t);if(n)return n;let o=`${A(e)}/projects/${t}`,i=(await I(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,i),i}async function M(e,t,r){let n=await yt(e,t,r),o=n.multipleModuleEditingDisabled,s=!o||o==="false";return n.expectedExtensionModules?.length&&s?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:xr}async function H(e,t,r){let n=await yt(e,t,r);return mt(n)}async function Ae(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await I(r,{cookie:t,timeoutMs:8e3});return n.statusCode>=200&&n.statusCode<300&&n.body?n.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${n.statusCode} from ${r}`),null)}var kt=T(require("crypto"));var Sr="116680003";function X(e,t,r,n,o="PREFERRED",s=!1){let i=e==="FSN"?se(n,s):we(n,o,s,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:i}}async function ht(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:s,taskKey:i,branchPath:a}=o,c=J(a),d=t.moduleId||await M(e,s,n),u=await H(e,s,n),l=t.preferredTerm||t.fsn,p=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,g={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[X("FSN",p,d,u,"PREFERRED",!0),X("SYNONYM",l,d,u,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:kt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:Sr},target:{conceptId:t.parentConceptId}}]}]},y=`${R(e)}/browser/${c}/${s}/${i}/concepts/?validate=true`,k=await I(y,{method:"POST",body:g,cookie:e.cookie});if(k.sessionExpired){let $="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: SESSION EXPIRED`),{statusCode:401,body:{error:$}}}let h=k.body,S=h&&"conceptId"in h?h.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: ${k.statusCode<300?"OK":"FAILED ("+k.statusCode+")"} \u2014 ${p}`+(S?` \u2192 ${S}`:"")),typeof S=="string"&&e.onValidationResults?.(S,h?.validationResults),{statusCode:k.statusCode,body:k.body}}function Z(e){return typeof e=="object"&&e!==null}function vr(e,t,r){let n=Array.isArray(e[r])?e[r]:[],o=[];for(let s of n){if(s.active===!1||typeof s.axiomId!="string")continue;(Array.isArray(s.relationships)?s.relationships:[]).forEach((a,c)=>{let d=a.type;if((Z(d)?d.conceptId:void 0)!==t)return;let l=a.target;o.push({axiomId:s.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:Z(l)?l.conceptId:void 0,targetFsn:Z(l)&&Z(l.fsn)?l.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return o}async function ie(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${R(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(o,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(t.attributeType&&s.statusCode>=200&&s.statusCode<300&&Z(s.body)){let i=t.gci?"gciAxioms":"classAxioms",a=vr(s.body,t.attributeType,i);return{statusCode:s.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:a}}}return{statusCode:s.statusCode,body:s.body}}async function ae(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={limit:t.limit??50,expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let s=`${R(e)}/${n.branchPath}/concepts/search`,i=await I(s,{method:"POST",body:o,cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let a=(i.body?.items??[]).map(c=>({conceptId:c.conceptId,fsn:c.fsn?.term,pt:c.pt?.term,active:c.active,moduleId:c.moduleId}));return{statusCode:i.statusCode,body:{total:i.body?.total??a.length,items:a}}}async function Ct(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=new URLSearchParams;typeof t.stated=="boolean"&&o.set("stated",String(t.stated)),typeof t.limit=="number"&&o.set("limit",String(t.limit)),typeof t.offset=="number"&&o.set("offset",String(t.offset));let s=o.toString(),i=`${R(e)}/${n.branchPath}/concepts/${t.conceptId}/references`+(s?`?${s}`:""),a=await I(i,{cookie:e.cookie});return a.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:a.statusCode,body:a.body}}var je=T(require("crypto"));function It(e){return typeof e=="object"&&e!==null}function Tr(e){let t=e.type,r=e.target,n=It(t)?t.conceptId:void 0,o=It(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function Rr(e,t){let r=[...t];for(let n of e){let o=r.findIndex(s=>s.typeId===n.typeId&&s.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function xt(e,t,r){let n=new Map;for(let i of e){let a=typeof i.groupId=="number"?i.groupId:0,c=n.get(a);c?c.push(i):n.set(a,[i])}let o=[];for(let[i,a]of n){if(r!=null?i!==r:i===0)continue;let c=a.map(Tr).filter(d=>d!=null);Rr(t,c)&&o.push(i)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let s=o[0];return{ok:!0,groupId:s,relationships:n.get(s)}}var wr=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],Ar=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],$r=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Er=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],jr=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],Pe=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function Et(e){return Pe.includes(e)}function ee(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function ce(e){return typeof e=="object"&&e!==null}function bt(e){return ce(e)?ee(e,Er):e}function jt(e){if(!ce(e))return e;let t=ee(e,$r);return"type"in t&&(t.type=bt(t.type)),"target"in t&&(t.target=bt(t.target)),t}function Pr(e){return ce(e)?ee(e,Ar):e}function St(e){if(!ce(e))return e;let t=ee(e,jr);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(jt)),t}function Ne(e){let t=ee(e,wr);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(Pr)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(jt)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(St)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(St)),t}function Nr(e){return new Promise(t=>setTimeout(t,e))}function Dr(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var $e=[300,600,1200,2400,4800],vt=new Map;function Or(e,t){let n=(vt.get(e)??Promise.resolve()).then(t,t);return vt.set(e,n.then(()=>{},()=>{})),n}async function w(e,t,r,n){try{return await Or(t.branchPath,()=>Fr(e,t,r,n))}catch(o){return{statusCode:500,body:{error:o instanceof Error?o.message:String(o)}}}}async function Fr(e,t,r,n){for(let o=0;;o++){let s=R(e),i=`${s}/browser/${t.branchPath}/concepts/${r}`,a=await I(i,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,d=n(c);if(d)return d;let u=J(t.branchPath),l=`${s}/browser/${u}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await I(l,{method:"PUT",body:Ne(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(Dr(p)&&o<$e.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${o+1}/${$e.length})`),await Nr($e[o]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let g=p.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:p.statusCode,body:p.body}}}var Tt=["PREFERRED","ACCEPTABLE"];async function Pt(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.type)return{statusCode:400,body:{error:"conceptId, term, and type are required."}};if(t.type!=="FSN"&&t.type!=="SYNONYM")return{statusCode:400,body:{error:"type must be FSN or SYNONYM."}};if(t.acceptability&&!Tt.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${Tt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await M(e,o.projectKey,n),i=await H(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(X(t.type,a,s,i,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,null})}async function Nt(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),a.relationships=c,null})}async function Dt(e,t,r){if(!t.conceptId||!t.status)return{statusCode:400,body:{error:"conceptId and status are required."}};if(t.status!=="PRIMITIVE"&&t.status!=="FULLY_DEFINED")return{statusCode:400,body:{error:"status must be PRIMITIVE or FULLY_DEFINED."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];return a?(a.definitionStatus=t.status,s.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}}})}async function Ot(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>o.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(o.active=!1,o.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(o.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function Ft(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};if(!t.term&&!t.caseSignificance)return{statusCode:400,body:{error:"At least one of term or caseSignificance must be provided."}};if(t.caseSignificance&&!Et(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Pe.join(", ")}.`}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(i.term=t.term),t.caseSignificance&&(i.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Kt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!Et(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Pe.join(", ")}.`}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?(i.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var Ee=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Rt(e){return Ee.includes(e)}function Lt(e){return e.us&&!Rt(e.us)?{statusCode:400,body:{error:`us must be one of: ${Ee.join(", ")}.`}}:e.gb&&!Rt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${Ee.join(", ")}.`}}:null}function Bt(e){return e.descriptionId?!e.lang&&!e.us&&!e.gb?{statusCode:400,body:{error:`Entry for description ${e.descriptionId} must set at least one of lang, us, or gb.`}}:Lt(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function De(e,t,r){let n=e.find(s=>s.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[F]:o[F]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[V]:o[V]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function Mt(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},o=Bt(n);if(o)return o;let s=await C(e,t,r);return s.ok?w(e,s,t.conceptId,i=>{let a=Array.isArray(i.descriptions)?i.descriptions:[];return De(a,t.conceptId,n)}):{statusCode:400,body:{error:s.error}}}async function _t(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(t.entries)||t.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of t.entries){let s=Bt(o);if(s)return s}let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[];for(let i of t.entries){let a=De(s,t.conceptId,i);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function Ut(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[],i=s.findIndex(a=>a.descriptionId===t.descriptionId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(s.splice(i,1),o.descriptions=s,null)}):{statusCode:400,body:{error:n.error}}}async function qt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?i.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(i.active=!1,i.inactivationIndicator=t.indicator,i.acceptabilityMap={},t.associationRefsetId&&t.associationTargetId&&(i.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}function wt(e,t,r){for(let n of e){if(n.descriptionId===t||n.active===!1)continue;let o=n.acceptabilityMap;o?.[r]==="PREFERRED"&&(n.acceptabilityMap={...o,[r]:"ACCEPTABLE"})}}async function Vt(e,t,r,n=new Map){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},s=Lt(o);if(s)return s;let i=!!(t.lang||t.us||t.gb),a=await C(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await H(e,a.projectKey,n);return w(e,a,t.conceptId,d=>{let u=Array.isArray(d.descriptions)?d.descriptions:[],l=u.find(g=>g.descriptionId===t.descriptionId);if(!l)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(l.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(l.type==="FSN"){if(i)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let g=u.filter(y=>y.type==="FSN"&&y.active!==!1&&y.descriptionId!==t.descriptionId);if(g.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${g.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(g.length===1){let y=g[0];if(y.effectiveTime==null)u.splice(u.indexOf(y),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(y.descriptionId)} in the same save.`}};y.active=!1,y.inactivationIndicator=t.indicator,y.acceptabilityMap={},t.associationRefsetId&&t.associationTargetId&&(y.associationTargets={[t.associationRefsetId]:[t.associationTargetId]})}}return l.active=!0,delete l.inactivationIndicator,delete l.associationTargets,l.acceptabilityMap=se(c,!1),d.descriptions=u,null}if(!i)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};l.active=!0,delete l.inactivationIndicator,delete l.associationTargets;let p=De(u,t.conceptId,o);return p||(o.us==="PREFERRED"&&wt(u,t.descriptionId,F),o.gb==="PREFERRED"&&wt(u,t.descriptionId,V),null)})}async function Jt(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await M(e,o.projectKey,n),i=await H(e,o.projectKey,n),a=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[],u;if(t.descriptionId){if(u=d.find(l=>l.descriptionId===t.descriptionId),!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(u.type)}, not an FSN.`}}}else{let l=d.filter(p=>p.type==="FSN"&&p.active!==!1);if(l.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${l.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};u=l[0]}return u.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(u.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(u.active=!1,u.inactivationIndicator=t.indicator,u.acceptabilityMap={},t.associationRefsetId&&t.associationTargetId&&(u.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),d.push(X("FSN",a,s,i,"PREFERRED",!1)),c.descriptions=d,null)})}async function Oe(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Gt(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Fe(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await M(e,o.projectKey,n);return w(e,o,t.conceptId,i=>{let a=Array.isArray(i.classAxioms)?i.classAxioms:[];return a.push({axiomId:je.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),i.classAxioms=a,null})}async function Ht(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await M(e,o.projectKey,n);return w(e,o,t.conceptId,i=>{let a=Array.isArray(i.gciAxioms)?i.gciAxioms:[];return a.push({axiomId:je.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),i.gciAxioms=a,null})}async function Yt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.findIndex(a=>a.axiomId===t.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(s.splice(i,1),o.classAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function Ke(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.find(c=>c.axiomId===t.axiomId);return i?i.active===!1?{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}}:i.effectiveTime==null?{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}}:s.filter(c=>c!==i&&c.active!==!1).length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:(i.active=!1,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}var Kr="116680003";function At(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function Lr(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let s of r)s?.id&&t.push({active:!0,groupId:0,type:{conceptId:Kr},target:{conceptId:s.id}});let n=Array.isArray(e.attributes)?e.attributes:[];for(let s of n)t.push(At(s,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((s,i)=>{let a=Array.isArray(s.attributes)?s.attributes:[];for(let c of a)t.push(At(c,i+1))}),t}async function Wt(e,t,r,n){let o=R(e),s=await I(`${o}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(s.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{ok:!1,result:{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:s.body,undetermined:!0}}};let i=Array.isArray(s.body.classAxioms)?s.body.classAxioms:[],a;if(n){if(a=i.find(c=>c.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`,undetermined:!0}}}}else{let c=i.filter(d=>d.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var Br="116680003";function Mr(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==Br?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function _r(e,t,r){let n=R(e),o=await I(`${n}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(o.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(o.statusCode<200||o.statusCode>=300||!o.body)return{ok:!1,result:{statusCode:o.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:o.body,undetermined:!0}}};let s=Lr(o.body);return s.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`,undetermined:!0}}}:{ok:!0,value:s}}async function Ur(e,t,r,n){let o=await Wt(e,t,r,n);if(!o.ok)return o;let s=await _r(e,t,r);return s.ok?{ok:!0,value:{axiom:o.value.axiom,axiomId:o.value.axiomId,targetRelationships:s.value}}:s}function qr(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let n=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${n}`}function $t(e){let t=new Map;for(let o of e){if(o.active===!1)continue;let s=typeof o.groupId=="number"?o.groupId:0,i=t.get(s)??[];i.push(qr(o)),t.set(s,i)}let r=(t.get(0)??[]).slice().sort(),n=[];for(let[o,s]of t)o!==0&&n.push(s.slice().sort());return{ungrouped:r,groups:n}}function Vr(e,t){let r=$t(e),n=$t(t);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(i=>i.join("|")).sort(),s=n.groups.map(i=>i.join("|")).sort();return o.join("||")===s.join("||")}async function de(e,t,r,n=new Map){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=await Ur(e,o,t.conceptId,t.axiomId);if(!s.ok)return s.result;let{axiom:i,axiomId:a,targetRelationships:c}=s.value,d=Array.isArray(i.relationships)?i.relationships:[];if(Vr(d,c))return e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${o.projectKey}/${o.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:a,alreadyConformed:!0}};if(!(i.effectiveTime!=null))return Oe(e,{conceptId:t.conceptId,axiomId:a,relationships:c,projectKey:o.projectKey,taskKey:o.taskKey},r);let l=await Fe(e,{conceptId:t.conceptId,relationships:c,moduleId:typeof i.moduleId=="string"?i.moduleId:void 0,definitionStatus:i.definitionStatus,projectKey:o.projectKey,taskKey:o.taskKey},r,n);if(l.statusCode<200||l.statusCode>=300)return l;let p=await Ke(e,{conceptId:t.conceptId,axiomId:a,projectKey:o.projectKey,taskKey:o.taskKey},r);return p.statusCode<200||p.statusCode>=300?{statusCode:p.statusCode,body:{error:`Added the transformed axiom but failed to inactivate published axiom ${a}: ${JSON.stringify(p.body)}`,addResult:l.body}}:{statusCode:p.statusCode,body:{replacedAxiomId:a,addResult:l.body,inactivateResult:p.body}}}async function ue(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Wt(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:s,axiomId:i}=o.value,a=Array.isArray(s.relationships)?s.relationships:[];return Mr(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:i,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:i,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function zt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!t.relationshipId&&t.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=t.relationshipId?a.findIndex(u=>u.relationshipId===t.relationshipId):t.relationshipIndex,d=c>=0?a[c]:void 0;return d?d.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),i.relationships=a,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function Qt(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.attributes)||t.attributes.length===0)return{statusCode:400,body:{error:"conceptId, axiomId, and a non-empty attributes array are required."}};for(let o of t.attributes)if(!o||typeof o.typeId!="string"||typeof o.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=xt(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let d=c.relationships.find(u=>u.effectiveTime!=null);return d?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(d.relationshipId)}) with effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(i.relationships=a.filter(u=>(typeof u.groupId=="number"?u.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function Xt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.gciAxioms)?o.gciAxioms:[],i=s.findIndex(a=>a.axiomId===t.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(s.splice(i,1),o.gciAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function Zt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return i?i.effectiveTime==null?{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}}:i.active===!1?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}}:(i.active=!1,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}var Jr=8;async function le(e,t,r,n){let o=[],s=[],i=0,a=async()=>{for(;;){let d=i++;if(d>=r.length)return;let u=r[d];try{let l=await ue(e,{conceptId:u.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),p=l.body;if(l.statusCode<200||l.statusCode>=300){s.push({...u,error:p?.error??`HTTP ${l.statusCode}`});continue}p?.conclusive&&o.push({...u,axiomId:p.axiomId})}catch(l){s.push({...u,error:l instanceof Error?l.message:String(l)})}}},c=Math.min(Jr,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:o,skipped:s}}async function eo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await ae(e,{...t,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let s=o.body?.items??[],i=s.map(d=>({conceptId:d.conceptId,fsn:d.fsn,pt:d.pt})),{matched:a,skipped:c}=await le(e,n,i,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:s.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function to(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=R(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await I(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:i.body}};if(i.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{method:"DELETE",cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${n.projectKey}/${n.taskKey}: ${c.statusCode<300?"OK":"FAILED ("+c.statusCode+")"} \u2014 ${t.conceptId}`),c.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:c.body}}:{statusCode:c.statusCode,body:c.body})}function Gr(e){let t=[];for(let r of e)t.some(o=>o.componentId===r.componentId&&o.severity===r.severity&&o.conceptId===r.conceptId&&o.message===r.message)||t.push(r);return t}async function pe(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=R(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await I(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:i.body}};let a=J(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await I(c,{method:"POST",body:Ne(i.body),cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let u=Array.isArray(d.body)?Gr(d.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:u,hasErrors:u.some(l=>l.severity==="ERROR"),hasWarnings:u.some(l=>l.severity==="WARNING")}}}var oo=200;async function Hr(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${R(e)}/browser/${t}/concepts/bulk-load`,s=!0;for(let i=0;i<r.length;i+=oo){let a=r.slice(i,i+oo),c=await I(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){s=!1;continue}for(let d of c.body)n.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:n,resolved:s}}async function K(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${gt(e)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,s=await I(o,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(s.statusCode<200||s.statusCode>=300)return{statusCode:s.statusCode,body:{error:"Could not fetch traceability for branch.",details:s.body}};let i=new Map,a=new Map,c=(k,h,S,$)=>{let j=k.get(h);j?($.forEach(P=>P&&j.componentSubTypes.add(P)),j.lastUpdatedTime=S):k.set(h,{conceptId:h,lastUpdatedTime:S,componentSubTypes:new Set($.filter(P=>!!P))})};for(let k of s.body?.content??[])if(!(k.activityType!=="CONTENT_CHANGE"&&k.activityType!=="CLASSIFICATION_SAVE"))for(let h of k.conceptChanges??[]){let S=String(h.conceptId),$=h.componentChanges??[],j=$.map(O=>O.componentSubType);if(k.activityType==="CLASSIFICATION_SAVE"){c(a,S,k.commitDate,j);continue}let P=$.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(P?i:a,S,k.commitDate,j)}for(let k of i.keys())a.delete(k);let d=[...new Set([...i.keys(),...a.keys()])],{terms:u,resolved:l}=await Hr(e,n.branchPath,d),p=k=>[...k.values()].sort((h,S)=>(S.lastUpdatedTime??"").localeCompare(h.lastUpdatedTime??"")).map(h=>{let S=l&&!u.has(h.conceptId);return{conceptId:h.conceptId,fsn:u.get(h.conceptId)?.fsn,pt:u.get(h.conceptId)?.pt,...S?{deleted:!0}:{},lastUpdatedTime:h.lastUpdatedTime,changedComponentTypes:[...h.componentSubTypes]}}),g=p(i),y=p(a);return{statusCode:200,body:{branchPath:n.branchPath,...l?{summary:{concepts:g.length,conceptsDeleted:g.filter(k=>k.deleted).length,conceptsClassified:y.length}}:{},concepts:g,conceptsClassified:y}}}async function no(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await K(e,t,r);if(o.statusCode<200||o.statusCode>=300){let u=o.body;return{statusCode:o.statusCode,body:{error:u.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=s.filter(u=>!u.deleted),a=i.map(u=>({conceptId:u.conceptId,fsn:u.fsn})),{matched:c,skipped:d}=await le(e,n,a,r);return{statusCode:200,body:{branchPath:n.branchPath,totalReviewed:i.length,matched:c.length,skipped:d.length,skippedDeleted:s.length-i.length,results:c,skippedConcepts:d}}}async function Yr(e,t,r,n){let o=[];for(let s of r){if(s.deleted){o.push({conceptId:s.conceptId,fsn:s.fsn,outcome:"deleted"});continue}let i=await pe(e,{conceptId:s.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),a=i.body;if(i.statusCode<200||i.statusCode>=300){o.push({conceptId:s.conceptId,fsn:s.fsn,outcome:"failed",error:a.error??`HTTP ${i.statusCode}`});continue}let c=a.validationResults??[];o.push({conceptId:s.conceptId,fsn:s.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return o}async function ro(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await K(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=await Yr(e,n,s,r),a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:i}}}async function L(e,t,r){let n=`${A(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body??null}var Le=new Set;function so(e){if(!(!e||typeof e!="object"))for(let t of Le)t(e)}function Wr(e){return Le.add(e),()=>Le.delete(e)}function zr(e,t){return t.entityType!==void 0&&e.entityType!==t.entityType?!1:e.task?e.task===t.taskKey&&e.project===t.projectKey:e.project?e.project===t.projectKey:e.branchPath===t.branchPath}function me(e){let t=()=>{};return{promise:new Promise(n=>{t=Wr(o=>{zr(o,e)&&(t(),n(o))})}),cancel:t}}var Ue=["RUNNING","BUILDING","SCHEDULED","QUEUED"],qe=["QUEUED","SCHEDULED","RUNNING"],Qr=["Promoted","Completed"],io=5e3;function _e(e){return new Promise(t=>setTimeout(t,e))}async function Xr(e,t,r){let n=0;for(;;){let{done:o,value:s}=await e();if(o)return{value:s,timedOut:!1};if(n>=r)return{value:s,timedOut:!0};n++,await _e(t)}}function Zr(){let e=[9e4];for(let t=0;t<3;t++)e.push(1e4);for(let t=0;t<12;t++)e.push(5e3);return e}var es=Zr(),ts=180;function os(){let e=[3e5];for(let t=0;t<5;t++)e.push(6e4);for(let t=0;t<10;t++)e.push(3e4);return e}var ns=os(),rs=900;async function uo(e,t,r,n,o){let s=r*1e3,i=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=n?me(n):void 0,u=await Promise.race(d?[_e(c).then(()=>{}),d.promise]:[_e(c).then(()=>{})]);if(d?.cancel(),u){let g=u.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:l,value:p}=await e();if(l)return{value:p,timedOut:!1};if(Date.now()-i>=s)return{value:p,timedOut:!0};a++}}async function lo(e,t,r){let n=await L(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&Qr.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${A(e)}/projects/${t}/tasks/${r}`;await I(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function Ve(e,t,r){let n=`${A(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await I(n,{method:"POST",body:{},cookie:e.cookie}),(await L(e,t,r))?.latestClassificationJson}async function ao(e,t,r,n,o){let s,{value:i,timedOut:a}=await uo(async()=>{let d=(await Ve(e,t,r))?.status;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||Ue.includes(d)),value:d}},es,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function Be(e,t,r){let n=`${R(e)}/${t}/classifications`,o=await I(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(s=>s.id===r)??o.body.items[o.body.items.length-1]}async function po(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,i=await Ve(e,o,s);return i?{statusCode:200,body:{hasClassification:!0,jobId:i.id,status:i.status,running:Ue.includes(i.status),latestClassificationJson:i}}:{statusCode:200,body:{hasClassification:!1}}}async function fe(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await lo(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??ts,d=await Ve(e,o,s),u=d?.status,l=d?.id;if(l&&u&&Ue.includes(u)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${l} already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:P}=await ao(e,o,s,i,c),O=await Be(e,i,l),U={accepted:!1};return!P&&j==="COMPLETED"&&(U=await Me(e,i,o,s,l)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: attached job ${l} final status ${j??"unknown"}${P?" (timed out waiting)":""}, save ${JSON.stringify(U)}`),{statusCode:200,body:{jobId:l,finalStatus:j,timedOut:P,details:O,save:U,attachedToExisting:!0}}}if(l&&u==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${l} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await Be(e,i,l),P=await Me(e,i,o,s,l);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: accepted existing job ${l}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:l,finalStatus:"COMPLETED",timedOut:!1,details:j,save:P,acceptedExisting:!0}}}let p=`${A(e)}/projects/${o}/tasks/${s}/classifications`,g=await I(p,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: start failed (HTTP ${g.statusCode}) \u2014 raw body: ${g.rawBody}`),{statusCode:g.statusCode||500,body:{error:"Failed to start classification.",details:g.body??g.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: started (${g.body.status??"unknown"})`);let y=g.body.id;if(!t.wait)return{statusCode:200,body:{jobId:y,status:g.body.status}};let{finalStatus:k,timedOut:h}=await ao(e,o,s,i,c),S=await Be(e,i,y),$={accepted:!1};return!h&&k==="COMPLETED"&&($=await Me(e,i,o,s,y)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: final status ${k??"unknown"}${h?" (timed out waiting)":""}, save ${JSON.stringify($)}`),{statusCode:200,body:{jobId:y,finalStatus:k,timedOut:h,details:S,save:$}}}var ss=["SAVED","STALE","SAVE_FAILED"],is=120;async function Me(e,t,r,n,o){let s=`${R(e)}/${t}/classifications/${o}`,i=await I(s,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(i.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(i.statusCode<200||i.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${i.statusCode}).`};let a=Math.ceil(is*1e3/io),{value:c,timedOut:d}=await Xr(async()=>{let l=(await I(s,{cookie:e.cookie})).body?.status;return{done:!!l&&ss.includes(l),value:l}},io,a);return d?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function mo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,a=(await L(e,o,s))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&qe.includes(a)}}}async function co(e,t,r,n,o){let s,{value:i,timedOut:a}=await uo(async()=>{let d=(await L(e,t,r))?.latestValidationStatus;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||qe.includes(d)),value:d}},ns,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function fo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await lo(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??rs,u=(await L(e,o,s))?.latestValidationStatus;if(u&&qe.includes(u)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: validation already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:k,timedOut:h}=await co(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: attached run final status ${k??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:k,timedOut:h,attachedToExisting:!0}}}let l=`${A(e)}/projects/${o}/tasks/${s}/validation`;typeof t.enableMrcmValidation=="boolean"&&(l+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await I(l,{method:"POST",body:{},cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(p.statusCode<200||p.statusCode>=300)return{statusCode:p.statusCode,body:{error:"Failed to start validation.",details:p.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:y}=await co(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: final status ${g??"unknown"}${y?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:y}}}var as=8;function cs(e){return typeof e=="string"&&/timed out after \d+ms/.test(e)}async function go(e,t,r,n,o,s){let i=0,a=0,c=async()=>{for(;;){let u=a++;if(u>=r.length)return;let l=r[u];try{let p=await de(e,{conceptId:l.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),g=p.body;p.statusCode<200||p.statusCode>=300?g?.undetermined?n.set(l.conceptId,{outcome:"skipped",error:g.error??`HTTP ${p.statusCode}`}):n.set(l.conceptId,{outcome:"failed",error:g?.error??`HTTP ${p.statusCode}`}):n.set(l.conceptId,{outcome:g?.alreadyConformed?"conformed":"transformed"})}catch(p){n.set(l.conceptId,{outcome:"failed",error:p instanceof Error?p.message:String(p)})}i+=1,e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: ${s} \u2014 ${l.conceptId} (${i}/${r.length})`)}},d=Math.min(as,r.length);await Promise.all(Array.from({length:d},()=>c()))}async function ds(e,t,r,n){let o=new Map;return await go(e,t,r,o,n,"axiom checked"),await us(e,t,r,o,n),o}async function us(e,t,r,n,o){let s=r.filter(i=>{let a=n.get(i.conceptId);return a?.outcome==="failed"&&cs(a.error)});s.length!==0&&(e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: reprocessing ${s.length} concept(s) that timed out on the first pass`),await go(e,t,s,n,o,"axiom rechecked"))}async function yo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await fe(e,{projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath,wait:!0},r);if(o.statusCode===401)return o;let s=o.body,i=o.statusCode>=200&&o.statusCode<300?{jobId:s?.jobId,finalStatus:s?.finalStatus,timedOut:s?.timedOut,save:s?.save}:{error:s?.error??`HTTP ${o.statusCode}`},a=await K(e,t,r);if(a.statusCode<200||a.statusCode>=300){let y=a.body;return{statusCode:a.statusCode,body:{error:y.error??"Could not list concepts for review."}}}let c=a.body.concepts??[],d=c.filter(y=>!y.deleted).map(y=>({conceptId:y.conceptId,fsn:y.fsn})),u=await ds(e,n,d,r),l=[];for(let[y,k]of c.entries()){if(k.deleted){l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"deleted"});continue}let h=u.get(k.conceptId),S=await ie(e,{conceptId:k.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),$=S.body,j=`(${y+1}/${c.length})`;if(S.statusCode<200||S.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: FAILED (${S.statusCode}) \u2014 ${k.conceptId} ${j}`),l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"failed",error:$?.error??`HTTP ${S.statusCode}`,axiom:h});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: OK \u2014 ${k.conceptId} ${j}`),l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"fetched",concept:S.body,axiom:h})}let p=y=>l.filter(k=>k.outcome===y).length,g=y=>Array.from(u.values()).filter(k=>k.outcome===y).length;return{statusCode:200,body:{branchPath:n.branchPath,classification:i,summary:{total:l.length,fetched:p("fetched"),skippedDeleted:p("deleted"),failed:p("failed"),axiomsTransformed:g("transformed"),axiomsConformed:g("conformed"),axiomsSkipped:g("skipped"),axiomsFailed:g("failed")},concepts:l}}}async function ko(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${A(e)}/projects${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function ho(e,t){let r=`${A(e)}/projects/${t}/tasks`;return(await I(r,{cookie:e.cookie})).body??[]}async function Co(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${A(e)}/projects/my-tasks${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function Io(e,t){let r=`${A(e)}/projects/${t.projectKey}/tasks`,n={summary:t.summary};t.description!==void 0&&(n.description=t.description),t.assigneeUsername&&(n.assignee={username:t.assigneeUsername});let o=await I(r,{method:"POST",body:n,cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}var ls=["FORWARD","DIVERGED"];async function ps(e,t){if(!t)return!1;let r=`${R(e)}/branches/${encodeURIComponent(t)}`,n=await I(r,{cookie:e.cookie});return ls.includes(n.body?.state??"")}var ms=["Promoted","Completed"];async function xo(e,t){let r=`${A(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};let o=n.body.status;if(o&&ms.includes(o))return{statusCode:409,error:`${t.projectKey}/${t.taskKey} has status ${o} \u2014 its work is already in the project, so the task cannot be deleted.`};if(o==="Deleted")return{statusCode:200,task:n.body,alreadyDeleted:!0};let s=await ps(e,n.body.branchPath),i=await I(r,{method:"PUT",body:{status:"DELETED"},cookie:e.cookie});return i.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:i.statusCode<200||i.statusCode>=300||!i.body?{statusCode:i.statusCode||500,error:`Failed to delete ${t.projectKey}/${t.taskKey} (HTTP ${i.statusCode})${i.rawBody?`: ${i.rawBody}`:""}`}:{statusCode:i.statusCode,task:i.body,hadUnpromotedChanges:s}}async function bo(e,t){let r=`${A(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await I(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var fs="IN_PROGRESS";async function So(e,t){let r=`${A(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};if(n.body.status!=="Deleted")return{statusCode:200,task:n.body,notDeleted:!0};let o=await I(r,{method:"PUT",body:{status:fs},cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}function vo(e){if(e==="o")return{type:"open"};if(e==="h")return{type:"heartbeat"};if(e.startsWith("a"))try{return{type:"message",messages:JSON.parse(e.slice(1))}}catch{return{type:"unknown",raw:e}}if(e.startsWith("c"))try{let[t,r]=JSON.parse(e.slice(1));return{type:"close",code:t,reason:r}}catch{return{type:"unknown",raw:e}}return{type:"unknown",raw:e}}function Je(e){return JSON.stringify([e])}function To(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",n="";for(let o=0;o<8;o++)n+=r[Math.floor(e()*r.length)];return`${t}/${n}/websocket`}function Ge(e,t={},r=""){let n=Object.entries(t).map(([o,s])=>`${o}:${s}`);return[e,...n,"",r].join(`
3
- `)+"\0"}function Ro(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
2
+ "use strict";var mr=Object.create;var ne=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var gr=Object.getOwnPropertyNames;var yr=Object.getPrototypeOf,kr=Object.prototype.hasOwnProperty;var hr=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},ut=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gr(t))!kr.call(e,o)&&o!==r&&ne(e,o,{get:()=>t[o],enumerable:!(n=fr(t,o))||n.enumerable});return e};var T=(e,t,r)=>(r=e!=null?mr(yr(e)):{},ut(t||!e||!e.__esModule?ne(r,"default",{value:e,enumerable:!0}):r,e)),Cr=e=>ut(ne({},"__esModule",{value:!0}),e);var Mi={};hr(Mi,{COMMANDS:()=>dt,main:()=>pr,parsePositionals:()=>ur});module.exports=Cr(Mi);var V={production:{imsEndpoint:"https://authoring.ihtsdotools.org/",terminologyServerEndpoint:"https://authoring.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://authoring.ihtsdotools.org/authoring-services/",cookieName:"ims-ihtsdo"},uat:{imsEndpoint:"https://uat-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://uat-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://uat-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"uat-ims-ihtsdo"},dev:{imsEndpoint:"https://dev-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://dev-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://dev-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"dev-ims-ihtsdo"}},Ir={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},re=Object.keys(V);function lt(e){return Ir[e.trim().toLowerCase()]??null}var z="uat",Ui=V.uat.imsEndpoint,Vi=V.uat.terminologyServerEndpoint,qi=V.uat.authoringServicesEndpoint;var xr=T(require("http")),br=T(require("https"));function I(e,t={}){let{method:r="GET",cookie:n,body:o,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(C){c(C);return}let u=d.protocol==="https:"?br:xr,l=o!==void 0?JSON.stringify(o):void 0,f={accept:"application/json",...i};if(l!==void 0&&(f["content-type"]="application/json",f["content-length"]=String(Buffer.byteLength(l))),n){let C=n.replace(/[^\x20-\x7e\t]/g,"");C&&(f.cookie=C)}let g=!1,y=u.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:f},C=>{let S="";C.on("data",$=>{S+=$}),C.on("end",()=>{if(g)return;g=!0,clearTimeout(k);let $=C.statusCode??0,P=(C.headers["content-type"]??"").includes("application/json"),O=null,U=!1;if(S)try{O=JSON.parse(S)}catch{U=!P}a({statusCode:$,body:O,rawBody:S,sessionExpired:U})})});y.on("error",C=>{g||(g=!0,clearTimeout(k),c(C))});let k=setTimeout(()=>{g||(g=!0,y.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);l!==void 0&&y.write(l),y.end()})}var F="900000000000509007",q="900000000000508004";var pt={[F]:"en-us",[q]:"en-gb"},mt={[F]:"true",[q]:"true"},Sr={},vr={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:pt,dialectDefaults:mt,readOnlyDialects:Sr,defaultLanguage:"en"};function ft(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return vr;let t={[F]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let u=d[1];t[String(e[c])]=u,o.length===0&&o.push(u)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let d=null,u=null;for(let[y,k]of Object.entries(c))y.length===2&&(d=y,u=String(k));if(!d||!u)continue;let l=c.dialectName;t[u]=typeof l=="string"?l:d;let f=c.default;f==="true"&&!o.includes(d)&&o.push(d),f!=null&&(r[u]=String(f));let g=c.readOnly;g!=null&&(n[u]=String(g))}let s=e.optionalLanguageRefsets;if(Array.isArray(s))for(let c of s)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?pt:t,dialectDefaults:a?mt:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function we(e,t,r,n){let o={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(n)?o[i]="PREFERRED":s.includes(e.defaultLanguage)&&(o[i]="ACCEPTABLE"):s.includes(n)&&(o[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete o[i],e.readOnlyDialects[i]==="true"&&delete o[i]}return o}function ie(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[F]:"PREFERRED"}:we(e,"PREFERRED",t,"en")}var Tr="900000000000207008";function gt(e){return e.replace(/\/$/,"")}function R(e){return gt(e.terminologyServerEndpoint)}function w(e){return gt(e.authoringServicesEndpoint)}function yt(e){return`${new URL(w(e)).origin}/authoring-traceability-service`}function J(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function h(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(s||(s=await Rr(e,n,o)??void 0),s?{ok:!0,projectKey:n,taskKey:o,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function G(e,t){let r=R(e),n=await I(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${n.statusCode}).`};let o=t.split("/").filter(Boolean),i=o[o.length-1],s=o.slice(0,-1).join("/");if(!i||!s)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await I(`${r}/branches`,{method:"POST",body:{parent:s,name:i},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function Rr(e,t,r){let n=`${w(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body?.branchPath??null}async function kt(e,t,r){let n=r?.get(t);if(n)return n;let o=`${w(e)}/projects/${t}`,s=(await I(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function M(e,t,r){let n=await kt(e,t,r),o=n.multipleModuleEditingDisabled,i=!o||o==="false";return n.expectedExtensionModules?.length&&i?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:Tr}async function H(e,t,r){let n=await kt(e,t,r);return ft(n)}async function $e(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await I(r,{cookie:t,timeoutMs:8e3});return n.statusCode>=200&&n.statusCode<300&&n.body?n.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${n.statusCode} from ${r}`),null)}var ht=T(require("crypto"));var Ar="116680003";function X(e,t,r,n,o="PREFERRED",i=!1){let s=e==="FSN"?ie(n,i):we(n,o,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function Ct(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await h(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:i,taskKey:s,branchPath:a}=o,c=J(a),d=t.moduleId||await M(e,i,n),u=await H(e,i,n),l=t.preferredTerm||t.fsn,f=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,g={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[X("FSN",f,d,u,"PREFERRED",!0),X("SYNONYM",l,d,u,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:ht.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:Ar},target:{conceptId:t.parentConceptId}}]}]},y=`${R(e)}/browser/${c}/${i}/${s}/concepts/?validate=true`,k=await I(y,{method:"POST",body:g,cookie:e.cookie});if(k.sessionExpired){let $="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: SESSION EXPIRED`),{statusCode:401,body:{error:$}}}let C=k.body,S=C&&"conceptId"in C?C.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: ${k.statusCode<300?"OK":"FAILED ("+k.statusCode+")"} \u2014 ${f}`+(S?` \u2192 ${S}`:"")),typeof S=="string"&&e.onValidationResults?.(S,C?.validationResults),{statusCode:k.statusCode,body:k.body}}function Z(e){return typeof e=="object"&&e!==null}function wr(e,t,r){let n=Array.isArray(e[r])?e[r]:[],o=[];for(let i of n){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let d=a.type;if((Z(d)?d.conceptId:void 0)!==t)return;let l=a.target;o.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:Z(l)?l.conceptId:void 0,targetFsn:Z(l)&&Z(l.fsn)?l.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return o}async function se(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${R(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await I(o,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(t.attributeType&&i.statusCode>=200&&i.statusCode<300&&Z(i.body)){let s=t.gci?"gciAxioms":"classAxioms",a=wr(i.body,t.attributeType,s);return{statusCode:i.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:a}}}return{statusCode:i.statusCode,body:i.body}}async function ae(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={limit:t.limit??50,expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let i=`${R(e)}/${n.branchPath}/concepts/search`,s=await I(i,{method:"POST",body:o,cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let a=(s.body?.items??[]).map(c=>({conceptId:c.conceptId,fsn:c.fsn?.term,pt:c.pt?.term,active:c.active,moduleId:c.moduleId}));return{statusCode:s.statusCode,body:{total:s.body?.total??a.length,items:a}}}async function It(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=new URLSearchParams;typeof t.stated=="boolean"&&o.set("stated",String(t.stated)),typeof t.limit=="number"&&o.set("limit",String(t.limit)),typeof t.offset=="number"&&o.set("offset",String(t.offset));let i=o.toString(),s=`${R(e)}/${n.branchPath}/concepts/${t.conceptId}/references`+(i?`?${i}`:""),a=await I(s,{cookie:e.cookie});return a.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:a.statusCode,body:a.body}}var Pe=T(require("crypto"));function xt(e){return typeof e=="object"&&e!==null}function $r(e){let t=e.type,r=e.target,n=xt(t)?t.conceptId:void 0,o=xt(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function Er(e,t){let r=[...t];for(let n of e){let o=r.findIndex(i=>i.typeId===n.typeId&&i.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function bt(e,t,r){let n=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=n.get(a);c?c.push(s):n.set(a,[s])}let o=[];for(let[s,a]of n){if(r!=null?s!==r:s===0)continue;let c=a.map($r).filter(d=>d!=null);Er(t,c)&&o.push(s)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let i=o[0];return{ok:!0,groupId:i,relationships:n.get(i)}}var jr=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],Pr=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],Nr=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Dr=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Or=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],Ne=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function Pt(e){return Ne.includes(e)}function ee(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function ce(e){return typeof e=="object"&&e!==null}function St(e){return ce(e)?ee(e,Dr):e}function Nt(e){if(!ce(e))return e;let t=ee(e,Nr);return"type"in t&&(t.type=St(t.type)),"target"in t&&(t.target=St(t.target)),t}function Fr(e){return ce(e)?ee(e,Pr):e}function vt(e){if(!ce(e))return e;let t=ee(e,Or);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Nt)),t}function De(e){let t=ee(e,jr);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(Fr)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Nt)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(vt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(vt)),t}function Kr(e){return new Promise(t=>setTimeout(t,e))}function Lr(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var Ee=[300,600,1200,2400,4800],Tt=new Map;function Br(e,t){let n=(Tt.get(e)??Promise.resolve()).then(t,t);return Tt.set(e,n.then(()=>{},()=>{})),n}async function A(e,t,r,n){try{return await Br(t.branchPath,()=>Mr(e,t,r,n))}catch(o){return{statusCode:500,body:{error:o instanceof Error?o.message:String(o)}}}}async function Mr(e,t,r,n){for(let o=0;;o++){let i=R(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await I(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,d=n(c);if(d)return d;let u=J(t.branchPath),l=`${i}/browser/${u}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,f=await I(l,{method:"PUT",body:De(c),cookie:e.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(Lr(f)&&o<Ee.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${o+1}/${Ee.length})`),await Kr(Ee[o]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${f.statusCode<300?"OK":"FAILED ("+f.statusCode+")"} \u2014 ${r}`);let g=f.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:f.statusCode,body:f.body}}}var Rt=["PREFERRED","ACCEPTABLE"];async function Dt(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.type)return{statusCode:400,body:{error:"conceptId, term, and type are required."}};if(t.type!=="FSN"&&t.type!=="SYNONYM")return{statusCode:400,body:{error:"type must be FSN or SYNONYM."}};if(t.acceptability&&!Rt.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${Rt.join(", ")}.`}};let o=await h(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n),s=await H(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return A(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(X(t.type,a,i,s,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,null})}async function Ot(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return A(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),a.relationships=c,null})}async function Ft(e,t,r){if(!t.conceptId||!t.status)return{statusCode:400,body:{error:"conceptId and status are required."}};if(t.status!=="PRIMITIVE"&&t.status!=="FULLY_DEFINED")return{statusCode:400,body:{error:"status must be PRIMITIVE or FULLY_DEFINED."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return A(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];return a?(a.definitionStatus=t.status,i.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}}})}async function Kt(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>o.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(o.active=!1,o.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(o.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function Lt(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};if(!t.term&&!t.caseSignificance)return{statusCode:400,body:{error:"At least one of term or caseSignificance must be provided."}};if(t.caseSignificance&&!Pt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Ne.join(", ")}.`}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(s.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(s.term=t.term),t.caseSignificance&&(s.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Bt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!Pt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Ne.join(", ")}.`}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?(s.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var je=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function At(e){return je.includes(e)}function Mt(e){return e.us&&!At(e.us)?{statusCode:400,body:{error:`us must be one of: ${je.join(", ")}.`}}:e.gb&&!At(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${je.join(", ")}.`}}:null}function _t(e){return e.descriptionId?!e.lang&&!e.us&&!e.gb?{statusCode:400,body:{error:`Entry for description ${e.descriptionId} must set at least one of lang, us, or gb.`}}:Mt(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function Oe(e,t,r){let n=e.find(i=>i.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[F]:o[F]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[q]:o[q]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function Ut(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},o=_t(n);if(o)return o;let i=await h(e,t,r);return i.ok?A(e,i,t.conceptId,s=>{let a=Array.isArray(s.descriptions)?s.descriptions:[];return Oe(a,t.conceptId,n)}):{statusCode:400,body:{error:i.error}}}async function Vt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(t.entries)||t.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of t.entries){let i=_t(o);if(i)return i}let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[];for(let s of t.entries){let a=Oe(i,t.conceptId,s);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function qt(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[],s=i.findIndex(a=>a.descriptionId===t.descriptionId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(i.splice(s,1),o.descriptions=i,null)}):{statusCode:400,body:{error:n.error}}}var de="REFERS_TO";async function Jt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(s.active=!1,s.inactivationIndicator=t.indicator,s.acceptabilityMap={},t.associationTargetId&&(s.associationTargets={[de]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}function wt(e,t,r){for(let n of e){if(n.descriptionId===t||n.active===!1||n.type!=="SYNONYM")continue;let o=n.acceptabilityMap;o?.[r]==="PREFERRED"&&(n.acceptabilityMap={...o,[r]:"ACCEPTABLE"})}}async function Gt(e,t,r,n=new Map){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},i=Mt(o);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await h(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await H(e,a.projectKey,n);return A(e,a,t.conceptId,d=>{let u=Array.isArray(d.descriptions)?d.descriptions:[],l=u.find(g=>g.descriptionId===t.descriptionId);if(!l)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(l.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(l.type==="FSN"){if(s)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let g=u.filter(y=>y.type==="FSN"&&y.active!==!1&&y.descriptionId!==t.descriptionId);if(g.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${g.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(g.length===1){let y=g[0];if(y.effectiveTime==null)u.splice(u.indexOf(y),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(y.descriptionId)} in the same save.`}};y.active=!1,y.inactivationIndicator=t.indicator,y.acceptabilityMap={},t.associationTargetId&&(y.associationTargets={[de]:[t.associationTargetId]})}}return l.active=!0,delete l.inactivationIndicator,delete l.associationTargets,l.acceptabilityMap=ie(c,!1),d.descriptions=u,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};l.active=!0,delete l.inactivationIndicator,delete l.associationTargets;let f=Oe(u,t.conceptId,o);return f||(o.us==="PREFERRED"&&wt(u,t.descriptionId,F),o.gb==="PREFERRED"&&wt(u,t.descriptionId,q),null)})}var _r="900000000000490003",$t=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function Ht(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!$t.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${$t.join(", ")}.`}};if(t.reason==="NOT_SEMANTICALLY_EQUIVALENT"){if(!t.targetId)return{statusCode:400,body:{error:"reason NOT_SEMANTICALLY_EQUIVALENT requires --target-id \u2014 the concept this description actually belongs under."}}}else if(t.targetId)return{statusCode:400,body:{error:`--target-id only applies to reason NOT_SEMANTICALLY_EQUIVALENT (paired with a REFERS_TO association) \u2014 omit it for ${t.reason}.`}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=`${R(e)}/${n.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${_r}&active=true`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:s.body}};let a=(s.body.items??[])[0];return a?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(a.effectiveTime)}) and cannot be changed.`}}:A(e,n,t.conceptId,c=>{let u=(Array.isArray(c.descriptions)?c.descriptions:[]).find(l=>l.descriptionId===t.descriptionId);return u?u.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(u.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?u.associationTargets={[de]:[t.targetId]}:delete u.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Yt(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let o=await h(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n),s=await H(e,o.projectKey,n),a=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return A(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[],u;if(t.descriptionId){if(u=d.find(l=>l.descriptionId===t.descriptionId),!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(u.type)}, not an FSN.`}}}else{let l=d.filter(f=>f.type==="FSN"&&f.active!==!1);if(l.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${l.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};u=l[0]}return u.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(u.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(u.active=!1,u.inactivationIndicator=t.indicator,u.acceptabilityMap={},t.associationTargetId&&(u.associationTargets={[de]:[t.associationTargetId]}),d.push(X("FSN",a,i,s,"PREFERRED",!1)),c.descriptions=d,null)})}async function Fe(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?s.effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(s.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(s.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Wt(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?s.effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} has effectiveTime ${String(s.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(s.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Ke(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await h(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n);return A(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[];return a.push({axiomId:Pe.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.classAxioms=a,null})}async function Qt(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};let o=await h(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n);return A(e,o,t.conceptId,s=>{let a=Array.isArray(s.gciAxioms)?s.gciAxioms:[];return a.push({axiomId:Pe.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.gciAxioms=a,null})}async function zt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:i.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(i.splice(s,1),o.classAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function Le(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);return s?s.active===!1?{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}}:s.effectiveTime==null?{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}}:i.filter(c=>c!==s&&c.active!==!1).length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:(s.active=!1,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}var Ur="116680003";function Et(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function Vr(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let i of r)i?.id&&t.push({active:!0,groupId:0,type:{conceptId:Ur},target:{conceptId:i.id}});let n=Array.isArray(e.attributes)?e.attributes:[];for(let i of n)t.push(Et(i,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((i,s)=>{let a=Array.isArray(i.attributes)?i.attributes:[];for(let c of a)t.push(Et(c,s+1))}),t}async function Xt(e,t,r,n){let o=R(e),i=await I(`${o}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(i.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{ok:!1,result:{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body,undetermined:!0}}};let s=Array.isArray(i.body.classAxioms)?i.body.classAxioms:[],a;if(n){if(a=s.find(c=>c.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`,undetermined:!0}}}}else{let c=s.filter(d=>d.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var qr="116680003";function Jr(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==qr?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function Gr(e,t,r){let n=R(e),o=await I(`${n}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(o.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(o.statusCode<200||o.statusCode>=300||!o.body)return{ok:!1,result:{statusCode:o.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:o.body,undetermined:!0}}};let i=Vr(o.body);return i.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`,undetermined:!0}}}:{ok:!0,value:i}}async function Hr(e,t,r,n){let o=await Xt(e,t,r,n);if(!o.ok)return o;let i=await Gr(e,t,r);return i.ok?{ok:!0,value:{axiom:o.value.axiom,axiomId:o.value.axiomId,targetRelationships:i.value}}:i}function Yr(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let n=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${n}`}function jt(e){let t=new Map;for(let o of e){if(o.active===!1)continue;let i=typeof o.groupId=="number"?o.groupId:0,s=t.get(i)??[];s.push(Yr(o)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),n=[];for(let[o,i]of t)o!==0&&n.push(i.slice().sort());return{ungrouped:r,groups:n}}function Wr(e,t){let r=jt(e),n=jt(t);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(s=>s.join("|")).sort(),i=n.groups.map(s=>s.join("|")).sort();return o.join("||")===i.join("||")}async function ue(e,t,r,n=new Map){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await h(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=await Hr(e,o,t.conceptId,t.axiomId);if(!i.ok)return i.result;let{axiom:s,axiomId:a,targetRelationships:c}=i.value,d=Array.isArray(s.relationships)?s.relationships:[];if(Wr(d,c))return e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${o.projectKey}/${o.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:a,alreadyConformed:!0}};if(!(s.effectiveTime!=null))return Fe(e,{conceptId:t.conceptId,axiomId:a,relationships:c,projectKey:o.projectKey,taskKey:o.taskKey},r);let l=await Ke(e,{conceptId:t.conceptId,relationships:c,moduleId:typeof s.moduleId=="string"?s.moduleId:void 0,definitionStatus:s.definitionStatus,projectKey:o.projectKey,taskKey:o.taskKey},r,n);if(l.statusCode<200||l.statusCode>=300)return l;let f=await Le(e,{conceptId:t.conceptId,axiomId:a,projectKey:o.projectKey,taskKey:o.taskKey},r);return f.statusCode<200||f.statusCode>=300?{statusCode:f.statusCode,body:{error:`Added the transformed axiom but failed to inactivate published axiom ${a}: ${JSON.stringify(f.body)}`,addResult:l.body}}:{statusCode:f.statusCode,body:{replacedAxiomId:a,addResult:l.body,inactivateResult:f.body}}}async function le(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Xt(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s}=o.value,a=Array.isArray(i.relationships)?i.relationships:[];return Jr(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function Zt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!t.relationshipId&&t.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=t.relationshipId?a.findIndex(u=>u.relationshipId===t.relationshipId):t.relationshipIndex,d=c>=0?a[c]:void 0;return d?d.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),s.relationships=a,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function eo(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.attributes)||t.attributes.length===0)return{statusCode:400,body:{error:"conceptId, axiomId, and a non-empty attributes array are required."}};for(let o of t.attributes)if(!o||typeof o.typeId!="string"||typeof o.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=bt(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let d=c.relationships.find(u=>u.effectiveTime!=null);return d?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(d.relationshipId)}) with effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(s.relationships=a.filter(u=>(typeof u.groupId=="number"?u.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function to(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(i.splice(s,1),o.gciAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function oo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await h(e,t,r);return n.ok?A(e,n,t.conceptId,o=>{let s=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?s.effectiveTime==null?{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}}:s.active===!1?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}}:(s.active=!1,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}var Qr=8;async function pe(e,t,r,n){let o=[],i=[],s=0,a=async()=>{for(;;){let d=s++;if(d>=r.length)return;let u=r[d];try{let l=await le(e,{conceptId:u.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),f=l.body;if(l.statusCode<200||l.statusCode>=300){i.push({...u,error:f?.error??`HTTP ${l.statusCode}`});continue}f?.conclusive&&o.push({...u,axiomId:f.axiomId})}catch(l){i.push({...u,error:l instanceof Error?l.message:String(l)})}}},c=Math.min(Qr,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:o,skipped:i}}async function no(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await ae(e,{...t,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let i=o.body?.items??[],s=i.map(d=>({conceptId:d.conceptId,fsn:d.fsn,pt:d.pt})),{matched:a,skipped:c}=await pe(e,n,s,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function ro(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=R(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};if(s.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{method:"DELETE",cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${n.projectKey}/${n.taskKey}: ${c.statusCode<300?"OK":"FAILED ("+c.statusCode+")"} \u2014 ${t.conceptId}`),c.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:c.body}}:{statusCode:c.statusCode,body:c.body})}function zr(e){let t=[];for(let r of e)t.some(o=>o.componentId===r.componentId&&o.severity===r.severity&&o.conceptId===r.conceptId&&o.message===r.message)||t.push(r);return t}async function me(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=R(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};let a=J(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await I(c,{method:"POST",body:De(s.body),cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let u=Array.isArray(d.body)?zr(d.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:u,hasErrors:u.some(l=>l.severity==="ERROR"),hasWarnings:u.some(l=>l.severity==="WARNING")}}}var io=200;async function Xr(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${R(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=io){let a=r.slice(s,s+io),c=await I(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let d of c.body)n.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:n,resolved:i}}async function K(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${yt(e)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,i=await I(o,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(i.statusCode<200||i.statusCode>=300)return{statusCode:i.statusCode,body:{error:"Could not fetch traceability for branch.",details:i.body}};let s=new Map,a=new Map,c=(k,C,S,$)=>{let j=k.get(C);j?($.forEach(P=>P&&j.componentSubTypes.add(P)),j.lastUpdatedTime=S):k.set(C,{conceptId:C,lastUpdatedTime:S,componentSubTypes:new Set($.filter(P=>!!P))})};for(let k of i.body?.content??[])if(!(k.activityType!=="CONTENT_CHANGE"&&k.activityType!=="CLASSIFICATION_SAVE"))for(let C of k.conceptChanges??[]){let S=String(C.conceptId),$=C.componentChanges??[],j=$.map(O=>O.componentSubType);if(k.activityType==="CLASSIFICATION_SAVE"){c(a,S,k.commitDate,j);continue}let P=$.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(P?s:a,S,k.commitDate,j)}for(let k of s.keys())a.delete(k);let d=[...new Set([...s.keys(),...a.keys()])],{terms:u,resolved:l}=await Xr(e,n.branchPath,d),f=k=>[...k.values()].sort((C,S)=>(S.lastUpdatedTime??"").localeCompare(C.lastUpdatedTime??"")).map(C=>{let S=l&&!u.has(C.conceptId);return{conceptId:C.conceptId,fsn:u.get(C.conceptId)?.fsn,pt:u.get(C.conceptId)?.pt,...S?{deleted:!0}:{},lastUpdatedTime:C.lastUpdatedTime,changedComponentTypes:[...C.componentSubTypes]}}),g=f(s),y=f(a);return{statusCode:200,body:{branchPath:n.branchPath,...l?{summary:{concepts:g.length,conceptsDeleted:g.filter(k=>k.deleted).length,conceptsClassified:y.length}}:{},concepts:g,conceptsClassified:y}}}async function so(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await K(e,t,r);if(o.statusCode<200||o.statusCode>=300){let u=o.body;return{statusCode:o.statusCode,body:{error:u.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=i.filter(u=>!u.deleted),a=s.map(u=>({conceptId:u.conceptId,fsn:u.fsn})),{matched:c,skipped:d}=await pe(e,n,a,r);return{statusCode:200,body:{branchPath:n.branchPath,totalReviewed:s.length,matched:c.length,skipped:d.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:d}}}async function Zr(e,t,r,n){let o=[];for(let i of r){if(i.deleted){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await me(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),a=s.body;if(s.statusCode<200||s.statusCode>=300){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return o}async function ao(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await K(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=await Zr(e,n,i,r),a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:s.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:s}}}async function L(e,t,r){let n=`${w(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body??null}var Be=new Set;function co(e){if(!(!e||typeof e!="object"))for(let t of Be)t(e)}function ei(e){return Be.add(e),()=>Be.delete(e)}function ti(e,t){return t.entityType!==void 0&&e.entityType!==t.entityType?!1:e.task?e.task===t.taskKey&&e.project===t.projectKey:e.project?e.project===t.projectKey:e.branchPath===t.branchPath}function fe(e){let t=()=>{};return{promise:new Promise(n=>{t=ei(o=>{ti(o,e)&&(t(),n(o))})}),cancel:t}}var Ve=["RUNNING","BUILDING","SCHEDULED","QUEUED"],qe=["QUEUED","SCHEDULED","RUNNING"],oi=["Promoted","Completed"],uo=5e3;function Ue(e){return new Promise(t=>setTimeout(t,e))}async function ni(e,t,r){let n=0;for(;;){let{done:o,value:i}=await e();if(o)return{value:i,timedOut:!1};if(n>=r)return{value:i,timedOut:!0};n++,await Ue(t)}}function ri(){let e=[9e4];for(let t=0;t<3;t++)e.push(1e4);for(let t=0;t<12;t++)e.push(5e3);return e}var ii=ri(),si=180;function ai(){let e=[3e5];for(let t=0;t<5;t++)e.push(6e4);for(let t=0;t<10;t++)e.push(3e4);return e}var ci=ai(),di=900;async function mo(e,t,r,n,o){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=n?fe(n):void 0,u=await Promise.race(d?[Ue(c).then(()=>{}),d.promise]:[Ue(c).then(()=>{})]);if(d?.cancel(),u){let g=u.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:l,value:f}=await e();if(l)return{value:f,timedOut:!1};if(Date.now()-s>=i)return{value:f,timedOut:!0};a++}}async function fo(e,t,r){let n=await L(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&oi.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${w(e)}/projects/${t}/tasks/${r}`;await I(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function Je(e,t,r){let n=`${w(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await I(n,{method:"POST",body:{},cookie:e.cookie}),(await L(e,t,r))?.latestClassificationJson}async function lo(e,t,r,n,o){let i,{value:s,timedOut:a}=await mo(async()=>{let d=(await Je(e,t,r))?.status;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||Ve.includes(d)),value:d}},ii,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function Me(e,t,r){let n=`${R(e)}/${t}/classifications`,o=await I(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(i=>i.id===r)??o.body.items[o.body.items.length-1]}async function go(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,s=await Je(e,o,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:Ve.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function ge(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await fo(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??si,d=await Je(e,o,i),u=d?.status,l=d?.id;if(l&&u&&Ve.includes(u)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${l} already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:P}=await lo(e,o,i,s,c),O=await Me(e,s,l),U={accepted:!1};return!P&&j==="COMPLETED"&&(U=await _e(e,s,o,i,l)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: attached job ${l} final status ${j??"unknown"}${P?" (timed out waiting)":""}, save ${JSON.stringify(U)}`),{statusCode:200,body:{jobId:l,finalStatus:j,timedOut:P,details:O,save:U,attachedToExisting:!0}}}if(l&&u==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${l} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await Me(e,s,l),P=await _e(e,s,o,i,l);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: accepted existing job ${l}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:l,finalStatus:"COMPLETED",timedOut:!1,details:j,save:P,acceptedExisting:!0}}}let f=`${w(e)}/projects/${o}/tasks/${i}/classifications`,g=await I(f,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: start failed (HTTP ${g.statusCode}) \u2014 raw body: ${g.rawBody}`),{statusCode:g.statusCode||500,body:{error:"Failed to start classification.",details:g.body??g.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: started (${g.body.status??"unknown"})`);let y=g.body.id;if(!t.wait)return{statusCode:200,body:{jobId:y,status:g.body.status}};let{finalStatus:k,timedOut:C}=await lo(e,o,i,s,c),S=await Me(e,s,y),$={accepted:!1};return!C&&k==="COMPLETED"&&($=await _e(e,s,o,i,y)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: final status ${k??"unknown"}${C?" (timed out waiting)":""}, save ${JSON.stringify($)}`),{statusCode:200,body:{jobId:y,finalStatus:k,timedOut:C,details:S,save:$}}}var ui=["SAVED","STALE","SAVE_FAILED"],li=120;async function _e(e,t,r,n,o){let i=`${R(e)}/${t}/classifications/${o}`,s=await I(i,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(s.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(s.statusCode<200||s.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${s.statusCode}).`};let a=Math.ceil(li*1e3/uo),{value:c,timedOut:d}=await ni(async()=>{let l=(await I(i,{cookie:e.cookie})).body?.status;return{done:!!l&&ui.includes(l),value:l}},uo,a);return d?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function yo(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,a=(await L(e,o,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&qe.includes(a)}}}async function po(e,t,r,n,o){let i,{value:s,timedOut:a}=await mo(async()=>{let d=(await L(e,t,r))?.latestValidationStatus;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||qe.includes(d)),value:d}},ci,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function ko(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await fo(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??di,u=(await L(e,o,i))?.latestValidationStatus;if(u&&qe.includes(u)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: validation already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:k,timedOut:C}=await po(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: attached run final status ${k??"unknown"}${C?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:k,timedOut:C,attachedToExisting:!0}}}let l=`${w(e)}/projects/${o}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(l+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let f=await I(l,{method:"POST",body:{},cookie:e.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(f.statusCode<200||f.statusCode>=300)return{statusCode:f.statusCode,body:{error:"Failed to start validation.",details:f.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:y}=await po(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: final status ${g??"unknown"}${y?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:y}}}var pi=8;function mi(e){return typeof e=="string"&&/timed out after \d+ms/.test(e)}async function ho(e,t,r,n,o,i){let s=0,a=0,c=async()=>{for(;;){let u=a++;if(u>=r.length)return;let l=r[u];try{let f=await ue(e,{conceptId:l.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),g=f.body;f.statusCode<200||f.statusCode>=300?g?.undetermined?n.set(l.conceptId,{outcome:"skipped",error:g.error??`HTTP ${f.statusCode}`}):n.set(l.conceptId,{outcome:"failed",error:g?.error??`HTTP ${f.statusCode}`}):n.set(l.conceptId,{outcome:g?.alreadyConformed?"conformed":"transformed"})}catch(f){n.set(l.conceptId,{outcome:"failed",error:f instanceof Error?f.message:String(f)})}s+=1,e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: ${i} \u2014 ${l.conceptId} (${s}/${r.length})`)}},d=Math.min(pi,r.length);await Promise.all(Array.from({length:d},()=>c()))}async function fi(e,t,r,n){let o=new Map;return await ho(e,t,r,o,n,"axiom checked"),await gi(e,t,r,o,n),o}async function gi(e,t,r,n,o){let i=r.filter(s=>{let a=n.get(s.conceptId);return a?.outcome==="failed"&&mi(a.error)});i.length!==0&&(e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: reprocessing ${i.length} concept(s) that timed out on the first pass`),await ho(e,t,i,n,o,"axiom rechecked"))}async function Co(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await ge(e,{projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath,wait:!0},r);if(o.statusCode===401)return o;let i=o.body,s=o.statusCode>=200&&o.statusCode<300?{jobId:i?.jobId,finalStatus:i?.finalStatus,timedOut:i?.timedOut,save:i?.save}:{error:i?.error??`HTTP ${o.statusCode}`},a=await K(e,t,r);if(a.statusCode<200||a.statusCode>=300){let y=a.body;return{statusCode:a.statusCode,body:{error:y.error??"Could not list concepts for review."}}}let c=a.body.concepts??[],d=c.filter(y=>!y.deleted).map(y=>({conceptId:y.conceptId,fsn:y.fsn})),u=await fi(e,n,d,r),l=[];for(let[y,k]of c.entries()){if(k.deleted){l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"deleted"});continue}let C=u.get(k.conceptId),S=await se(e,{conceptId:k.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),$=S.body,j=`(${y+1}/${c.length})`;if(S.statusCode<200||S.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: FAILED (${S.statusCode}) \u2014 ${k.conceptId} ${j}`),l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"failed",error:$?.error??`HTTP ${S.statusCode}`,axiom:C});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: OK \u2014 ${k.conceptId} ${j}`),l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"fetched",concept:S.body,axiom:C})}let f=y=>l.filter(k=>k.outcome===y).length,g=y=>Array.from(u.values()).filter(k=>k.outcome===y).length;return{statusCode:200,body:{branchPath:n.branchPath,classification:s,summary:{total:l.length,fetched:f("fetched"),skippedDeleted:f("deleted"),failed:f("failed"),axiomsTransformed:g("transformed"),axiomsConformed:g("conformed"),axiomsSkipped:g("skipped"),axiomsFailed:g("failed")},concepts:l}}}async function Io(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${w(e)}/projects${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function xo(e,t){let r=`${w(e)}/projects/${t}/tasks`;return(await I(r,{cookie:e.cookie})).body??[]}async function bo(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${w(e)}/projects/my-tasks${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function So(e,t){let r=`${w(e)}/projects/${t.projectKey}/tasks`,n={summary:t.summary};t.description!==void 0&&(n.description=t.description),t.assigneeUsername&&(n.assignee={username:t.assigneeUsername});let o=await I(r,{method:"POST",body:n,cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}var yi=["FORWARD","DIVERGED"];async function ki(e,t){if(!t)return!1;let r=`${R(e)}/branches/${encodeURIComponent(t)}`,n=await I(r,{cookie:e.cookie});return yi.includes(n.body?.state??"")}var hi=["Promoted","Completed"];async function vo(e,t){let r=`${w(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};let o=n.body.status;if(o&&hi.includes(o))return{statusCode:409,error:`${t.projectKey}/${t.taskKey} has status ${o} \u2014 its work is already in the project, so the task cannot be deleted.`};if(o==="Deleted")return{statusCode:200,task:n.body,alreadyDeleted:!0};let i=await ki(e,n.body.branchPath),s=await I(r,{method:"PUT",body:{status:"DELETED"},cookie:e.cookie});return s.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:s.statusCode<200||s.statusCode>=300||!s.body?{statusCode:s.statusCode||500,error:`Failed to delete ${t.projectKey}/${t.taskKey} (HTTP ${s.statusCode})${s.rawBody?`: ${s.rawBody}`:""}`}:{statusCode:s.statusCode,task:s.body,hadUnpromotedChanges:i}}async function To(e,t){let r=`${w(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await I(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var Ci="IN_PROGRESS";async function Ro(e,t){let r=`${w(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};if(n.body.status!=="Deleted")return{statusCode:200,task:n.body,notDeleted:!0};let o=await I(r,{method:"PUT",body:{status:Ci},cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}function Ao(e){if(e==="o")return{type:"open"};if(e==="h")return{type:"heartbeat"};if(e.startsWith("a"))try{return{type:"message",messages:JSON.parse(e.slice(1))}}catch{return{type:"unknown",raw:e}}if(e.startsWith("c"))try{let[t,r]=JSON.parse(e.slice(1));return{type:"close",code:t,reason:r}}catch{return{type:"unknown",raw:e}}return{type:"unknown",raw:e}}function Ge(e){return JSON.stringify([e])}function wo(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",n="";for(let o=0;o<8;o++)n+=r[Math.floor(e()*r.length)];return`${t}/${n}/websocket`}function He(e,t={},r=""){let n=Object.entries(t).map(([o,i])=>`${o}:${i}`);return[e,...n,"",r].join(`
3
+ `)+"\0"}function $o(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
4
4
 
5
- `),n=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r+2),s=n.split(`
6
- `),i=s[0],a={};for(let c of s.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:i,headers:a,body:o}}var Ao=T(require("ws"));var wo=[1e3,2e3,5e3,1e4,3e4];function $o(e,t={}){let r=t.createSocket??((u,l)=>new Ao.default(u,l)),n=!1,o,s=0,i,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let u=wo[Math.min(s,wo.length-1)];s+=1,i=setTimeout(d,u)};function d(){if(n)return;let l=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${To()}`,p=r(l,a?{headers:{cookie:a}}:{});o=p,p.on("message",g=>{let y=vo(g.toString());if(y.type==="open"){p.send(Je(Ge("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(y.type==="close"){p.close();return}if(y.type==="message")for(let k of y.messages){let h=Ro(k);if(h){if(h.command==="CONNECTED"){s=0;let S=`/topic/user/${e.login}/notifications`;p.send(Je(Ge("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:S})));continue}if(h.command==="MESSAGE"){try{e.onNotification(JSON.parse(h.body))}catch(S){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",S)}continue}h.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",h.headers,h.body)}}}),p.on("unexpected-response",(g,y)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${y.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),p.on("close",c)}return d(),{stop(){n=!0,i&&clearTimeout(i),o?.removeAllListeners(),o?.close()}}}function Eo(e,t,r={}){let n=r.startRelay??$o,o=r.onNotification??so,s=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>s.stop()}}var gs=60;async function jo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=t.timeoutSeconds??gs,c=me({entityType:t.entityType,projectKey:o,taskKey:s,branchPath:i}),d,u=new Promise(g=>{d=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),l=c.promise.then(g=>({kind:"notification",payload:g})),p=await Promise.race([l,u]);return c.cancel(),clearTimeout(d),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function x(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",n=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",o=t.componentId??t.conceptId??"?";console.log(`${n} ${r} [${o}] ${t.message??""}`)}}var Vo=T(require("http")),Jo=require("child_process");var ye=T(require("fs")),Po=T(require("os")),No=T(require("path"));function ys(){return No.join(Po.homedir(),"Library","Application Support","Google","Chrome","Local State")}function ks(){let e=ys();if(!ye.existsSync(e))return[];let t;try{t=JSON.parse(ye.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([n,o])=>({directoryName:n,displayName:typeof o?.name=="string"&&o.name?o.name:n}))}var ge=class extends Error{constructor(t,r){super(`Chrome profile "${t}" not found. Available profiles: ${r.length?r.map(n=>`"${n.displayName}"`).join(", "):"(none detected)"}`),this.name="ChromeProfileNotFoundError"}};function ke(e,t=ks()){if(!e){let n=t.find(o=>o.directoryName==="Default");if(n)return n;if(t.length)return t[0];throw new ge("Default",t)}let r=t.find(n=>n.directoryName===e||n.displayName.toLowerCase()===e.toLowerCase());if(!r)throw new ge(e,t);return r}var _o=require("child_process"),Uo=require("util"),We=T(require("fs")),Ie=T(require("os")),ze=T(require("path"));var Do=require("child_process"),Oo=require("util"),he=T(require("crypto")),_=T(require("fs")),hs=(0,Oo.promisify)(Do.exec);function He(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}async function Fo(){let{stdout:e}=await hs('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return e.trim()}function Ko(e){return he.pbkdf2Sync(e,"saltysalt",1003,16,"sha1")}function Lo(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let n=r.subarray(0,3).toString("utf8");if(n!=="v10"&&n!=="v11")return null;let o=Buffer.alloc(16,32),s=r.subarray(3),i;try{let d=he.createDecipheriv("aes-128-cbc",t,o);i=Buffer.concat([d.update(s),d.final()])}catch{return null}let a=i.length>32?i.subarray(32):null,c=i;return a&&He(a)&&!He(i)&&(c=a),He(c)?c.toString("utf8"):null}function Bo(e,t){_.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;_.existsSync(n)&&_.copyFileSync(n,t+r)}}function Mo(e){for(let t of[e,e+"-wal",e+"-shm"])try{_.unlinkSync(t)}catch{}}var Cs=(0,Uo.promisify)(_o.exec),Ce=class extends Error{},Ye=class extends Error{};function Is(e){return ze.join(Ie.homedir(),"Library","Application Support","Google","Chrome",e,"Cookies")}function xs(){return We.existsSync("/Applications/Google Chrome.app")}function bs(e){let t=e.split(".").filter(Boolean),r=[];for(let n=0;n+1<t.length;n++){let o=t.slice(n).join(".");r.push(o,`.${o}`)}return r}async function Qe(e,t,r){let n=Is(e);if(!We.existsSync(n))return null;let o=ze.join(Ie.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);Bo(n,o);try{let s;try{s=await Fo()}catch{return null}let i=Ko(s),a=l=>`'${l.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${bs(t).map(a).join(", ")}) AND name = ${a(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await Cs(`sqlite3 "${o}" "${d}"`);return Lo(u.trim(),i)}catch{return null}finally{Mo(o)}}function Ss(e){return new Promise(t=>setTimeout(t,e))}async function qo(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??xs;if(r!=="darwin")throw new Ce(`Automatic session capture is only supported on macOS with Google Chrome. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!n())throw new Ce("Automatic session capture requires Google Chrome (checked /Applications/Google Chrome.app), but it was not found. Install Chrome, or use the manual cookie-paste fallback instead.");let o=t.readCookie??Qe,s=t.sleep??Ss,i=e.pollIntervalMs??750,a=e.timeoutMs??15e3,c=await o(e.profileDirectory,e.host,e.cookieName),d=Date.now()+a;for(;Date.now()<d;){let u=await o(e.profileDirectory,e.host,e.cookieName);if(u&&u!==c)return u;await s(i)}throw new Ye(`Timed out after ${a}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host}. Complete login in the Chrome window that opened, or use the manual cookie-paste fallback.`)}function Xe(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}function vs(e,t){let r=n=>`'${n.replace(/'/g,"'\\''")}'`;(0,Jo.exec)(`open -a ${r("Google Chrome")} ${r(e)} --args --profile-directory=${r(t)}`)}function Ts(){return`<!DOCTYPE html>
5
+ `),n=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r+2),i=n.split(`
6
+ `),s=i[0],a={};for(let c of i.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:s,headers:a,body:o}}var jo=T(require("ws"));var Eo=[1e3,2e3,5e3,1e4,3e4];function Po(e,t={}){let r=t.createSocket??((u,l)=>new jo.default(u,l)),n=!1,o,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let u=Eo[Math.min(i,Eo.length-1)];i+=1,s=setTimeout(d,u)};function d(){if(n)return;let l=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${wo()}`,f=r(l,a?{headers:{cookie:a}}:{});o=f,f.on("message",g=>{let y=Ao(g.toString());if(y.type==="open"){f.send(Ge(He("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(y.type==="close"){f.close();return}if(y.type==="message")for(let k of y.messages){let C=$o(k);if(C){if(C.command==="CONNECTED"){i=0;let S=`/topic/user/${e.login}/notifications`;f.send(Ge(He("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:S})));continue}if(C.command==="MESSAGE"){try{e.onNotification(JSON.parse(C.body))}catch(S){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",S)}continue}C.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",C.headers,C.body)}}}),f.on("unexpected-response",(g,y)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${y.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),f.terminate()}),f.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),f.on("close",c)}return d(),{stop(){n=!0,s&&clearTimeout(s),o?.removeAllListeners(),o?.close()}}}function No(e,t,r={}){let n=r.startRelay??Po,o=r.onNotification??co,i=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>i.stop()}}var Ii=60;async function Do(e,t,r){let n=await h(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=t.timeoutSeconds??Ii,c=fe({entityType:t.entityType,projectKey:o,taskKey:i,branchPath:s}),d,u=new Promise(g=>{d=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),l=c.promise.then(g=>({kind:"notification",payload:g})),f=await Promise.race([l,u]);return c.cancel(),clearTimeout(d),f.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:f.payload}}}function x(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",n=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",o=t.componentId??t.conceptId??"?";console.log(`${n} ${r} [${o}] ${t.message??""}`)}}var Ho=T(require("http")),Yo=require("child_process");var ke=T(require("fs")),Oo=T(require("os")),Fo=T(require("path"));function xi(){return Fo.join(Oo.homedir(),"Library","Application Support","Google","Chrome","Local State")}function bi(){let e=xi();if(!ke.existsSync(e))return[];let t;try{t=JSON.parse(ke.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([n,o])=>({directoryName:n,displayName:typeof o?.name=="string"&&o.name?o.name:n}))}var ye=class extends Error{constructor(t,r){super(`Chrome profile "${t}" not found. Available profiles: ${r.length?r.map(n=>`"${n.displayName}"`).join(", "):"(none detected)"}`),this.name="ChromeProfileNotFoundError"}};function he(e,t=bi()){if(!e){let n=t.find(o=>o.directoryName==="Default");if(n)return n;if(t.length)return t[0];throw new ye("Default",t)}let r=t.find(n=>n.directoryName===e||n.displayName.toLowerCase()===e.toLowerCase());if(!r)throw new ye(e,t);return r}var qo=require("child_process"),Jo=require("util"),Qe=T(require("fs")),xe=T(require("os")),ze=T(require("path"));var Ko=require("child_process"),Lo=require("util"),Ce=T(require("crypto")),_=T(require("fs")),Si=(0,Lo.promisify)(Ko.exec);function Ye(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}async function Bo(){let{stdout:e}=await Si('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return e.trim()}function Mo(e){return Ce.pbkdf2Sync(e,"saltysalt",1003,16,"sha1")}function _o(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let n=r.subarray(0,3).toString("utf8");if(n!=="v10"&&n!=="v11")return null;let o=Buffer.alloc(16,32),i=r.subarray(3),s;try{let d=Ce.createDecipheriv("aes-128-cbc",t,o);s=Buffer.concat([d.update(i),d.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&Ye(a)&&!Ye(s)&&(c=a),Ye(c)?c.toString("utf8"):null}function Uo(e,t){_.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;_.existsSync(n)&&_.copyFileSync(n,t+r)}}function Vo(e){for(let t of[e,e+"-wal",e+"-shm"])try{_.unlinkSync(t)}catch{}}var vi=(0,Jo.promisify)(qo.exec),Ie=class extends Error{},We=class extends Error{};function Ti(e){return ze.join(xe.homedir(),"Library","Application Support","Google","Chrome",e,"Cookies")}function Ri(){return Qe.existsSync("/Applications/Google Chrome.app")}function Ai(e){let t=e.split(".").filter(Boolean),r=[];for(let n=0;n+1<t.length;n++){let o=t.slice(n).join(".");r.push(o,`.${o}`)}return r}async function Xe(e,t,r){let n=Ti(e);if(!Qe.existsSync(n))return null;let o=ze.join(xe.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);Uo(n,o);try{let i;try{i=await Bo()}catch{return null}let s=Mo(i),a=l=>`'${l.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Ai(t).map(a).join(", ")}) AND name = ${a(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await vi(`sqlite3 "${o}" "${d}"`);return _o(u.trim(),s)}catch{return null}finally{Vo(o)}}function wi(e){return new Promise(t=>setTimeout(t,e))}async function Go(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??Ri;if(r!=="darwin")throw new Ie(`Automatic session capture is only supported on macOS with Google Chrome. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!n())throw new Ie("Automatic session capture requires Google Chrome (checked /Applications/Google Chrome.app), but it was not found. Install Chrome, or use the manual cookie-paste fallback instead.");let o=t.readCookie??Xe,i=t.sleep??wi,s=e.pollIntervalMs??750,a=e.timeoutMs??15e3,c=await o(e.profileDirectory,e.host,e.cookieName),d=Date.now()+a;for(;Date.now()<d;){let u=await o(e.profileDirectory,e.host,e.cookieName);if(u&&u!==c)return u;await i(s)}throw new We(`Timed out after ${a}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host}. Complete login in the Chrome window that opened, or use the manual cookie-paste fallback.`)}function Ze(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}function $i(e,t){let r=n=>`'${n.replace(/'/g,"'\\''")}'`;(0,Yo.exec)(`open -a ${r("Google Chrome")} ${r(e)} --args --profile-directory=${r(t)}`)}function Ei(){return`<!DOCTYPE html>
7
7
  <html>
8
8
  <head>
9
9
  <meta charset="utf-8">
@@ -14,20 +14,20 @@
14
14
  <h3>You're signed in.</h3>
15
15
  <p>Return to your terminal \u2014 the CLI is finishing sign-in automatically. You can close this tab.</p>
16
16
  </body>
17
- </html>`}function Go(e,t={}){let r=e.cookieName??Xe(e.host),n=t.openChrome??vs,o=t.resolveProfile??ke,s=t.captureCookie??qo,i=e.callbackTimeoutMs??12e4,a=o(e.chromeProfile);return new Promise((c,d)=>{let u=!1,l=g=>{u||(u=!0,p.close(),g())},p=Vo.createServer((g,y)=>{if((g.url||"/").split("?")[0]==="/callback"){y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(Ts()),(async()=>{try{let h=await s({profileDirectory:a.directoryName,host:e.host,cookieName:r});l(()=>c({cookie:`${r}=${h}`}))}catch(h){l(()=>d(h))}})();return}y.writeHead(404),y.end()});p.listen(0,"127.0.0.1",()=>{let y=`http://localhost:${p.address().port}/callback`,k=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(y)}`;n(k,a.directoryName)}),p.on("error",g=>l(()=>d(g))),setTimeout(()=>l(()=>c(null)),i)})}var N=T(require("fs")),Ho=T(require("os")),Ze=T(require("path"));function Yo(){return Ze.join(Ho.homedir(),".authoring-cli")}function et(){return Ze.join(Yo(),"session.json")}function tt(){let e=et();if(!N.existsSync(e))return null;let t=N.readFileSync(e,"utf8");return JSON.parse(t)}function xe(e){N.mkdirSync(Yo(),{recursive:!0,mode:448});let t={...e,updatedAt:new Date().toISOString()};N.writeFileSync(et(),JSON.stringify(t,null,2),{mode:384})}function Wo(){let e=et();N.existsSync(e)&&N.unlinkSync(e)}function B(e){let t=tt();if(!t)throw new Error('Not signed in \u2014 run "login" first.');xe({...t,currentTask:e})}async function Rs(e,t,r,n){let o;try{o=ke(n).directoryName}catch{return null}let s=await Qe(o,t,r).catch(()=>null);if(!s)return null;let i=`${r}=${s}`,a=await Ae(e,i).catch(()=>null);return a?{cookie:i,account:a}:null}function zo(e){let t=e?.displayName??e?.login;return t?`Signed in as ${t}.`:"Signed in. (Could not confirm account details \u2014 proceed with caution.)"}function Qo(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:s}of e)console.log(` ${(n+":").padEnd(t+2)}${r} (${o?"from flag":s})`)}async function Xo(e){let t=e.environment?ut(e.environment):Q;if(!t){console.error(`Unknown environment: ${e.environment}
18
- Expected one of: ${re.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=q[t],n=e.imsEndpoint||r.imsEndpoint,o=e.terminologyServerEndpoint||r.terminologyServerEndpoint,s=e.authoringServicesEndpoint||r.authoringServicesEndpoint,i;try{i=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||Xe(i),d=t===Q&&!e.environment?`${t}, default`:t,u=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:s,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(y=>({...y,source:d})),l=await Rs(n,i,c,e.chromeProfile);if(l){xe({cookie:l.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:l.account,currentTask:null}),console.log(`${zo(l.account)} (reused an existing Chrome session \u2014 no browser opened.)`),Qo(u);return}console.log(`Opening Chrome to sign in to ${n} ...`);let p=await Go({imsEndpoint:n,host:i,cookieName:c,chromeProfile:e.chromeProfile});if(!p){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let g=await Ae(n,p.cookie).catch(()=>null);xe({cookie:p.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:g,currentTask:null}),console.log(zo(g)),Qo(u)}async function Zo(){Wo(),console.log("Signed out.")}var Se=T(require("fs")),be=T(require("path"));async function en(){let e=[be.join(__dirname,"../../HELP.md"),be.join(__dirname,"../HELP.md"),be.join(process.cwd(),"HELP.md")];for(let t of e)try{if(Se.existsSync(t)){let r=Se.readFileSync(t,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function m(){let e=tt();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function f(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function tn(e){return e.projectKey??e.key??"?"}async function on(e){let t=m(),r=f(t),n=await ko(r);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(s=>tn(s).length))+1;for(let s of n){let i=s.title??"";console.log(`${tn(s).padEnd(o)}${i?`"${i}"`:""}`)}}function ve(e){return e.taskKey??e.key??"?"}function nn(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function ws(e){return e.projectKey||ve(e).split("-")[0]||"?"}function ot(e,t){let r=new Map;for(let n of e){let o=t(n);r.set(o,(r.get(o)??0)+1)}return[...r].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0]))}function nt(e,t){let r=Math.max(...t.map(([o])=>o.length)),n=Math.max(...t.map(([,o])=>String(o).length));console.log(""),console.log(`${e}:`);for(let[o,s]of t)console.log(` ${o.padEnd(r)} ${String(s).padStart(n)}`)}async function rn(e){let t=m(),r=f(t),n=e.mine||!e.project,o=n?await Co(r):await ho(r,e.project);if(n&&e.project){let u=e.project.toLowerCase();o=o.filter(l=>(l.projectKey??"").toLowerCase()===u||ve(l).toLowerCase().startsWith(`${u}-`))}if(e.status){let u=e.status.trim().toLowerCase();o=o.filter(l=>(l.status??"").toLowerCase()===u)}let s=ot(o,ws),i=ot(o,nn),a=ot(o,u=>u.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(s),byAssignee:Object.fromEntries(i),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),s.length>1&&nt("By project",s),!n&&i.length>1&&nt("By assignee",i),a.length>1&&nt("By status",a);return}let d=Math.max(...o.map(u=>ve(u).length))+1;for(let u of o){let l=u.summary??u.title??"",p=u.status?` status=${u.status}`:"",g=n?"":` [${nn(u)}]`;console.log(`${ve(u).padEnd(d)}${l?`"${l}"`:""}${p}${g}`)}}async function sn(e){let t=m(),r=f(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,s=await Io(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!s.task){console.error(s.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let i=s.task,a=i.key??i.taskKey,c=i.branchPath;if(e.json)console.log(JSON.stringify(i,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${i.summary??e.summary}"${i.status?` status=${i.status}`:""}`),c&&console.log(` branch: ${c}`);let d=i.assignee?.displayName??i.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await G(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.created&&!e.json&&console.log(` created branch ${c}`)}if(!e.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}B({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function an(e){let t=m(),r=f(t),n=t.currentTask;if(!!e.project!=!!e.task){console.error("Pass --project and --task together, or neither to delete the currently selected task."),process.exitCode=1;return}let o=e.project||n?.projectKey,s=e.task||n?.taskKey;if(!o||!s){console.error('No task to delete: pass --project/--task, or select one with "select-task".'),process.exitCode=1;return}let i=await xo(r,{projectKey:o,taskKey:s});if(i.error){console.error(i.error),process.exitCode=1;return}i.alreadyDeleted?console.log(`${o}/${s} is already deleted.`):console.log(`\u2713 Deleted task ${o}/${s}`),i.hadUnpromotedChanges&&console.log(` note: its branch had changes that were never promoted. They still exist on ${i.task?.branchPath??"the task branch"}, but a deleted task appears in no listing \u2014 move it out of Deleted to reach them again.`),n&&n.projectKey===o&&n.taskKey===s&&(B(null),console.log(" cleared the current task selection."))}async function cn(e){let t=m(),r=f(t);if(!e.task){let s=await bo(r,e.project);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${s.length} deleted task${s.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let i of s){let a=i.assignee?.displayName??i.assignee?.username??"unassigned";console.log(` ${i.key} "${i.summary??""}" [${a}]`)}return}let n=await So(r,{projectKey:e.project,taskKey:e.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let s=await G(r,o);if(!s.ok){console.error(`Task recovered, but its branch could not be prepared: ${s.error}`),process.exitCode=1;return}console.log(s.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(B({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function dn(e){let t=m(),r=f(t),n=await L(r,e.project,e.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let o=await G(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}B({projectKey:e.project,taskKey:e.task,branchPath:n.branchPath}),console.log(`\u2713 Current task set to ${e.project}/${e.task} (${n.branchPath})`),o.created&&console.log(` created branch ${n.branchPath}`)}async function un(e){let t=m();if(!t.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=t.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function ln(e){let t=m(),r=f(t),n=await ht(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300&&o.conceptId){console.log(`Created concept ${o.conceptId}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function pn(e){let t=m(),r=f(t),n={term:e.term,ecl:e.ecl,active:e.active!==void 0?e.active==="true":void 0,limit:e.limit?Number(e.limit):void 0,projectKey:e.project,taskKey:e.task},o=e.checkStatedParentsDefinitionStatus?await eo(r,n,t.currentTask):await ae(r,n,t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to search concepts (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function mn(e){let t=m(),r=f(t),n=await ie(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to get concept (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function fn(e){let t=m(),r=f(t),n=await Ct(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to find references (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function gn(e){let t=m(),r=f(t),n=await pe(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}let s=o.validationResults;if(!Array.isArray(s)||s.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(s),o.hasErrors&&(process.exitCode=1)}async function yn(e){let t=m(),r=f(t),n=e.checkStatedParentsDefinitionStatus?await no(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await K(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function kn(e){let t=m(),r=f(t),n=await ro(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let s=o.results??[],i=o.summary;if(s.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of s){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),x(a.validationResults)}if(i){console.log("");let a=[`${i.validated} validated`,`${i.clean} clean`,`${i.withIssues} with issues`];i.skippedDeleted&&a.push(`${i.skippedDeleted} skipped (deleted on this branch)`),i.failed&&a.push(`${i.failed} failed`),console.log(a.join(", ")+".")}i&&(i.withIssues>0||i.failed>0)&&(process.exitCode=1)}async function hn(e){let t=m(),r=f(t),n=await yo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Cn(e){let t=m(),r=f(t),n=await Pt(r,{conceptId:e.id,term:e.term,type:e.type,semanticTag:e.tag,moduleId:e.module,acceptability:e.acceptability,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function In(e){let t=m(),r=f(t),n=await Nt(r,{conceptId:e.id,typeId:e.type,targetId:e.target,groupId:e.group?Number(e.group):void 0,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function xn(e){let t=m(),r=f(t),n=await zt(r,{conceptId:e.id,axiomId:e.axiomId,relationshipId:e.relationshipId,relationshipIndex:e.relationshipIndex?Number(e.relationshipIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function bn(e){let t;try{t=JSON.parse(e.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await Qt(n,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Sn(e){let t=m(),r=f(t),n=await Ft(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function vn(e){let t=m(),r=f(t),n=await Kt(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Tn(e){let t=m(),r=f(t);if(e.entries){let i;try{i=JSON.parse(e.entries)}catch(u){console.error(`--entries is not valid JSON: ${u.message}`),process.exitCode=1;return}if(!Array.isArray(i)||i.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await _t(r,{conceptId:e.id,entries:i,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${i.length} description(s) on concept ${e.id}`),x(c.validationResults);return}let d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),process.exitCode=1;return}if(!e.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await Mt(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let i=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${i.join(", ")})`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Rn(e){let t=m(),r=f(t),n=await Ot(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function wn(e){let t=m(),r=f(t),n=await Dt(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function An(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await Oe(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function $n(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await Gt(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function En(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=m(),n=f(r),o=await Ht(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.gciAxioms)?s.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function jn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=m(),n=f(r),o=await Fe(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.classAxioms)?s.classAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Pn(e){let t=m(),r=f(t),n=await to(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Nn(e){let t=m(),r=f(t),n=await Ut(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Dn(e){let t=m(),r=f(t),n=await qt(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function On(e){let t=m(),r=f(t),n=await Vt(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to restore description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Fn(e){let t=m(),r=f(t),n=await Jt(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to replace FSN (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Kn(e){let t=m(),r=f(t),n=await Yt(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Ln(e){let t=m(),r=f(t),n=await Ke(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Bn(e){let t=m(),r=f(t),n=await de(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){if(o.alreadyConformed)console.log(`Concept ${e.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let i=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=i.length>0?i[i.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Mn(e){let t=m(),r=f(t),n=await ue(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}if(o.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${o.axiomId}) \u2014 ${o.message}`)}async function _n(e){let t=m(),r=f(t),n=await Xt(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Un(e){let t=m(),r=f(t),n=await Zt(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}function Y(e){let t=e.account?.login;return t?Eo(f(e),t):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function qn(e){let t=m(),r=f(t),n=Y(t),o;try{o=await fe(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?(console.log(`Classification ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),s.details&&console.log(JSON.stringify(s.details,null,2)),s.save&&(s.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${s.save.error?`: ${s.save.error}`:""}${s.save.status?` (status: ${s.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${s.jobId} (${s.status})`),s.timedOut&&(process.exitCode=1);return}let i=s.details!==void 0?` \u2014 details: ${JSON.stringify(s.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}${i}`),process.exitCode=1}async function Vn(e){let t=m(),r=f(t),n=await po(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Jn(e){let t=m(),r=f(t),n=Y(t),o;try{o=await fo(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?console.log(`Validation ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),s.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}`),process.exitCode=1}async function Gn(e){let t=m(),r=f(t),n=await mo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Hn(e){let t=m(),r=f(t),n=Y(t);try{let o=await jo(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),s=o.body;if(o.statusCode<200||o.statusCode>=300){let i=s.error?s.error:JSON.stringify(s);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),s.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var it=T(require("os")),W=T(require("path"));var v=T(require("fs")),rt=T(require("os")),b=T(require("path")),E="authoring-cli",D=["claude","codex"];function Te(e){let t=[b.resolve(e,"..","skills",E),b.resolve(e,"..","..","skills",E)];for(let r of t)if(v.existsSync(b.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${E}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function As(e){let t=[];return v.existsSync(b.join(e,".claude"))&&t.push("claude"),v.existsSync(b.join(e,".codex"))&&t.push("codex"),t}function te(e,t){if(e==="all")return[...D];if(e){let n=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),o=n.filter(s=>!D.includes(s));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=As(t);return r.length?r:["claude"]}var Wn="# authoring-cli \u2014 SNOMED CT authoring guidance";function $s(e){let t=b.join(e,"SKILL.md"),r=b.join(e,"references","batch-authoring.md");return[Wn,"",`Read \`${t}\` now, and follow it for the rest of this session whenever you run the`,"`authoring-cli` command \u2014 before any concept creation, description/acceptability edit,","relationship or axiom edit, `classify`, or `validate-task`. It documents server-side","constraints and async behavior that fail or mislead in non-obvious ways, so reading it after","a command has already failed is too late.","",`Also read \`${r}\` when the task is a large, multi-session batch (tens to thousands of`,"concepts generated from a source list).","","Both files live inside the installed `authoring-cli` npm package, so they stay in step with","the CLI itself. If the paths above no longer exist, the package moved or was upgraded to a","different location \u2014 re-run `authoring-cli install-skill` to refresh this prompt.",""].join(`
19
- `)}function Re(e){try{return b.resolve(b.dirname(e),v.readlinkSync(e))}catch{return null}}function oe(e){try{return v.lstatSync(e)}catch{return null}}function st(e){let t=Re(e);return t?v.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:oe(e)?.isDirectory()?"an existing directory":"an existing file"}function zn(e){let t=Re(e);return t!==null&&b.basename(t)===E&&b.basename(b.dirname(t))==="skills"}function Qn(e){if(!oe(e)?.isFile())return!1;try{return v.readFileSync(e,"utf8").startsWith(Wn)}catch{return!1}}function Yn(e){return v.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>b.relative(e,b.join(t.parentPath,t.name))).sort()}function Xn(e,t){if(!t||!v.existsSync(t))return!1;try{let r=Yn(t);return r.join(`
20
- `)!==Yn(e).join(`
21
- `)?!1:r.every(n=>v.readFileSync(b.join(e,n)).equals(v.readFileSync(b.join(t,n))))}catch{return!1}}function Es(e,t,r){let n=e.project?b.join(r,".claude","skills"):b.join(t,".claude","skills"),o=b.join(n,E),s=e.shippedSkillDir,i=e.project&&s.startsWith(r+b.sep)?b.relative(b.dirname(o),s):s,a=oe(o),c=!1;if(a){let d=Re(o);if(d===s&&v.existsSync(d))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:s};if(!(zn(o)||Xn(o,s))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:st(o)};v.rmSync(o,{recursive:!0,force:!0}),c=!0}v.mkdirSync(n,{recursive:!0});try{return v.symlinkSync(i,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:i}}catch(d){let u=d.code;if(u!=="EPERM"&&u!=="EACCES")throw d;return v.cpSync(s,o,{recursive:!0}),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function js(e,t){let r=b.join(t,".codex","prompts"),n=b.join(r,`${E}.md`),o=$s(e.shippedSkillDir),s=oe(n),i=!1;if(s){if((s.isFile()?v.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!Qn(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:st(n)};v.rmSync(n,{recursive:!0,force:!0}),i=!0}return v.mkdirSync(r,{recursive:!0}),v.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:i?"replaced":"installed",kind:"pointer"}}function Zn(e){let t=e.homeDir??rt.homedir(),r=e.cwd??process.cwd();return(e.agents??te(void 0,t)).map(o=>o==="claude"?Es(e,t,r):js(e,t))}function er(e){let t=e.homeDir??rt.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?b.join(e.project?b.join(r,".claude"):b.join(t,".claude"),"skills",E):b.join(t,".codex","prompts",`${E}.md`);if(!oe(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?zn(o)||Xn(o,e.shippedSkillDir):Qn(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${st(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let i=Re(o)??void 0;return v.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:i}})}function tr(e){let t=it.homedir();return e===t||e.startsWith(t+W.sep)?W.join("~",W.relative(t,e)):e}function Ps(e){let t=tr(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${tr(e.detail??"")})`:e.kind==="copy"?`${t} (copy \u2014 ${e.detail})`:`${t} (pointer into the installed package)`;case"already-current":return`${t} (already registered \u2014 nothing to do)`;case"blocked":return`${t} NOT written \u2014 ${e.detail} is in the way; re-run with --force to replace it`}}async function or(e){let t=Te(__dirname),r=te(e.agent,it.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=Zn({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),s=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${E}' for:`:s.length?`Could not install skill '${E}':`:`Skill '${E}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${Ps(a)}`);if(e.project&&r.includes("claude")&&console.log(`
17
+ </html>`}function Wo(e,t={}){let r=e.cookieName??Ze(e.host),n=t.openChrome??$i,o=t.resolveProfile??he,i=t.captureCookie??Go,s=e.callbackTimeoutMs??12e4,a=o(e.chromeProfile);return new Promise((c,d)=>{let u=!1,l=g=>{u||(u=!0,f.close(),g())},f=Ho.createServer((g,y)=>{if((g.url||"/").split("?")[0]==="/callback"){y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(Ei()),(async()=>{try{let C=await i({profileDirectory:a.directoryName,host:e.host,cookieName:r});l(()=>c({cookie:`${r}=${C}`}))}catch(C){l(()=>d(C))}})();return}y.writeHead(404),y.end()});f.listen(0,"127.0.0.1",()=>{let y=`http://localhost:${f.address().port}/callback`,k=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(y)}`;n(k,a.directoryName)}),f.on("error",g=>l(()=>d(g))),setTimeout(()=>l(()=>c(null)),s)})}var N=T(require("fs")),Qo=T(require("os")),et=T(require("path"));function zo(){return et.join(Qo.homedir(),".authoring-cli")}function tt(){return et.join(zo(),"session.json")}function ot(){let e=tt();if(!N.existsSync(e))return null;let t=N.readFileSync(e,"utf8");return JSON.parse(t)}function be(e){N.mkdirSync(zo(),{recursive:!0,mode:448});let t={...e,updatedAt:new Date().toISOString()};N.writeFileSync(tt(),JSON.stringify(t,null,2),{mode:384})}function Xo(){let e=tt();N.existsSync(e)&&N.unlinkSync(e)}function B(e){let t=ot();if(!t)throw new Error('Not signed in \u2014 run "login" first.');be({...t,currentTask:e})}async function ji(e,t,r,n){let o;try{o=he(n).directoryName}catch{return null}let i=await Xe(o,t,r).catch(()=>null);if(!i)return null;let s=`${r}=${i}`,a=await $e(e,s).catch(()=>null);return a?{cookie:s,account:a}:null}function Zo(e){let t=e?.displayName??e?.login;return t?`Signed in as ${t}.`:"Signed in. (Could not confirm account details \u2014 proceed with caution.)"}function en(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:i}of e)console.log(` ${(n+":").padEnd(t+2)}${r} (${o?"from flag":i})`)}async function tn(e){let t=e.environment?lt(e.environment):z;if(!t){console.error(`Unknown environment: ${e.environment}
18
+ Expected one of: ${re.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=V[t],n=e.imsEndpoint||r.imsEndpoint,o=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||Ze(s),d=t===z&&!e.environment?`${t}, default`:t,u=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(y=>({...y,source:d})),l=await ji(n,s,c,e.chromeProfile);if(l){be({cookie:l.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:l.account,currentTask:null}),console.log(`${Zo(l.account)} (reused an existing Chrome session \u2014 no browser opened.)`),en(u);return}console.log(`Opening Chrome to sign in to ${n} ...`);let f=await Wo({imsEndpoint:n,host:s,cookieName:c,chromeProfile:e.chromeProfile});if(!f){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let g=await $e(n,f.cookie).catch(()=>null);be({cookie:f.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:g,currentTask:null}),console.log(Zo(g)),en(u)}async function on(){Xo(),console.log("Signed out.")}var ve=T(require("fs")),Se=T(require("path"));async function nn(){let e=[Se.join(__dirname,"../../HELP.md"),Se.join(__dirname,"../HELP.md"),Se.join(process.cwd(),"HELP.md")];for(let t of e)try{if(ve.existsSync(t)){let r=ve.readFileSync(t,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function p(){let e=ot();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function m(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function rn(e){return e.projectKey??e.key??"?"}async function sn(e){let t=p(),r=m(t),n=await Io(r);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(i=>rn(i).length))+1;for(let i of n){let s=i.title??"";console.log(`${rn(i).padEnd(o)}${s?`"${s}"`:""}`)}}function Te(e){return e.taskKey??e.key??"?"}function an(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Pi(e){return e.projectKey||Te(e).split("-")[0]||"?"}function nt(e,t){let r=new Map;for(let n of e){let o=t(n);r.set(o,(r.get(o)??0)+1)}return[...r].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0]))}function rt(e,t){let r=Math.max(...t.map(([o])=>o.length)),n=Math.max(...t.map(([,o])=>String(o).length));console.log(""),console.log(`${e}:`);for(let[o,i]of t)console.log(` ${o.padEnd(r)} ${String(i).padStart(n)}`)}async function cn(e){let t=p(),r=m(t),n=e.mine||!e.project,o=n?await bo(r):await xo(r,e.project);if(n&&e.project){let u=e.project.toLowerCase();o=o.filter(l=>(l.projectKey??"").toLowerCase()===u||Te(l).toLowerCase().startsWith(`${u}-`))}if(e.status){let u=e.status.trim().toLowerCase();o=o.filter(l=>(l.status??"").toLowerCase()===u)}let i=nt(o,Pi),s=nt(o,an),a=nt(o,u=>u.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),i.length>1&&rt("By project",i),!n&&s.length>1&&rt("By assignee",s),a.length>1&&rt("By status",a);return}let d=Math.max(...o.map(u=>Te(u).length))+1;for(let u of o){let l=u.summary??u.title??"",f=u.status?` status=${u.status}`:"",g=n?"":` [${an(u)}]`;console.log(`${Te(u).padEnd(d)}${l?`"${l}"`:""}${f}${g}`)}}async function dn(e){let t=p(),r=m(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,i=await So(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!i.task){console.error(i.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let s=i.task,a=s.key??s.taskKey,c=s.branchPath;if(e.json)console.log(JSON.stringify(s,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${s.summary??e.summary}"${s.status?` status=${s.status}`:""}`),c&&console.log(` branch: ${c}`);let d=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await G(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.created&&!e.json&&console.log(` created branch ${c}`)}if(!e.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}B({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function un(e){let t=p(),r=m(t),n=t.currentTask;if(!!e.project!=!!e.task){console.error("Pass --project and --task together, or neither to delete the currently selected task."),process.exitCode=1;return}let o=e.project||n?.projectKey,i=e.task||n?.taskKey;if(!o||!i){console.error('No task to delete: pass --project/--task, or select one with "select-task".'),process.exitCode=1;return}let s=await vo(r,{projectKey:o,taskKey:i});if(s.error){console.error(s.error),process.exitCode=1;return}s.alreadyDeleted?console.log(`${o}/${i} is already deleted.`):console.log(`\u2713 Deleted task ${o}/${i}`),s.hadUnpromotedChanges&&console.log(` note: its branch had changes that were never promoted. They still exist on ${s.task?.branchPath??"the task branch"}, but a deleted task appears in no listing \u2014 move it out of Deleted to reach them again.`),n&&n.projectKey===o&&n.taskKey===i&&(B(null),console.log(" cleared the current task selection."))}async function ln(e){let t=p(),r=m(t);if(!e.task){let i=await To(r,e.project);if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${i.length} deleted task${i.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let s of i){let a=s.assignee?.displayName??s.assignee?.username??"unassigned";console.log(` ${s.key} "${s.summary??""}" [${a}]`)}return}let n=await Ro(r,{projectKey:e.project,taskKey:e.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let i=await G(r,o);if(!i.ok){console.error(`Task recovered, but its branch could not be prepared: ${i.error}`),process.exitCode=1;return}console.log(i.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(B({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function pn(e){let t=p(),r=m(t),n=await L(r,e.project,e.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let o=await G(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}B({projectKey:e.project,taskKey:e.task,branchPath:n.branchPath}),console.log(`\u2713 Current task set to ${e.project}/${e.task} (${n.branchPath})`),o.created&&console.log(` created branch ${n.branchPath}`)}async function mn(e){let t=p();if(!t.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=t.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function fn(e){let t=p(),r=m(t),n=await Ct(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300&&o.conceptId){console.log(`Created concept ${o.conceptId}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function gn(e){let t=p(),r=m(t),n={term:e.term,ecl:e.ecl,active:e.active!==void 0?e.active==="true":void 0,limit:e.limit?Number(e.limit):void 0,projectKey:e.project,taskKey:e.task},o=e.checkStatedParentsDefinitionStatus?await no(r,n,t.currentTask):await ae(r,n,t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to search concepts (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function yn(e){let t=p(),r=m(t),n=await se(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to get concept (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function kn(e){let t=p(),r=m(t),n=await It(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to find references (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function hn(e){let t=p(),r=m(t),n=await me(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}let i=o.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(i),o.hasErrors&&(process.exitCode=1)}async function Cn(e){let t=p(),r=m(t),n=e.checkStatedParentsDefinitionStatus?await so(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await K(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function In(e){let t=p(),r=m(t),n=await ao(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let i=o.results??[],s=o.summary;if(i.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of i){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),x(a.validationResults)}if(s){console.log("");let a=[`${s.validated} validated`,`${s.clean} clean`,`${s.withIssues} with issues`];s.skippedDeleted&&a.push(`${s.skippedDeleted} skipped (deleted on this branch)`),s.failed&&a.push(`${s.failed} failed`),console.log(a.join(", ")+".")}s&&(s.withIssues>0||s.failed>0)&&(process.exitCode=1)}async function xn(e){let t=p(),r=m(t),n=await Co(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function bn(e){let t=p(),r=m(t),n=await Dt(r,{conceptId:e.id,term:e.term,type:e.type,semanticTag:e.tag,moduleId:e.module,acceptability:e.acceptability,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Sn(e){let t=p(),r=m(t),n=await Ot(r,{conceptId:e.id,typeId:e.type,targetId:e.target,groupId:e.group?Number(e.group):void 0,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function vn(e){let t=p(),r=m(t),n=await Zt(r,{conceptId:e.id,axiomId:e.axiomId,relationshipId:e.relationshipId,relationshipIndex:e.relationshipIndex?Number(e.relationshipIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Tn(e){let t;try{t=JSON.parse(e.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await eo(n,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Rn(e){let t=p(),r=m(t),n=await Lt(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function An(e){let t=p(),r=m(t),n=await Bt(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function wn(e){let t=p(),r=m(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(u){console.error(`--entries is not valid JSON: ${u.message}`),process.exitCode=1;return}if(!Array.isArray(s)||s.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await Vt(r,{conceptId:e.id,entries:s,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${s.length} description(s) on concept ${e.id}`),x(c.validationResults);return}let d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),process.exitCode=1;return}if(!e.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await Ut(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let s=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${s.join(", ")})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function $n(e){let t=p(),r=m(t),n=await Kt(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function En(e){let t=p(),r=m(t),n=await Ft(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function jn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Fe(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Pn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Wt(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Nn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=p(),n=m(r),o=await Qt(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Dn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=p(),n=m(r),o=await Ke(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function On(e){let t=p(),r=m(t),n=await ro(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Fn(e){let t=p(),r=m(t),n=await qt(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Kn(e){let t=p(),r=m(t),n=await Jt(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Ln(e){let t=p(),r=m(t),n=await Gt(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to restore description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Bn(e){let t=p(),r=m(t),n=await Yt(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to replace FSN (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Mn(e){let t=p(),r=m(t),n=await Ht(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set description inactivation reason (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function _n(e){let t=p(),r=m(t),n=await zt(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Un(e){let t=p(),r=m(t),n=await Le(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Vn(e){let t=p(),r=m(t),n=await ue(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){if(o.alreadyConformed)console.log(`Concept ${e.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let s=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=s.length>0?s[s.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function qn(e){let t=p(),r=m(t),n=await le(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}if(o.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${o.axiomId}) \u2014 ${o.message}`)}async function Jn(e){let t=p(),r=m(t),n=await to(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Gn(e){let t=p(),r=m(t),n=await oo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}function Y(e){let t=e.account?.login;return t?No(m(e),t):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function Hn(e){let t=p(),r=m(t),n=Y(t),o;try{o=await ge(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?(console.log(`Classification ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),i.details&&console.log(JSON.stringify(i.details,null,2)),i.save&&(i.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${i.save.error?`: ${i.save.error}`:""}${i.save.status?` (status: ${i.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${i.jobId} (${i.status})`),i.timedOut&&(process.exitCode=1);return}let s=i.details!==void 0?` \u2014 details: ${JSON.stringify(i.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function Yn(e){let t=p(),r=m(t),n=await go(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Wn(e){let t=p(),r=m(t),n=Y(t),o;try{o=await ko(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?console.log(`Validation ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),i.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function Qn(e){let t=p(),r=m(t),n=await yo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function zn(e){let t=p(),r=m(t),n=Y(t);try{let o=await Do(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=o.body;if(o.statusCode<200||o.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var at=T(require("os")),W=T(require("path"));var v=T(require("fs")),it=T(require("os")),b=T(require("path")),E="authoring-cli",D=["claude","codex"];function Re(e){let t=[b.resolve(e,"..","skills",E),b.resolve(e,"..","..","skills",E)];for(let r of t)if(v.existsSync(b.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${E}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function Ni(e){let t=[];return v.existsSync(b.join(e,".claude"))&&t.push("claude"),v.existsSync(b.join(e,".codex"))&&t.push("codex"),t}function te(e,t){if(e==="all")return[...D];if(e){let n=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),o=n.filter(i=>!D.includes(i));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=Ni(t);return r.length?r:["claude"]}var Zn="# authoring-cli \u2014 SNOMED CT authoring guidance";function Di(e){let t=b.join(e,"SKILL.md"),r=b.join(e,"references","batch-authoring.md");return[Zn,"",`Read \`${t}\` now, and follow it for the rest of this session whenever you run the`,"`authoring-cli` command \u2014 before any concept creation, description/acceptability edit,","relationship or axiom edit, `classify`, or `validate-task`. It documents server-side","constraints and async behavior that fail or mislead in non-obvious ways, so reading it after","a command has already failed is too late.","",`Also read \`${r}\` when the task is a large, multi-session batch (tens to thousands of`,"concepts generated from a source list).","","Both files live inside the installed `authoring-cli` npm package, so they stay in step with","the CLI itself. If the paths above no longer exist, the package moved or was upgraded to a","different location \u2014 re-run `authoring-cli install-skill` to refresh this prompt.",""].join(`
19
+ `)}function Ae(e){try{return b.resolve(b.dirname(e),v.readlinkSync(e))}catch{return null}}function oe(e){try{return v.lstatSync(e)}catch{return null}}function st(e){let t=Ae(e);return t?v.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:oe(e)?.isDirectory()?"an existing directory":"an existing file"}function er(e){let t=Ae(e);return t!==null&&b.basename(t)===E&&b.basename(b.dirname(t))==="skills"}function tr(e){if(!oe(e)?.isFile())return!1;try{return v.readFileSync(e,"utf8").startsWith(Zn)}catch{return!1}}function Xn(e){return v.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>b.relative(e,b.join(t.parentPath,t.name))).sort()}function or(e,t){if(!t||!v.existsSync(t))return!1;try{let r=Xn(t);return r.join(`
20
+ `)!==Xn(e).join(`
21
+ `)?!1:r.every(n=>v.readFileSync(b.join(e,n)).equals(v.readFileSync(b.join(t,n))))}catch{return!1}}function Oi(e,t,r){let n=e.project?b.join(r,".claude","skills"):b.join(t,".claude","skills"),o=b.join(n,E),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+b.sep)?b.relative(b.dirname(o),i):i,a=oe(o),c=!1;if(a){let d=Ae(o);if(d===i&&v.existsSync(d))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:i};if(!(er(o)||or(o,i))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:st(o)};v.rmSync(o,{recursive:!0,force:!0}),c=!0}v.mkdirSync(n,{recursive:!0});try{return v.symlinkSync(s,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(d){let u=d.code;if(u!=="EPERM"&&u!=="EACCES")throw d;return v.cpSync(i,o,{recursive:!0}),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function Fi(e,t){let r=b.join(t,".codex","prompts"),n=b.join(r,`${E}.md`),o=Di(e.shippedSkillDir),i=oe(n),s=!1;if(i){if((i.isFile()?v.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!tr(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:st(n)};v.rmSync(n,{recursive:!0,force:!0}),s=!0}return v.mkdirSync(r,{recursive:!0}),v.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:s?"replaced":"installed",kind:"pointer"}}function nr(e){let t=e.homeDir??it.homedir(),r=e.cwd??process.cwd();return(e.agents??te(void 0,t)).map(o=>o==="claude"?Oi(e,t,r):Fi(e,t))}function rr(e){let t=e.homeDir??it.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?b.join(e.project?b.join(r,".claude"):b.join(t,".claude"),"skills",E):b.join(t,".codex","prompts",`${E}.md`);if(!oe(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?er(o)||or(o,e.shippedSkillDir):tr(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${st(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=Ae(o)??void 0;return v.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:s}})}function ir(e){let t=at.homedir();return e===t||e.startsWith(t+W.sep)?W.join("~",W.relative(t,e)):e}function Ki(e){let t=ir(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${ir(e.detail??"")})`:e.kind==="copy"?`${t} (copy \u2014 ${e.detail})`:`${t} (pointer into the installed package)`;case"already-current":return`${t} (already registered \u2014 nothing to do)`;case"blocked":return`${t} NOT written \u2014 ${e.detail} is in the way; re-run with --force to replace it`}}async function sr(e){let t=Re(__dirname),r=te(e.agent,at.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=nr({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),i=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${E}' for:`:i.length?`Could not install skill '${E}':`:`Skill '${E}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${Ki(a)}`);if(e.project&&r.includes("claude")&&console.log(`
22
22
  Project-scoped install: commit .claude/skills only if authoring-cli is a dependency of this
23
- repo \u2014 a link into a globally installed package resolves on your machine alone.`),s.length){process.exitCode=1;return}o.length&&(console.log(`
24
- Restart your agent, then use /${E}.`),n.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let i=D.filter(a=>!r.includes(a));i.length&&!e.agent&&console.log(`
25
- Skipped ${i.join(", ")} (no config directory found). Pass --agent ${i.join(",")} to register anyway.`)}var at=T(require("os")),z=T(require("path"));function nr(e){let t=at.homedir();return e===t||e.startsWith(t+z.sep)?z.join("~",z.relative(t,e)):e}function Ns(e){let t=nr(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${nr(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function rr(e){let t=e.agent?te(e.agent,at.homedir()):[...D],r;try{r=Te(__dirname)}catch{r=void 0}let n=er({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),o=n.filter(i=>i.status==="removed"),s=n.filter(i=>i.status==="left-alone");console.log(o.length?`Removed skill '${E}' registration for:`:s.length?`Left every registration of '${E}' in place:`:`No '${E}' registration found:`);for(let i of n)console.log(` ${i.agent.padEnd(7)} ${Ns(i)}`);if(s.length){process.exitCode=1;return}o.length&&console.log(`
26
- Restart your agent to drop /authoring-cli from its command list.`)}function Ds(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")){let o=n.slice(2),s=e[r+1],i=s&&!s.startsWith("--")?e[++r]:"";t[o]=i}}return t}function ir(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var ct=[{name:"login",usage:`login [${re.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--chrome-profile <name>] [--cookie-name <name>] (opens Chrome to sign in; automatically captures the session, macOS + Chrome only at launch. Environment defaults to ${Q}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>Xo({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],chromeProfile:e["chrome-profile"],cookieName:e["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>Zo()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>en()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${D.join("|")}|all] [--project] [--force] (registers the authoring guidance skill bundled with this package with your AI agent, so /authoring-cli works alongside these commands \u2014 defaults to whichever agents are installed)`,run:e=>or({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${D.join("|")}|all] [--project] [--force] (removes what install-skill registered \u2014 run this BEFORE "npm rm -g authoring-cli", since npm runs no uninstall hooks and this command goes away with the package)`,run:e=>rr({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:e=>on({json:"json"in e})},{name:"tasks",usage:`tasks [--project <projectKey>] [--mine] [--status <status>] [--summary] [--json] (lists a project's tasks, or your own tasks across all projects if --project is omitted; --mine restricts to tasks assigned to you, --status filters by status e.g. "In Progress", --summary prints counts by project/assignee/status instead of one line per task)`,run:e=>rn({project:e.project,mine:"mine"in e,status:e.status,summary:"summary"in e,json:"json"in e})},{name:"create-task",usage:'create-task --project <projectKey> --summary "<title>" [--description "<text>"] [--assignee <username>] [--unassigned] [--no-select] [--json] (creates a task via authoring-services and selects it; assigned to you unless overridden)',required:["project","summary"],run:e=>sn({project:e.project,summary:e.summary,description:e.description,assignee:e.assignee,unassigned:"unassigned"in e,noSelect:"no-select"in e,json:"json"in e})},{name:"delete-task",usage:"delete-task [--project <projectKey> --task <taskKey>] (marks the task Deleted, defaulting to the selected task and clearing that selection; the branch and its content are left alone)",run:e=>an({project:e.project,task:e.task})},{name:"recover-task",usage:"recover-task --project <projectKey> [--task <taskKey>] [--no-select] [--json] (without --task, lists the project's deleted tasks; with it, moves that task out of Deleted, keeps its branch content, and selects it)",required:["project"],run:e=>cn({project:e.project,task:e.task,noSelect:"no-select"in e,json:"json"in e})},{name:"select-task",usage:"select-task --project <projectKey> --task <taskKey> (sets the task subsequent commands target when --project/--task are omitted)",required:["project","task"],run:e=>dn({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints the locally selected task; with --project/--task, notes whether they match \u2014 standalone has no editor UI to compare against instead)",run:e=>un({project:e.project,task:e.task})},{name:"create-concept",usage:'create-concept --fsn "<term>" --parent <SCTID> [--tag <semantic tag>] [--pt "<preferred term>"] [--module <moduleId>] [--project <projectKey> --task <taskKey>]',required:["fsn","parent"],run:e=>ln({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:`search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (--check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never "conforms"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)`,run:e=>pn({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--project <projectKey> --task <taskKey>] (--attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type is required for --gci to have any effect; a plain get-concept with no flags already shows gciAxioms.length for a quick has-it-got-any-GCIs check)",required:["id"],run:e=>mn({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes)",required:["id"],run:e=>fn({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first, so it is checked and fixed once for the whole batch by review-concepts instead of per single-concept call here)",required:["id"],run:e=>gn({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>yn({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues; does not cover class-axiom authoring-form conformance, see review-concepts)',run:e=>kn({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (the end-of-task review pipeline for every concept with pending stated changes: classifies the branch, transforms any class axiom that doesn't already match transform-axiom's standard authoring form, then fetches each concept's final representation \u2014 descriptions, relationships, axioms \u2014 reflecting any transform just applied. Does not re-run Snowstorm's own convention check (that already happened on each edit's own save); run validate-review-concepts yourself if you want that re-checked in batch. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)",run:e=>hn({project:e.project,task:e.task})},{name:"add-description",usage:'add-description --id <SCTID> --term "<text>" --type FSN|SYNONYM [--tag <semanticTag>] [--module <id>] [--acceptability PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>]',required:["id","term","type"],run:e=>Cn({id:e.id,term:e.term,type:e.type,tag:e.tag,module:e.module,acceptability:e.acceptability,project:e.project,task:e.task})},{name:"update-description",usage:'update-description --id <SCTID> --description-id <descriptionId> [--term "<text>"] [--case-significance <value>] [--project <projectKey> --task <taskKey>] (only if never versioned; reuses the existing descriptionId)',required:["id","description-id"],run:e=>Sn({id:e.id,descriptionId:e["description-id"],term:e.term,caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-case-significance",usage:"set-case-significance --id <SCTID> --description-id <descriptionId> --case-significance CASE_INSENSITIVE|INITIAL_CHARACTER_CASE_INSENSITIVE|ENTIRE_TERM_CASE_SENSITIVE [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","description-id","case-significance"],run:e=>vn({id:e.id,descriptionId:e["description-id"],caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-acceptability",usage:`set-acceptability --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--project <projectKey> --task <taskKey>] (at least one of --lang, --us, --gb required)
27
- set-acceptability --id <SCTID> --entries '[{"descriptionId":"...","gb":"PREFERRED"},{"descriptionId":"...","gb":"ACCEPTABLE"}]' [--project <projectKey> --task <taskKey>] (applies all entries in one save)`,required:["id"],run:e=>Tn({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,entries:e.entries,project:e.project,task:e.task})},{name:"add-relationship",usage:"add-relationship --id <SCTID> --type <SCTID> --target <SCTID> [--group N] [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","type","target"],run:e=>In({id:e.id,type:e.type,target:e.target,group:e.group,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"remove-relationship",aliases:["delete-relationship"],usage:"remove-relationship --id <SCTID> --axiom-id <axiomId> (--relationship-id <relationshipId> | --relationship-index N) [--project <projectKey> --task <taskKey>] (only if the targeted relationship was never versioned)",required:["id","axiom-id"],run:e=>xn({id:e.id,axiomId:e["axiom-id"],relationshipId:e["relationship-id"],relationshipIndex:e["relationship-index"],project:e.project,task:e.task})},{name:"remove-role-group",aliases:["delete-role-group","delete-rolegroup"],usage:`remove-role-group --id <SCTID> --axiom-id <axiomId> --attributes '[{"typeId":"...","targetId":"..."}]' [--group-id N] [--project <projectKey> --task <taskKey>]`,required:["id","axiom-id","attributes"],run:e=>bn({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>Rn({id:e.id,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"set-definition-status",usage:"set-definition-status --id <SCTID> --status PRIMITIVE|FULLY_DEFINED [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","status"],run:e=>wn({id:e.id,status:e.status,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"update-axiom",usage:`update-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:e=>An({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,project:e.project,task:e.task})},{name:"add-axiom",usage:`add-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--definition-status PRIMITIVE|FULLY_DEFINED] [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new class axiom; use to replace a published axiom \u2014 add the replacement here, then inactivate-axiom the old one)`,required:["id","relationships"],run:e=>jn({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.task})},{name:"add-gci-axiom",usage:`add-gci-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new GCI axiom; the relationships are the axiom's sufficient-condition side)`,required:["id","relationships"],run:e=>En({id:e.id,relationships:e.relationships,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"update-gci-axiom",usage:`update-gci-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:e=>$n({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>Pn({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>Nn({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>Dn({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
28
- restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save)`,required:["id","description-id"],run:e=>On({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-refset <id> --association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>Fn({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>Kn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom)",required:["id","axiom-id"],run:e=>Ln({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"transform-axiom",usage:"transform-axiom --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (rewrites a class axiom into the standard authoring form \u2014 Is-a to the proximal primitive parent(s) plus every currently-inferred attribute, per Snowstorm's own authoring-form computation; a never-versioned axiom is updated in place, a published one is replaced by adding the transformed axiom and inactivating the original \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>Bn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>Mn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>_n({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional)",required:["id","axiom-id"],run:e=>Un({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"classify",usage:"classify [--wait] [--timeout <seconds>, default 180] [--project <projectKey> --task <taskKey>] (self-healing: attaches to an already-running job, accepts an already-completed-but-unsaved one, or starts fresh)",run:e=>qn({wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"classification-status",usage:"classification-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Vn({project:e.project,task:e.task})},{name:"validate-task",usage:"validate-task [--enable-mrcm] [--wait] [--timeout <seconds>, default 900] [--project <projectKey> --task <taskKey>] (validates the whole task branch \u2014 distinct from validate-concept)",run:e=>Jn({enableMrcm:"enable-mrcm"in e,wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"validation-status",usage:"validation-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Gn({project:e.project,task:e.task})},{name:"watch-notification",usage:"watch-notification [--entity-type <type>] [--timeout <seconds>, default 60] [--project <projectKey> --task <taskKey>] (blocks until the next real-time notification for this task arrives, or the timeout elapses \u2014 opens a temporary STOMP connection for the duration of this call)",run:e=>Hn({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function ar(e){if(!e.aliases?.length)return e.usage;let t=`(alias: ${e.aliases.join(", ")})`;return e.usage.startsWith(e.name)?`${e.name} ${t}${e.usage.slice(e.name.length)}`:`${e.usage} ${t}`}function sr(){return["Usage: authoring-cli <command> [options]","","Commands:",...ct.map(e=>` ${ar(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
29
- `)}async function cr(e=process.argv){let[,,t,...r]=e,n=Ds(r),o=ir(r);if(!t){console.log(sr());return}let s=ct.find(a=>a.name===t||a.aliases?.includes(t));if(!s){console.error(`Unknown command: ${t}
23
+ repo \u2014 a link into a globally installed package resolves on your machine alone.`),i.length){process.exitCode=1;return}o.length&&(console.log(`
24
+ Restart your agent, then use /${E}.`),n.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let s=D.filter(a=>!r.includes(a));s.length&&!e.agent&&console.log(`
25
+ Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var ct=T(require("os")),Q=T(require("path"));function ar(e){let t=ct.homedir();return e===t||e.startsWith(t+Q.sep)?Q.join("~",Q.relative(t,e)):e}function Li(e){let t=ar(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${ar(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function cr(e){let t=e.agent?te(e.agent,ct.homedir()):[...D],r;try{r=Re(__dirname)}catch{r=void 0}let n=rr({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),o=n.filter(s=>s.status==="removed"),i=n.filter(s=>s.status==="left-alone");console.log(o.length?`Removed skill '${E}' registration for:`:i.length?`Left every registration of '${E}' in place:`:`No '${E}' registration found:`);for(let s of n)console.log(` ${s.agent.padEnd(7)} ${Li(s)}`);if(i.length){process.exitCode=1;return}o.length&&console.log(`
26
+ Restart your agent to drop /authoring-cli from its command list.`)}function Bi(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")){let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[o]=s}}return t}function ur(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var dt=[{name:"login",usage:`login [${re.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--chrome-profile <name>] [--cookie-name <name>] (opens Chrome to sign in; automatically captures the session, macOS + Chrome only at launch. Environment defaults to ${z}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>tn({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],chromeProfile:e["chrome-profile"],cookieName:e["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>on()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>nn()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${D.join("|")}|all] [--project] [--force] (registers the authoring guidance skill bundled with this package with your AI agent, so /authoring-cli works alongside these commands \u2014 defaults to whichever agents are installed)`,run:e=>sr({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${D.join("|")}|all] [--project] [--force] (removes what install-skill registered \u2014 run this BEFORE "npm rm -g authoring-cli", since npm runs no uninstall hooks and this command goes away with the package)`,run:e=>cr({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:e=>sn({json:"json"in e})},{name:"tasks",usage:`tasks [--project <projectKey>] [--mine] [--status <status>] [--summary] [--json] (lists a project's tasks, or your own tasks across all projects if --project is omitted; --mine restricts to tasks assigned to you, --status filters by status e.g. "In Progress", --summary prints counts by project/assignee/status instead of one line per task)`,run:e=>cn({project:e.project,mine:"mine"in e,status:e.status,summary:"summary"in e,json:"json"in e})},{name:"create-task",usage:'create-task --project <projectKey> --summary "<title>" [--description "<text>"] [--assignee <username>] [--unassigned] [--no-select] [--json] (creates a task via authoring-services and selects it; assigned to you unless overridden)',required:["project","summary"],run:e=>dn({project:e.project,summary:e.summary,description:e.description,assignee:e.assignee,unassigned:"unassigned"in e,noSelect:"no-select"in e,json:"json"in e})},{name:"delete-task",usage:"delete-task [--project <projectKey> --task <taskKey>] (marks the task Deleted, defaulting to the selected task and clearing that selection; the branch and its content are left alone)",run:e=>un({project:e.project,task:e.task})},{name:"recover-task",usage:"recover-task --project <projectKey> [--task <taskKey>] [--no-select] [--json] (without --task, lists the project's deleted tasks; with it, moves that task out of Deleted, keeps its branch content, and selects it)",required:["project"],run:e=>ln({project:e.project,task:e.task,noSelect:"no-select"in e,json:"json"in e})},{name:"select-task",usage:"select-task --project <projectKey> --task <taskKey> (sets the task subsequent commands target when --project/--task are omitted)",required:["project","task"],run:e=>pn({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints the locally selected task; with --project/--task, notes whether they match \u2014 standalone has no editor UI to compare against instead)",run:e=>mn({project:e.project,task:e.task})},{name:"create-concept",usage:'create-concept --fsn "<term>" --parent <SCTID> [--tag <semantic tag>] [--pt "<preferred term>"] [--module <moduleId>] [--project <projectKey> --task <taskKey>]',required:["fsn","parent"],run:e=>fn({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:`search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (--check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never "conforms"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)`,run:e=>gn({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--project <projectKey> --task <taskKey>] (--attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type is required for --gci to have any effect; a plain get-concept with no flags already shows gciAxioms.length for a quick has-it-got-any-GCIs check)",required:["id"],run:e=>yn({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes)",required:["id"],run:e=>kn({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first, so it is checked and fixed once for the whole batch by review-concepts instead of per single-concept call here)",required:["id"],run:e=>hn({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>Cn({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues; does not cover class-axiom authoring-form conformance, see review-concepts)',run:e=>In({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (the end-of-task review pipeline for every concept with pending stated changes: classifies the branch, transforms any class axiom that doesn't already match transform-axiom's standard authoring form, then fetches each concept's final representation \u2014 descriptions, relationships, axioms \u2014 reflecting any transform just applied. Does not re-run Snowstorm's own convention check (that already happened on each edit's own save); run validate-review-concepts yourself if you want that re-checked in batch. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)",run:e=>xn({project:e.project,task:e.task})},{name:"add-description",usage:'add-description --id <SCTID> --term "<text>" --type FSN|SYNONYM [--tag <semanticTag>] [--module <id>] [--acceptability PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>]',required:["id","term","type"],run:e=>bn({id:e.id,term:e.term,type:e.type,tag:e.tag,module:e.module,acceptability:e.acceptability,project:e.project,task:e.task})},{name:"update-description",usage:'update-description --id <SCTID> --description-id <descriptionId> [--term "<text>"] [--case-significance <value>] [--project <projectKey> --task <taskKey>] (only if never versioned; reuses the existing descriptionId)',required:["id","description-id"],run:e=>Rn({id:e.id,descriptionId:e["description-id"],term:e.term,caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-case-significance",usage:"set-case-significance --id <SCTID> --description-id <descriptionId> --case-significance CASE_INSENSITIVE|INITIAL_CHARACTER_CASE_INSENSITIVE|ENTIRE_TERM_CASE_SENSITIVE [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","description-id","case-significance"],run:e=>An({id:e.id,descriptionId:e["description-id"],caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-acceptability",usage:`set-acceptability --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--project <projectKey> --task <taskKey>] (at least one of --lang, --us, --gb required)
27
+ set-acceptability --id <SCTID> --entries '[{"descriptionId":"...","gb":"PREFERRED"},{"descriptionId":"...","gb":"ACCEPTABLE"}]' [--project <projectKey> --task <taskKey>] (applies all entries in one save)`,required:["id"],run:e=>wn({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,entries:e.entries,project:e.project,task:e.task})},{name:"add-relationship",usage:"add-relationship --id <SCTID> --type <SCTID> --target <SCTID> [--group N] [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","type","target"],run:e=>Sn({id:e.id,type:e.type,target:e.target,group:e.group,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"remove-relationship",aliases:["delete-relationship"],usage:"remove-relationship --id <SCTID> --axiom-id <axiomId> (--relationship-id <relationshipId> | --relationship-index N) [--project <projectKey> --task <taskKey>] (only if the targeted relationship was never versioned)",required:["id","axiom-id"],run:e=>vn({id:e.id,axiomId:e["axiom-id"],relationshipId:e["relationship-id"],relationshipIndex:e["relationship-index"],project:e.project,task:e.task})},{name:"remove-role-group",aliases:["delete-role-group","delete-rolegroup"],usage:`remove-role-group --id <SCTID> --axiom-id <axiomId> --attributes '[{"typeId":"...","targetId":"..."}]' [--group-id N] [--project <projectKey> --task <taskKey>]`,required:["id","axiom-id","attributes"],run:e=>Tn({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>$n({id:e.id,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"set-definition-status",usage:"set-definition-status --id <SCTID> --status PRIMITIVE|FULLY_DEFINED [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","status"],run:e=>En({id:e.id,status:e.status,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"update-axiom",usage:`update-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:e=>jn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,project:e.project,task:e.task})},{name:"add-axiom",usage:`add-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--definition-status PRIMITIVE|FULLY_DEFINED] [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new class axiom; use to replace a published axiom \u2014 add the replacement here, then inactivate-axiom the old one)`,required:["id","relationships"],run:e=>Dn({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.task})},{name:"add-gci-axiom",usage:`add-gci-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new GCI axiom; the relationships are the axiom's sufficient-condition side)`,required:["id","relationships"],run:e=>Nn({id:e.id,relationships:e.relationships,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"update-gci-axiom",usage:`update-gci-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:e=>Pn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>On({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>Fn({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; --association-target is always a REFERS_TO association \u2014 a description has no other association type; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>Kn({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
28
+ restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save; --association-target there is always a REFERS_TO association)`,required:["id","description-id"],run:e=>Ln({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; --association-target is always a REFERS_TO association; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>Bn({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"set-description-inactivation-reason",usage:"set-description-inactivation-reason --id <SCTID> --description-id <descriptionId> --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id <SCTID>] [--project <projectKey> --task <taskKey>] (assigns or retargets the reason on a description that is already inactive, without touching its active state \u2014 --target-id is required for reason NOT_SEMANTICALLY_EQUIVALENT (the concept this description actually belongs under, via a REFERS_TO association) and rejected for the other three reasons, which take no target; 409s if the reason currently assigned has already been published \u2014 only an unpublished reason can be retargeted; for a description that is still active, use inactivate-description instead)",required:["id","description-id","reason"],run:e=>Mn({id:e.id,descriptionId:e["description-id"],reason:e.reason,targetId:e["target-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>_n({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom)",required:["id","axiom-id"],run:e=>Un({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"transform-axiom",usage:"transform-axiom --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (rewrites a class axiom into the standard authoring form \u2014 Is-a to the proximal primitive parent(s) plus every currently-inferred attribute, per Snowstorm's own authoring-form computation; a never-versioned axiom is updated in place, a published one is replaced by adding the transformed axiom and inactivating the original \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>Vn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>qn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>Jn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional)",required:["id","axiom-id"],run:e=>Gn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"classify",usage:"classify [--wait] [--timeout <seconds>, default 180] [--project <projectKey> --task <taskKey>] (self-healing: attaches to an already-running job, accepts an already-completed-but-unsaved one, or starts fresh)",run:e=>Hn({wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"classification-status",usage:"classification-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Yn({project:e.project,task:e.task})},{name:"validate-task",usage:"validate-task [--enable-mrcm] [--wait] [--timeout <seconds>, default 900] [--project <projectKey> --task <taskKey>] (validates the whole task branch \u2014 distinct from validate-concept)",run:e=>Wn({enableMrcm:"enable-mrcm"in e,wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"validation-status",usage:"validation-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Qn({project:e.project,task:e.task})},{name:"watch-notification",usage:"watch-notification [--entity-type <type>] [--timeout <seconds>, default 60] [--project <projectKey> --task <taskKey>] (blocks until the next real-time notification for this task arrives, or the timeout elapses \u2014 opens a temporary STOMP connection for the duration of this call)",run:e=>zn({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function lr(e){if(!e.aliases?.length)return e.usage;let t=`(alias: ${e.aliases.join(", ")})`;return e.usage.startsWith(e.name)?`${e.name} ${t}${e.usage.slice(e.name.length)}`:`${e.usage} ${t}`}function dr(){return["Usage: authoring-cli <command> [options]","","Commands:",...dt.map(e=>` ${lr(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
29
+ `)}async function pr(e=process.argv){let[,,t,...r]=e,n=Bi(r),o=ur(r);if(!t){console.log(dr());return}let i=dt.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
30
30
 
31
- ${sr()}`),process.exitCode=1;return}let i=(s.required??[]).filter(a=>!n[a]);if(i.length){console.error(`Missing required flag(s): ${i.map(a=>`--${a}`).join(", ")}
31
+ ${dr()}`),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!n[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
32
32
 
33
- Usage: ${ar(s)}`),process.exitCode=1;return}await s.run(n,o)}require.main===module&&cr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
33
+ Usage: ${lr(i)}`),process.exitCode=1;return}await i.run(n,o)}require.main===module&&pr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "authoring-cli",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "CLI for SNOMED CT authoring against authoring-services",
5
5
  "license": "Apache-2.0",
6
6
  "bin": {
@@ -748,8 +748,8 @@ validation problem — check 1 is worth running before either command.
748
748
 
749
749
  The same choice exists one level down, for a single description: `delete-description` splices a
750
750
  never-versioned FSN/PT/synonym out entirely, while `inactivate-description --id <SCTID>
751
- --description-id <descriptionId> --indicator <value> [--association-refset <id>
752
- --association-target <SCTID>]` retires a *released* one in place, matching real RF2 data — an
751
+ --description-id <descriptionId> --indicator <value> [--association-target <SCTID>]` retires a
752
+ *released* one in place, matching real RF2 data — an
753
753
  already-inactive description always has an empty `acceptabilityMap`, so `inactivate-description`
754
754
  clears it for you rather than leaving a stale PREFERRED/ACCEPTABLE entry behind. Each command
755
755
  guards the case the other one is for: `delete-description` 409s on a versioned description,
@@ -758,6 +758,10 @@ inactivating a dialect's sole PT clears its only PREFERRED entry in that refset,
758
758
  `inactivate-description` itself gets the 400 if you do it first. Same fix as replacing a published
759
759
  axiom — promote the replacement synonym to PREFERRED with `set-acceptability`/`--entries` *before*
760
760
  inactivating the old PT, not after, so the dialect never has zero PREFERREDs at any save boundary.
761
+ Unlike `inactivate-concept`, there's no `--association-refset` choice here: a description's
762
+ historical association is always `REFERS_TO`, regardless of indicator, so `--association-target`
763
+ is the only flag needed — confirmed live against real content, where passing the numeric refset id
764
+ as the association key instead 400s outright ("Description inactivation indicator not recognised").
761
765
 
762
766
  `restore-description --id <SCTID> --description-id <descriptionId> [--lang <code>] [--us
763
767
  PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE]` reverses `inactivate-description`. Because
@@ -785,11 +789,34 @@ ACCEPTABLE-staged FSN to add safely first the way a synonym has. Retiring the ol
785
789
  new one as two separate `inactivate-description` + `add-description` saves 400s no matter which
786
790
  order you pick — add first and there are briefly two PREFERRED FSNs in the dialect, retire first and
787
791
  there are briefly zero. Use `replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value>
788
- [--description-id <oldFsnDescriptionId>] [--association-refset <id> --association-target <SCTID>]`
792
+ [--description-id <oldFsnDescriptionId>] [--association-target <SCTID>]`
789
793
  instead — it bundles both edits into the one save that actually works. `--description-id` is only
790
794
  required when the concept has more than one active FSN to disambiguate; a never-versioned FSN
791
795
  should go through `update-description` (in-place term edit), not `replace-fsn`.
792
796
 
797
+ ### Assigning or retargeting a description's inactivation reason on its own
798
+
799
+ `inactivate-description --indicator` accepts any free-text value, because real content still
800
+ carries the older/broader RF2 vocabulary (`ERRONEOUS`, `DUPLICATE`, ...). `set-description-inactivation-reason
801
+ --id <SCTID> --description-id <descriptionId> --reason <value>` is narrower and separate: it's for
802
+ assigning or changing the reason on a description that's *already* inactive, independent of the
803
+ inactivation act itself, and restricted to the four values SNOMED International's current editorial
804
+ policy actually permits a description to be given: `NOT_SEMANTICALLY_EQUIVALENT`, `OUTDATED`,
805
+ `GRAMMATICAL_DESCRIPTION_ERROR`, `NONCONFORMANCE_TO_EDITORIAL_POLICY`. It 409s if the description is
806
+ still active — inactivating with a reason at the same time is still `inactivate-description`'s job.
807
+
808
+ `NOT_SEMANTICALLY_EQUIVALENT` is the only one of the four that carries an association, and it's
809
+ always `REFERS_TO`, pointing at the concept the description actually belongs under — so
810
+ `--target-id <SCTID>` is required for that reason and rejected for the other three, which take no
811
+ target at all.
812
+
813
+ It also guards something `inactivate-description` doesn't need to: once the *reason itself* has
814
+ been published, it can't be retargeted, and the command 409s. This is a narrower fact than the
815
+ description's own `effectiveTime` — a description can sit on the very same released row across
816
+ several releases while the reason attached to it is re-versioned independently underneath it in a
817
+ later one, so retargeting is checked against the reason's own reference-set membership, not the
818
+ description's `effectiveTime`.
819
+
793
820
  The same choice exists for a single class axiom too: `delete-axiom --id <SCTID> --axiom-id
794
821
  <axiomId>` 409s on a versioned axiom, `inactivate-axiom --id <SCTID> --axiom-id <axiomId>` 409s on
795
822
  a never-versioned one — same guard pairing as concept/description. There's no indicator or