authoring-cli 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -140,7 +140,7 @@ authoring-cli recover-task --project PROJ --task PROJ-123
|
|
|
140
140
|
| `set-definition-status` | Set PRIMITIVE/FULLY_DEFINED |
|
|
141
141
|
| `inactivate-concept` | Inactivate with a reason and optional association |
|
|
142
142
|
| `validate-concept` | Read-only pre-save validation check |
|
|
143
|
-
| `
|
|
143
|
+
| `get-concepts-for-review` | List concepts with pending stated/classified changes |
|
|
144
144
|
| `validate-review-concepts` | Validate every concept with pending stated changes, with a pass/issue tally |
|
|
145
145
|
| `classify` | Self-healing classification (attaches to a running job, accepts a completed one, or starts fresh) |
|
|
146
146
|
| `classification-status` | Read-only classification status |
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var $n=Object.create;var Q=Object.defineProperty;var An=Object.getOwnPropertyDescriptor;var En=Object.getOwnPropertyNames;var jn=Object.getPrototypeOf,Nn=Object.prototype.hasOwnProperty;var Pn=(e,t)=>{for(var r in t)Q(e,r,{get:t[r],enumerable:!0})},He=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of En(t))!Nn.call(e,o)&&o!==r&&Q(e,o,{get:()=>t[o],enumerable:!(n=An(t,o))||n.enumerable});return e};var T=(e,t,r)=>(r=e!=null?$n(jn(e)):{},He(t||!e||!e.__esModule?Q(r,"default",{value:e,enumerable:!0}):r,e)),Dn=e=>He(Q({},"__esModule",{value:!0}),e);var Or={};Pn(Or,{COMMANDS:()=>Ge,main:()=>Rn,parsePositionals:()=>vn});module.exports=Dn(Or);var F={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"}},On={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},Z=Object.keys(F);function We(e){return On[e.trim().toLowerCase()]??null}var G="uat",Kr=F.uat.imsEndpoint,Br=F.uat.terminologyServerEndpoint,Fr=F.uat.authoringServicesEndpoint;var Ln=T(require("http")),Kn=T(require("https"));function y(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 l=d.protocol==="https:"?Kn:Ln,u=o!==void 0?JSON.stringify(o):void 0,g={accept:"application/json",...s};if(u!==void 0&&(g["content-type"]="application/json",g["content-length"]=String(Buffer.byteLength(u))),n){let h=n.replace(/[^\x20-\x7e\t]/g,"");h&&(g.cookie=h)}let f=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:g},h=>{let C="";h.on("data",k=>{C+=k}),h.on("end",()=>{let k=h.statusCode??0,N=(h.headers["content-type"]??"").includes("application/json"),j=null,A=!1;if(C)try{j=JSON.parse(C)}catch{A=!N}a({statusCode:k,body:j,rawBody:C,sessionExpired:A})})});f.on("error",c),f.setTimeout(i,()=>{f.destroy(new Error(`Request to ${e} timed out after ${i}ms`))}),u!==void 0&&f.write(u),f.end()})}var K="900000000000509007",H="900000000000508004";var Ye={[K]:"en-us",[H]:"en-gb"},ze={[K]:"true",[H]:"true"},Bn={},Fn={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:Ye,dialectDefaults:ze,readOnlyDialects:Bn,defaultLanguage:"en"};function Xe(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Fn;let t={[K]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];t[String(e[c])]=l,o.length===0&&o.push(l)}}let s=e.requiredLanguageRefsets;if(Array.isArray(s))for(let c of s){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[h,C]of Object.entries(c))h.length===2&&(d=h,l=String(C));if(!d||!l)continue;let u=c.dialectName;t[l]=typeof u=="string"?u:d;let g=c.default;g==="true"&&!o.includes(d)&&o.push(d),g!=null&&(r[l]=String(g));let f=c.readOnly;f!=null&&(n[l]=String(f))}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?Ye:t,dialectDefaults:a?ze:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function ke(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 Qe(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[K]:"PREFERRED"}:ke(e,"PREFERRED",t,"en")}var Mn="900000000000207008";function Ze(e){return e.replace(/\/$/,"")}function w(e){return Ze(e.terminologyServerEndpoint)}function R(e){return Ze(e.authoringServicesEndpoint)}function et(e){return`${new URL(R(e)).origin}/authoring-traceability-service`}function M(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function x(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 Un(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 U(e,t){let r=w(e),n=await y(`${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 y(`${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 Un(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await y(n,{cookie:e.cookie})).body?.branchPath??null}async function tt(e,t,r){let n=r?.get(t);if(n)return n;let o=`${R(e)}/projects/${t}`,i=(await y(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,i),i}async function W(e,t,r){let n=await tt(e,t,r),o=n.multipleModuleEditingDisabled,s=!o||o==="false";return n.expectedExtensionModules?.length&&s?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:Mn}async function ee(e,t,r){let n=await tt(e,t,r);return Xe(n)}async function he(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await y(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 ot=T(require("crypto"));var _n="116680003";function te(e,t,r,n,o="PREFERRED",s=!1){let i=e==="FSN"?Qe(n,s):ke(n,o,s,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:i}}async function nt(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await x(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:s,taskKey:i,branchPath:a}=o,c=M(a),d=t.moduleId||await W(e,s,n),l=await ee(e,s,n),u=t.preferredTerm||t.fsn,g=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,f={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[te("FSN",g,d,l,"PREFERRED",!0),te("SYNONYM",u,d,l,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:ot.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:_n},target:{conceptId:t.parentConceptId}}]}]},h=`${w(e)}/browser/${c}/${s}/${i}/concepts/?validate=true`,C=await y(h,{method:"POST",body:f,cookie:e.cookie});if(C.sessionExpired){let N="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: SESSION EXPIRED`),{statusCode:401,body:{error:N}}}let k=C.body,v=k&&"conceptId"in k?k.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: ${C.statusCode<300?"OK":"FAILED ("+C.statusCode+")"} \u2014 ${g}`+(v?` \u2192 ${v}`:"")),typeof v=="string"&&e.onValidationResults?.(v,k?.validationResults),{statusCode:C.statusCode,body:C.body}}async function rt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${w(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await y(o,{cookie:e.cookie});return s.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:s.statusCode,body:s.body}}async function st(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await x(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=`${w(e)}/${n.branchPath}/concepts/search`,i=await y(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 it(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=w(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await y(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:`Concept ${t.conceptId} has effectiveTime ${String(i.body.effectiveTime)} set (already versioned) \u2014 cannot delete.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await y(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 at(e){return typeof e=="object"&&e!==null}function Vn(e){let t=e.type,r=e.target,n=at(t)?t.conceptId:void 0,o=at(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function qn(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 ct(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(Vn).filter(d=>d!=null);qn(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 mt=T(require("crypto"));var Jn=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],Gn=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],Hn=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Wn=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Yn=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],xe=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function ft(e){return xe.includes(e)}function Y(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function oe(e){return typeof e=="object"&&e!==null}function dt(e){return oe(e)?Y(e,Wn):e}function gt(e){if(!oe(e))return e;let t=Y(e,Hn);return"type"in t&&(t.type=dt(t.type)),"target"in t&&(t.target=dt(t.target)),t}function zn(e){return oe(e)?Y(e,Gn):e}function lt(e){if(!oe(e))return e;let t=Y(e,Yn);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(gt)),t}function Ie(e){let t=Y(e,Jn);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(zn)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(gt)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(lt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(lt)),t}async function E(e,t,r,n){let o=w(e),s=`${o}/browser/${t.branchPath}/concepts/${r}`,i=await y(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 ${r}.`,details:i.body}};let a=i.body,c=n(a);if(c)return c;let d=M(t.branchPath),l=`${o}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,u=await y(l,{method:"PUT",body:Ie(a),cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${u.statusCode<300?"OK":"FAILED ("+u.statusCode+")"} \u2014 ${r}`);let g=u.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:u.statusCode,body:u.body}}var ut=["PREFERRED","ACCEPTABLE"];async function yt(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&&!ut.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${ut.join(", ")}.`}};let o=await x(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await W(e,o.projectKey,n),i=await ee(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return E(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(te(t.type,a,s,i,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,null})}async function kt(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return E(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 ht(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 x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return E(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 Ct(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await x(e,t,r);return n.ok?E(e,n,t.conceptId,o=>(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 xt(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&&!ft(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${xe.join(", ")}.`}};let n=await x(e,t,r);return n.ok?E(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 It(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!ft(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${xe.join(", ")}.`}};let n=await x(e,t,r);return n.ok?E(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 Ce=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function pt(e){return Ce.includes(e)}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.`}}:e.us&&!pt(e.us)?{statusCode:400,body:{error:`us must be one of: ${Ce.join(", ")}.`}}:e.gb&&!pt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${Ce.join(", ")}.`}}:null:{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function St(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[K]:o[K]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[H]:o[H]=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 Tt(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 x(e,t,r);return s.ok?E(e,s,t.conceptId,i=>{let a=Array.isArray(i.descriptions)?i.descriptions:[];return St(a,t.conceptId,n)}):{statusCode:400,body:{error:s.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 s=bt(o);if(s)return s}let n=await x(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[];for(let i of t.entries){let a=St(s,t.conceptId,i);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function wt(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await x(e,t,r);return n.ok?E(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:`Description ${t.descriptionId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.descriptions=s,null)}):{statusCode:400,body:{error:n.error}}}async function Rt(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 x(e,t,r);return n.ok?E(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 $t(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 x(e,t,r);return n.ok?E(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 At(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 x(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await W(e,o.projectKey,n);return E(e,o,t.conceptId,i=>{let a=Array.isArray(i.gciAxioms)?i.gciAxioms:[];return a.push({axiomId:mt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),i.gciAxioms=a,null})}async function Et(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await x(e,t,r);return n.ok?E(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.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.classAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function jt(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 x(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.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(l=>l.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 Nt(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 x(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.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=ct(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let d=c.relationships.find(l=>l.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(l=>(typeof l.groupId=="number"?l.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function Pt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await x(e,t,r);return n.ok?E(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:`GCI axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.gciAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}function Xn(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 ne(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=w(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await y(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=M(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await y(c,{method:"POST",body:Ie(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 l=Array.isArray(d.body)?Xn(d.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:l,hasErrors:l.some(u=>u.severity==="ERROR"),hasWarnings:l.some(u=>u.severity==="WARNING")}}}var Dt=200;async function Qn(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${w(e)}/browser/${t}/concepts/bulk-load`,s=!0;for(let i=0;i<r.length;i+=Dt){let a=r.slice(i,i+Dt),c=await y(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 re(e,t,r){let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${et(e)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,s=await y(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=(C,k,v,N)=>{let j=C.get(k);j?(N.forEach(A=>A&&j.componentSubTypes.add(A)),j.lastUpdatedTime=v):C.set(k,{conceptId:k,lastUpdatedTime:v,componentSubTypes:new Set(N.filter(A=>!!A))})};for(let C of s.body?.content??[])if(!(C.activityType!=="CONTENT_CHANGE"&&C.activityType!=="CLASSIFICATION_SAVE"))for(let k of C.conceptChanges??[]){let v=String(k.conceptId),N=k.componentChanges??[],j=N.map(J=>J.componentSubType);if(C.activityType==="CLASSIFICATION_SAVE"){c(a,v,C.commitDate,j);continue}let A=N.some(J=>J.componentSubType!=="INFERRED_RELATIONSHIP");c(A?i:a,v,C.commitDate,j)}for(let C of i.keys())a.delete(C);let d=[...new Set([...i.keys(),...a.keys()])],{terms:l,resolved:u}=await Qn(e,n.branchPath,d),g=C=>[...C.values()].sort((k,v)=>(v.lastUpdatedTime??"").localeCompare(k.lastUpdatedTime??"")).map(k=>{let v=u&&!l.has(k.conceptId);return{conceptId:k.conceptId,fsn:l.get(k.conceptId)?.fsn,pt:l.get(k.conceptId)?.pt,...v?{deleted:!0}:{},lastUpdatedTime:k.lastUpdatedTime,changedComponentTypes:[...k.componentSubTypes]}}),f=g(i),h=g(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:f.length,conceptsDeleted:f.filter(C=>C.deleted).length,conceptsClassified:h.length}}:{},concepts:f,conceptsClassified:h}}}async function Ot(e,t,r){let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await re(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=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await ne(e,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l.error??`HTTP ${d.statusCode}`});continue}let u=l.validationResults??[];i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:u.length===0?"clean":"issues",validationResults:u.length?u:void 0,hasErrors:l.hasErrors})}let 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}}}var be=new Set;function Lt(e){if(!(!e||typeof e!="object"))for(let t of be)t(e)}function Zn(e){return be.add(e),()=>be.delete(e)}function er(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 se(e){let t=()=>{};return{promise:new Promise(n=>{t=Zn(o=>{er(o,e)&&(t(),n(o))})}),cancel:t}}async function O(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await y(n,{cookie:e.cookie})).body??null}var we=["RUNNING","BUILDING","SCHEDULED","QUEUED"],Re=["QUEUED","SCHEDULED","RUNNING"],tr=["Promoted","Completed"],Kt=5e3;function ve(e){return new Promise(t=>setTimeout(t,e))}async function or(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 ve(t)}}function nr(){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 rr=nr(),sr=180;function ir(){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 ar=ir(),cr=900;async function Mt(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?se(n):void 0,l=await Promise.race(d?[ve(c).then(()=>{}),d.promise]:[ve(c).then(()=>{})]);if(d?.cancel(),l){let f=l.event;o?.(`[${new Date().toISOString()}] woken by notification${f?`: ${f}`:""}`)}let{done:u,value:g}=await e();if(u)return{value:g,timedOut:!1};if(Date.now()-i>=s)return{value:g,timedOut:!0};a++}}async function Ut(e,t,r){let n=await O(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&tr.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${R(e)}/projects/${t}/tasks/${r}`;await y(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function $e(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await y(n,{method:"POST",body:{},cookie:e.cookie}),(await O(e,t,r))?.latestClassificationJson}async function Bt(e,t,r,n,o){let s,{value:i,timedOut:a}=await Mt(async()=>{let d=(await $e(e,t,r))?.status;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||we.includes(d)),value:d}},rr,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function Se(e,t,r){let n=`${w(e)}/${t}/classifications`,o=await y(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 _t(e,t,r){let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,i=await $e(e,o,s);return i?{statusCode:200,body:{hasClassification:!0,jobId:i.id,status:i.status,running:we.includes(i.status),latestClassificationJson:i}}:{statusCode:200,body:{hasClassification:!1}}}async function Vt(e,t,r){let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await Ut(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??sr,d=await $e(e,o,s),l=d?.status,u=d?.id;if(u&&l&&we.includes(l)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:A}=await Bt(e,o,s,i,c),J=await Se(e,i,u),ye={accepted:!1};return!A&&j==="COMPLETED"&&(ye=await Te(e,i,o,s,u)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: attached job ${u} final status ${j??"unknown"}${A?" (timed out waiting)":""}, save ${JSON.stringify(ye)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:A,details:J,save:ye,attachedToExisting:!0}}}if(u&&l==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await Se(e,i,u),A=await Te(e,i,o,s,u);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: accepted existing job ${u}, save ${JSON.stringify(A)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:A,acceptedExisting:!0}}}let g=`${R(e)}/projects/${o}/tasks/${s}/classifications`,f=await y(g,{method:"POST",body:{},cookie:e.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!f.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: start failed (HTTP ${f.statusCode}) \u2014 raw body: ${f.rawBody}`),{statusCode:f.statusCode||500,body:{error:"Failed to start classification.",details:f.body??f.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: started (${f.body.status??"unknown"})`);let h=f.body.id;if(!t.wait)return{statusCode:200,body:{jobId:h,status:f.body.status}};let{finalStatus:C,timedOut:k}=await Bt(e,o,s,i,c),v=await Se(e,i,h),N={accepted:!1};return!k&&C==="COMPLETED"&&(N=await Te(e,i,o,s,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: final status ${C??"unknown"}${k?" (timed out waiting)":""}, save ${JSON.stringify(N)}`),{statusCode:200,body:{jobId:h,finalStatus:C,timedOut:k,details:v,save:N}}}var dr=["SAVED","STALE","SAVE_FAILED"],lr=120;async function Te(e,t,r,n,o){let s=`${w(e)}/${t}/classifications/${o}`,i=await y(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(lr*1e3/Kt),{value:c,timedOut:d}=await or(async()=>{let u=(await y(s,{cookie:e.cookie})).body?.status;return{done:!!u&&dr.includes(u),value:u}},Kt,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 qt(e,t,r){let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,a=(await O(e,o,s))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&Re.includes(a)}}}async function Ft(e,t,r,n,o){let s,{value:i,timedOut:a}=await Mt(async()=>{let d=(await O(e,t,r))?.latestValidationStatus;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||Re.includes(d)),value:d}},ar,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function Jt(e,t,r){let n=await x(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await Ut(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??cr,l=(await O(e,o,s))?.latestValidationStatus;if(l&&Re.includes(l)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:C,timedOut:k}=await Ft(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: attached run final status ${C??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:C,timedOut:k,attachedToExisting:!0}}}let u=`${R(e)}/projects/${o}/tasks/${s}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let g=await y(u,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(g.statusCode<200||g.statusCode>=300)return{statusCode:g.statusCode,body:{error:"Failed to start validation.",details:g.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:f,timedOut:h}=await Ft(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: final status ${f??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:f,timedOut:h}}}async function Gt(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${R(e)}/projects${r}`;return(await y(n,{cookie:e.cookie})).body??[]}async function Ht(e,t){let r=`${R(e)}/projects/${t}/tasks`;return(await y(r,{cookie:e.cookie})).body??[]}async function Wt(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${R(e)}/projects/my-tasks${r}`;return(await y(n,{cookie:e.cookie})).body??[]}async function Yt(e,t){let r=`${R(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 y(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 ur=["FORWARD","DIVERGED"];async function pr(e,t){if(!t)return!1;let r=`${w(e)}/branches/${encodeURIComponent(t)}`,n=await y(r,{cookie:e.cookie});return ur.includes(n.body?.state??"")}var mr=["Promoted","Completed"];async function zt(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await y(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&&mr.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 pr(e,n.body.branchPath),i=await y(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 Xt(e,t){let r=`${R(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await y(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var fr="IN_PROGRESS";async function Qt(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await y(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 y(r,{method:"PUT",body:{status:fr},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 Zt(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 Ae(e){return JSON.stringify([e])}function eo(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 Ee(e,t={},r=""){let n=Object.entries(t).map(([o,s])=>`${o}:${s}`);return[e,...n,"",r].join(`
|
|
3
|
-
`)+"\0"}function
|
|
2
|
+
"use strict";var En=Object.create;var Z=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var Nn=Object.getOwnPropertyNames;var Pn=Object.getPrototypeOf,Dn=Object.prototype.hasOwnProperty;var On=(e,t)=>{for(var r in t)Z(e,r,{get:t[r],enumerable:!0})},We=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nn(t))!Dn.call(e,o)&&o!==r&&Z(e,o,{get:()=>t[o],enumerable:!(n=jn(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?En(Pn(e)):{},We(t||!e||!e.__esModule?Z(r,"default",{value:e,enumerable:!0}):r,e)),Ln=e=>We(Z({},"__esModule",{value:!0}),e);var Kr={};On(Kr,{COMMANDS:()=>He,main:()=>An,parsePositionals:()=>Rn});module.exports=Ln(Kr);var F={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"}},Kn={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},ee=Object.keys(F);function Ye(e){return Kn[e.trim().toLowerCase()]??null}var H="uat",Fr=F.uat.imsEndpoint,Mr=F.uat.terminologyServerEndpoint,Ur=F.uat.authoringServicesEndpoint;var Bn=v(require("http")),Fn=v(require("https"));function y(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(C){c(C);return}let l=d.protocol==="https:"?Fn:Bn,u=o!==void 0?JSON.stringify(o):void 0,g={accept:"application/json",...s};if(u!==void 0&&(g["content-type"]="application/json",g["content-length"]=String(Buffer.byteLength(u))),n){let C=n.replace(/[^\x20-\x7e\t]/g,"");C&&(g.cookie=C)}let f=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:g},C=>{let h="";C.on("data",k=>{h+=k}),C.on("end",()=>{let k=C.statusCode??0,N=(C.headers["content-type"]??"").includes("application/json"),j=null,A=!1;if(h)try{j=JSON.parse(h)}catch{A=!N}a({statusCode:k,body:j,rawBody:h,sessionExpired:A})})});f.on("error",c),f.setTimeout(i,()=>{f.destroy(new Error(`Request to ${e} timed out after ${i}ms`))}),u!==void 0&&f.write(u),f.end()})}var K="900000000000509007",W="900000000000508004";var ze={[K]:"en-us",[W]:"en-gb"},Xe={[K]:"true",[W]:"true"},Mn={},Un={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:ze,dialectDefaults:Xe,readOnlyDialects:Mn,defaultLanguage:"en"};function Qe(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Un;let t={[K]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];t[String(e[c])]=l,o.length===0&&o.push(l)}}let s=e.requiredLanguageRefsets;if(Array.isArray(s))for(let c of s){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[C,h]of Object.entries(c))C.length===2&&(d=C,l=String(h));if(!d||!l)continue;let u=c.dialectName;t[l]=typeof u=="string"?u:d;let g=c.default;g==="true"&&!o.includes(d)&&o.push(d),g!=null&&(r[l]=String(g));let f=c.readOnly;f!=null&&(n[l]=String(f))}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?ze:t,dialectDefaults:a?Xe:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function Ce(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 Ze(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[K]:"PREFERRED"}:Ce(e,"PREFERRED",t,"en")}var _n="900000000000207008";function et(e){return e.replace(/\/$/,"")}function w(e){return et(e.terminologyServerEndpoint)}function R(e){return et(e.authoringServicesEndpoint)}function tt(e){return`${new URL(R(e)).origin}/authoring-traceability-service`}function M(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function I(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 Vn(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 U(e,t){let r=w(e),n=await y(`${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 y(`${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 Vn(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await y(n,{cookie:e.cookie})).body?.branchPath??null}async function ot(e,t,r){let n=r?.get(t);if(n)return n;let o=`${R(e)}/projects/${t}`,i=(await y(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,i),i}async function Y(e,t,r){let n=await ot(e,t,r),o=n.multipleModuleEditingDisabled,s=!o||o==="false";return n.expectedExtensionModules?.length&&s?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:_n}async function te(e,t,r){let n=await ot(e,t,r);return Qe(n)}async function he(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await y(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 nt=v(require("crypto"));var qn="116680003";function oe(e,t,r,n,o="PREFERRED",s=!1){let i=e==="FSN"?Ze(n,s):Ce(n,o,s,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:i}}async function rt(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await I(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:s,taskKey:i,branchPath:a}=o,c=M(a),d=t.moduleId||await Y(e,s,n),l=await te(e,s,n),u=t.preferredTerm||t.fsn,g=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,f={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[oe("FSN",g,d,l,"PREFERRED",!0),oe("SYNONYM",u,d,l,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:nt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:qn},target:{conceptId:t.parentConceptId}}]}]},C=`${w(e)}/browser/${c}/${s}/${i}/concepts/?validate=true`,h=await y(C,{method:"POST",body:f,cookie:e.cookie});if(h.sessionExpired){let N="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: SESSION EXPIRED`),{statusCode:401,body:{error:N}}}let k=h.body,T=k&&"conceptId"in k?k.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: ${h.statusCode<300?"OK":"FAILED ("+h.statusCode+")"} \u2014 ${g}`+(T?` \u2192 ${T}`:"")),typeof T=="string"&&e.onValidationResults?.(T,k?.validationResults),{statusCode:h.statusCode,body:h.body}}async function ne(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${w(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await y(o,{cookie:e.cookie});return s.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:s.statusCode,body:s.body}}async function st(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await I(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=`${w(e)}/${n.branchPath}/concepts/search`,i=await y(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 it(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=w(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await y(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:`Concept ${t.conceptId} has effectiveTime ${String(i.body.effectiveTime)} set (already versioned) \u2014 cannot delete.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await y(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 at(e){return typeof e=="object"&&e!==null}function Jn(e){let t=e.type,r=e.target,n=at(t)?t.conceptId:void 0,o=at(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function Gn(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 ct(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(Jn).filter(d=>d!=null);Gn(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 mt=v(require("crypto"));var Hn=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],Wn=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],Yn=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],zn=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Xn=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],xe=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function ft(e){return xe.includes(e)}function z(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function re(e){return typeof e=="object"&&e!==null}function dt(e){return re(e)?z(e,zn):e}function gt(e){if(!re(e))return e;let t=z(e,Yn);return"type"in t&&(t.type=dt(t.type)),"target"in t&&(t.target=dt(t.target)),t}function Qn(e){return re(e)?z(e,Wn):e}function lt(e){if(!re(e))return e;let t=z(e,Xn);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(gt)),t}function be(e){let t=z(e,Hn);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(Qn)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(gt)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(lt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(lt)),t}async function E(e,t,r,n){let o=w(e),s=`${o}/browser/${t.branchPath}/concepts/${r}`,i=await y(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 ${r}.`,details:i.body}};let a=i.body,c=n(a);if(c)return c;let d=M(t.branchPath),l=`${o}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,u=await y(l,{method:"PUT",body:be(a),cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${u.statusCode<300?"OK":"FAILED ("+u.statusCode+")"} \u2014 ${r}`);let g=u.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:u.statusCode,body:u.body}}var ut=["PREFERRED","ACCEPTABLE"];async function yt(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&&!ut.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${ut.join(", ")}.`}};let o=await I(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await Y(e,o.projectKey,n),i=await te(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return E(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(oe(t.type,a,s,i,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,null})}async function kt(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return E(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 Ct(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 I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return E(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 ht(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>(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 It(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&&!ft(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${xe.join(", ")}.`}};let n=await I(e,t,r);return n.ok?E(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 xt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!ft(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${xe.join(", ")}.`}};let n=await I(e,t,r);return n.ok?E(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 Ie=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function pt(e){return Ie.includes(e)}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.`}}:e.us&&!pt(e.us)?{statusCode:400,body:{error:`us must be one of: ${Ie.join(", ")}.`}}:e.gb&&!pt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${Ie.join(", ")}.`}}:null:{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function St(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[K]:o[K]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[W]:o[W]=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 vt(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 I(e,t,r);return s.ok?E(e,s,t.conceptId,i=>{let a=Array.isArray(i.descriptions)?i.descriptions:[];return St(a,t.conceptId,n)}):{statusCode:400,body:{error:s.error}}}async function Tt(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 I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[];for(let i of t.entries){let a=St(s,t.conceptId,i);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function wt(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await I(e,t,r);return n.ok?E(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:`Description ${t.descriptionId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.descriptions=s,null)}):{statusCode:400,body:{error:n.error}}}async function Rt(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 I(e,t,r);return n.ok?E(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 $t(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 I(e,t,r);return n.ok?E(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 At(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 I(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await Y(e,o.projectKey,n);return E(e,o,t.conceptId,i=>{let a=Array.isArray(i.gciAxioms)?i.gciAxioms:[];return a.push({axiomId:mt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),i.gciAxioms=a,null})}async function Et(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await I(e,t,r);return n.ok?E(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.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.classAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function jt(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 I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.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(l=>l.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 Nt(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 I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.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=ct(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let d=c.relationships.find(l=>l.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(l=>(typeof l.groupId=="number"?l.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function Pt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await I(e,t,r);return n.ok?E(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:`GCI axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.gciAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}function Zn(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 se(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=w(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await y(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=M(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await y(c,{method:"POST",body:be(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 l=Array.isArray(d.body)?Zn(d.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:l,hasErrors:l.some(u=>u.severity==="ERROR"),hasWarnings:l.some(u=>u.severity==="WARNING")}}}var Dt=200;async function er(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${w(e)}/browser/${t}/concepts/bulk-load`,s=!0;for(let i=0;i<r.length;i+=Dt){let a=r.slice(i,i+Dt),c=await y(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 _(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${tt(e)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,s=await y(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=(h,k,T,N)=>{let j=h.get(k);j?(N.forEach(A=>A&&j.componentSubTypes.add(A)),j.lastUpdatedTime=T):h.set(k,{conceptId:k,lastUpdatedTime:T,componentSubTypes:new Set(N.filter(A=>!!A))})};for(let h of s.body?.content??[])if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let k of h.conceptChanges??[]){let T=String(k.conceptId),N=k.componentChanges??[],j=N.map(G=>G.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,T,h.commitDate,j);continue}let A=N.some(G=>G.componentSubType!=="INFERRED_RELATIONSHIP");c(A?i:a,T,h.commitDate,j)}for(let h of i.keys())a.delete(h);let d=[...new Set([...i.keys(),...a.keys()])],{terms:l,resolved:u}=await er(e,n.branchPath,d),g=h=>[...h.values()].sort((k,T)=>(T.lastUpdatedTime??"").localeCompare(k.lastUpdatedTime??"")).map(k=>{let T=u&&!l.has(k.conceptId);return{conceptId:k.conceptId,fsn:l.get(k.conceptId)?.fsn,pt:l.get(k.conceptId)?.pt,...T?{deleted:!0}:{},lastUpdatedTime:k.lastUpdatedTime,changedComponentTypes:[...k.componentSubTypes]}}),f=g(i),C=g(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:f.length,conceptsDeleted:f.filter(h=>h.deleted).length,conceptsClassified:C.length}}:{},concepts:f,conceptsClassified:C}}}async function Ot(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await _(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=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await se(e,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l.error??`HTTP ${d.statusCode}`});continue}let u=l.validationResults??[];i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:u.length===0?"clean":"issues",validationResults:u.length?u:void 0,hasErrors:l.hasErrors})}let 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 Lt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await _(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=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await ne(e,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l?.error??`HTTP ${d.statusCode}`});continue}i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"fetched",concept:d.body})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:i}}}var Se=new Set;function Kt(e){if(!(!e||typeof e!="object"))for(let t of Se)t(e)}function tr(e){return Se.add(e),()=>Se.delete(e)}function or(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 ie(e){let t=()=>{};return{promise:new Promise(n=>{t=tr(o=>{or(o,e)&&(t(),n(o))})}),cancel:t}}async function O(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await y(n,{cookie:e.cookie})).body??null}var Re=["RUNNING","BUILDING","SCHEDULED","QUEUED"],$e=["QUEUED","SCHEDULED","RUNNING"],nr=["Promoted","Completed"],Bt=5e3;function we(e){return new Promise(t=>setTimeout(t,e))}async function rr(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 we(t)}}function sr(){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 ir=sr(),ar=180;function cr(){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 dr=cr(),lr=900;async function Ut(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?ie(n):void 0,l=await Promise.race(d?[we(c).then(()=>{}),d.promise]:[we(c).then(()=>{})]);if(d?.cancel(),l){let f=l.event;o?.(`[${new Date().toISOString()}] woken by notification${f?`: ${f}`:""}`)}let{done:u,value:g}=await e();if(u)return{value:g,timedOut:!1};if(Date.now()-i>=s)return{value:g,timedOut:!0};a++}}async function _t(e,t,r){let n=await O(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&nr.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${R(e)}/projects/${t}/tasks/${r}`;await y(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function Ae(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await y(n,{method:"POST",body:{},cookie:e.cookie}),(await O(e,t,r))?.latestClassificationJson}async function Ft(e,t,r,n,o){let s,{value:i,timedOut:a}=await Ut(async()=>{let d=(await Ae(e,t,r))?.status;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||Re.includes(d)),value:d}},ir,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function ve(e,t,r){let n=`${w(e)}/${t}/classifications`,o=await y(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 Vt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,i=await Ae(e,o,s);return i?{statusCode:200,body:{hasClassification:!0,jobId:i.id,status:i.status,running:Re.includes(i.status),latestClassificationJson:i}}:{statusCode:200,body:{hasClassification:!1}}}async function qt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await _t(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??ar,d=await Ae(e,o,s),l=d?.status,u=d?.id;if(u&&l&&Re.includes(l)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:A}=await Ft(e,o,s,i,c),G=await ve(e,i,u),ke={accepted:!1};return!A&&j==="COMPLETED"&&(ke=await Te(e,i,o,s,u)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: attached job ${u} final status ${j??"unknown"}${A?" (timed out waiting)":""}, save ${JSON.stringify(ke)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:A,details:G,save:ke,attachedToExisting:!0}}}if(u&&l==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await ve(e,i,u),A=await Te(e,i,o,s,u);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: accepted existing job ${u}, save ${JSON.stringify(A)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:A,acceptedExisting:!0}}}let g=`${R(e)}/projects/${o}/tasks/${s}/classifications`,f=await y(g,{method:"POST",body:{},cookie:e.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!f.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: start failed (HTTP ${f.statusCode}) \u2014 raw body: ${f.rawBody}`),{statusCode:f.statusCode||500,body:{error:"Failed to start classification.",details:f.body??f.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: started (${f.body.status??"unknown"})`);let C=f.body.id;if(!t.wait)return{statusCode:200,body:{jobId:C,status:f.body.status}};let{finalStatus:h,timedOut:k}=await Ft(e,o,s,i,c),T=await ve(e,i,C),N={accepted:!1};return!k&&h==="COMPLETED"&&(N=await Te(e,i,o,s,C)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: final status ${h??"unknown"}${k?" (timed out waiting)":""}, save ${JSON.stringify(N)}`),{statusCode:200,body:{jobId:C,finalStatus:h,timedOut:k,details:T,save:N}}}var ur=["SAVED","STALE","SAVE_FAILED"],pr=120;async function Te(e,t,r,n,o){let s=`${w(e)}/${t}/classifications/${o}`,i=await y(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(pr*1e3/Bt),{value:c,timedOut:d}=await rr(async()=>{let u=(await y(s,{cookie:e.cookie})).body?.status;return{done:!!u&&ur.includes(u),value:u}},Bt,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 Jt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,a=(await O(e,o,s))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&$e.includes(a)}}}async function Mt(e,t,r,n,o){let s,{value:i,timedOut:a}=await Ut(async()=>{let d=(await O(e,t,r))?.latestValidationStatus;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||$e.includes(d)),value:d}},dr,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function Gt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await _t(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??lr,l=(await O(e,o,s))?.latestValidationStatus;if(l&&$e.includes(l)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:h,timedOut:k}=await Mt(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: attached run final status ${h??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:h,timedOut:k,attachedToExisting:!0}}}let u=`${R(e)}/projects/${o}/tasks/${s}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let g=await y(u,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(g.statusCode<200||g.statusCode>=300)return{statusCode:g.statusCode,body:{error:"Failed to start validation.",details:g.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:f,timedOut:C}=await Mt(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: final status ${f??"unknown"}${C?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:f,timedOut:C}}}async function Ht(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${R(e)}/projects${r}`;return(await y(n,{cookie:e.cookie})).body??[]}async function Wt(e,t){let r=`${R(e)}/projects/${t}/tasks`;return(await y(r,{cookie:e.cookie})).body??[]}async function Yt(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${R(e)}/projects/my-tasks${r}`;return(await y(n,{cookie:e.cookie})).body??[]}async function zt(e,t){let r=`${R(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 y(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 mr=["FORWARD","DIVERGED"];async function fr(e,t){if(!t)return!1;let r=`${w(e)}/branches/${encodeURIComponent(t)}`,n=await y(r,{cookie:e.cookie});return mr.includes(n.body?.state??"")}var gr=["Promoted","Completed"];async function Xt(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await y(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&&gr.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 fr(e,n.body.branchPath),i=await y(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 Qt(e,t){let r=`${R(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await y(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var yr="IN_PROGRESS";async function Zt(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await y(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 y(r,{method:"PUT",body:{status:yr},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 eo(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 Ee(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 je(e,t={},r=""){let n=Object.entries(t).map(([o,s])=>`${o}:${s}`);return[e,...n,"",r].join(`
|
|
3
|
+
`)+"\0"}function oo(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
|
|
4
4
|
|
|
5
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
|
|
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 ro=v(require("ws"));var no=[1e3,2e3,5e3,1e4,3e4];function so(e,t={}){let r=t.createSocket??((l,u)=>new ro.default(l,u)),n=!1,o,s=0,i,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let l=no[Math.min(s,no.length-1)];s+=1,i=setTimeout(d,l)};function d(){if(n)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${to()}`,g=r(u,a?{headers:{cookie:a}}:{});o=g,g.on("message",f=>{let C=eo(f.toString());if(C.type==="open"){g.send(Ee(je("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(C.type==="close"){g.close();return}if(C.type==="message")for(let h of C.messages){let k=oo(h);if(k){if(k.command==="CONNECTED"){s=0;let T=`/topic/user/${e.login}/notifications`;g.send(Ee(je("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:T})));continue}if(k.command==="MESSAGE"){try{e.onNotification(JSON.parse(k.body))}catch(T){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",T)}continue}k.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",k.headers,k.body)}}}),g.on("unexpected-response",(f,C)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${C.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),g.terminate()}),g.on("error",f=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",f.message)}),g.on("close",c)}return d(),{stop(){n=!0,i&&clearTimeout(i),o?.removeAllListeners(),o?.close()}}}function io(e,t,r={}){let n=r.startRelay??so,o=r.onNotification??Kt,s=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>s.stop()}}var kr=60;async function ao(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=t.timeoutSeconds??kr,c=ie({entityType:t.entityType,projectKey:o,taskKey:s,branchPath:i}),d,l=new Promise(f=>{d=setTimeout(()=>f({kind:"timeout"}),a*1e3)}),u=c.promise.then(f=>({kind:"notification",payload:f})),g=await Promise.race([u,l]);return c.cancel(),clearTimeout(d),g.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:g.payload}}}function b(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 xo=v(require("http")),bo=require("child_process");var ce=v(require("fs")),co=v(require("os")),lo=v(require("path"));function Cr(){return lo.join(co.homedir(),"Library","Application Support","Google","Chrome","Local State")}function hr(){let e=Cr();if(!ce.existsSync(e))return[];let t;try{t=JSON.parse(ce.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 ae=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 de(e,t=hr()){if(!e){let n=t.find(o=>o.directoryName==="Default");if(n)return n;if(t.length)return t[0];throw new ae("Default",t)}let r=t.find(n=>n.directoryName===e||n.displayName.toLowerCase()===e.toLowerCase());if(!r)throw new ae(e,t);return r}var Co=require("child_process"),ho=require("util"),De=v(require("fs")),pe=v(require("os")),Oe=v(require("path"));var uo=require("child_process"),po=require("util"),le=v(require("crypto")),B=v(require("fs")),Ir=(0,po.promisify)(uo.exec);function Ne(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}async function mo(){let{stdout:e}=await Ir('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return e.trim()}function fo(e){return le.pbkdf2Sync(e,"saltysalt",1003,16,"sha1")}function go(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=le.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&&Ne(a)&&!Ne(i)&&(c=a),Ne(c)?c.toString("utf8"):null}function yo(e,t){B.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;B.existsSync(n)&&B.copyFileSync(n,t+r)}}function ko(e){for(let t of[e,e+"-wal",e+"-shm"])try{B.unlinkSync(t)}catch{}}var xr=(0,ho.promisify)(Co.exec),ue=class extends Error{},Pe=class extends Error{};function br(e){return Oe.join(pe.homedir(),"Library","Application Support","Google","Chrome",e,"Cookies")}function Sr(){return De.existsSync("/Applications/Google Chrome.app")}function vr(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 Le(e,t,r){let n=br(e);if(!De.existsSync(n))return null;let o=Oe.join(pe.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);yo(n,o);try{let s;try{s=await mo()}catch{return null}let i=fo(s),a=u=>`'${u.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${vr(t).map(a).join(", ")}) AND name = ${a(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:l}=await xr(`sqlite3 "${o}" "${d}"`);return go(l.trim(),i)}catch{return null}finally{ko(o)}}function Tr(e){return new Promise(t=>setTimeout(t,e))}async function Io(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??Sr;if(r!=="darwin")throw new ue(`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 ue("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??Le,s=t.sleep??Tr,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 l=await o(e.profileDirectory,e.host,e.cookieName);if(l&&l!==c)return l;await s(i)}throw new Pe(`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 Ke(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}function wr(e,t){let r=n=>`'${n.replace(/'/g,"'\\''")}'`;(0,bo.exec)(`open -a ${r("Google Chrome")} ${r(e)} --args --profile-directory=${r(t)}`)}function Rr(){return`<!DOCTYPE html>
|
|
7
7
|
<html>
|
|
8
8
|
<head>
|
|
9
9
|
<meta charset="utf-8">
|
|
@@ -14,19 +14,19 @@
|
|
|
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
|
|
18
|
-
Expected one of: ${Z.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=F[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||Le(i),d=t===G&&!e.environment?`${t}, default`:t,l=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:s,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(h=>({...h,source:d})),u=await wr(n,i,c,e.chromeProfile);if(u){pe({cookie:u.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:u.account,currentTask:null}),console.log(`${wo(u.account)} (reused an existing Chrome session \u2014 no browser opened.)`),Ro(l);return}console.log(`Opening Chrome to sign in to ${n} ...`);let g=await bo({imsEndpoint:n,host:i,cookieName:c,chromeProfile:e.chromeProfile});if(!g){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let f=await he(n,g.cookie).catch(()=>null);pe({cookie:g.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:f,currentTask:null}),console.log(wo(f)),Ro(l)}async function Ao(){vo(),console.log("Signed out.")}function p(){let e=Fe();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 Eo(e){return e.projectKey??e.key??"?"}async function jo(e){let t=p(),r=m(t),n=await Gt(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=>Eo(s).length))+1;for(let s of n){let i=s.title??"";console.log(`${Eo(s).padEnd(o)}${i?`"${i}"`:""}`)}}function me(e){return e.taskKey??e.key??"?"}function No(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Rr(e){return e.projectKey||me(e).split("-")[0]||"?"}function Me(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 Ue(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 Po(e){let t=p(),r=m(t),n=e.mine||!e.project,o=n?await Wt(r):await Ht(r,e.project);if(n&&e.project){let l=e.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===l||me(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===l)}let s=Me(o,Rr),i=Me(o,No),a=Me(o,l=>l.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&&Ue("By project",s),!n&&i.length>1&&Ue("By assignee",i),a.length>1&&Ue("By status",a);return}let d=Math.max(...o.map(l=>me(l).length))+1;for(let l of o){let u=l.summary??l.title??"",g=l.status?` status=${l.status}`:"",f=n?"":` [${No(l)}]`;console.log(`${me(l).padEnd(d)}${u?`"${u}"`:""}${g}${f}`)}}async function Do(e){let t=p(),r=m(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,s=await Yt(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 U(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}L({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function Oo(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,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 zt(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&&(L(null),console.log(" cleared the current task selection."))}async function Lo(e){let t=p(),r=m(t);if(!e.task){let s=await Xt(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 Qt(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 U(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||(L({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Ko(e){let t=p(),r=m(t),n=await O(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 U(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}L({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 Bo(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 Fo(e){let t=p(),r=m(t),n=await nt(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}`),b(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 Mo(e){let t=p(),r=m(t),n=await st(r,{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},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to search concepts (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function Uo(e){let t=p(),r=m(t),n=await rt(r,{conceptId:e.id,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 _o(e){let t=p(),r=m(t),n=await ne(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}b(s),o.hasErrors&&(process.exitCode=1)}async function Vo(e){let t=p(),r=m(t),n=await re(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 qo(e){let t=p(),r=m(t),n=await Ot(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}`),b(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 Jo(e){let t=p(),r=m(t),n=await yt(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}`),b(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 Go(e){let t=p(),r=m(t),n=await kt(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}`),b(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 Ho(e){let t=p(),r=m(t),n=await jt(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}`),b(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 Wo(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 Nt(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}`),b(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 Yo(e){let t=p(),r=m(t),n=await xt(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}`),b(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 zo(e){let t=p(),r=m(t),n=await It(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}`),b(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 Xo(e){let t=p(),r=m(t);if(e.entries){let i;try{i=JSON.parse(e.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.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 vt(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}`),b(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 Tt(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(", ")})`),b(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 Qo(e){let t=p(),r=m(t),n=await Ct(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}`),b(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 Zo(e){let t=p(),r=m(t),n=await ht(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}`),b(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 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}let r=p(),n=m(r),o=await Rt(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}`),b(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 tn(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 $t(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}`),b(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 on(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 At(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})`:""}`),b(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 nn(e){let t=p(),r=m(t),n=await it(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 rn(e){let t=p(),r=m(t),n=await wt(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 sn(e){let t=p(),r=m(t),n=await Et(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 an(e){let t=p(),r=m(t),n=await Pt(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}function _(e){let t=e.account?.login;return t?so(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 cn(e){let t=p(),r=m(t),n=_(t),o;try{o=await Vt(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 dn(e){let t=p(),r=m(t),n=await _t(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 ln(e){let t=p(),r=m(t),n=_(t),o;try{o=await Jt(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 un(e){let t=p(),r=m(t),n=await qt(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 pn(e){let t=p(),r=m(t),n=_(t);try{let o=await io(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 qe=T(require("os")),V=T(require("path"));var S=T(require("fs")),_e=T(require("os")),I=T(require("path")),$="authoring-cli",D=["claude","codex"];function fe(e){let t=[I.resolve(e,"..","skills",$),I.resolve(e,"..","..","skills",$)];for(let r of t)if(S.existsSync(I.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function $r(e){let t=[];return S.existsSync(I.join(e,".claude"))&&t.push("claude"),S.existsSync(I.join(e,".codex"))&&t.push("codex"),t}function z(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=$r(t);return r.length?r:["claude"]}var fn="# authoring-cli \u2014 SNOMED CT authoring guidance";function Ar(e){let t=I.join(e,"SKILL.md"),r=I.join(e,"references","batch-authoring.md");return[fn,"",`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
|
|
20
|
-
`)!==
|
|
21
|
-
`)?!1:r.every(n=>S.readFileSync(
|
|
17
|
+
</html>`}function So(e,t={}){let r=e.cookieName??Ke(e.host),n=t.openChrome??wr,o=t.resolveProfile??de,s=t.captureCookie??Io,i=e.callbackTimeoutMs??12e4,a=o(e.chromeProfile);return new Promise((c,d)=>{let l=!1,u=f=>{l||(l=!0,g.close(),f())},g=xo.createServer((f,C)=>{if((f.url||"/").split("?")[0]==="/callback"){C.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),C.end(Rr()),(async()=>{try{let k=await s({profileDirectory:a.directoryName,host:e.host,cookieName:r});u(()=>c({cookie:`${r}=${k}`}))}catch(k){u(()=>d(k))}})();return}C.writeHead(404),C.end()});g.listen(0,"127.0.0.1",()=>{let C=`http://localhost:${g.address().port}/callback`,h=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(C)}`;n(h,a.directoryName)}),g.on("error",f=>u(()=>d(f))),setTimeout(()=>u(()=>c(null)),i)})}var P=v(require("fs")),vo=v(require("os")),Be=v(require("path"));function To(){return Be.join(vo.homedir(),".authoring-cli")}function Fe(){return Be.join(To(),"session.json")}function Me(){let e=Fe();if(!P.existsSync(e))return null;let t=P.readFileSync(e,"utf8");return JSON.parse(t)}function me(e){P.mkdirSync(To(),{recursive:!0,mode:448});let t={...e,updatedAt:new Date().toISOString()};P.writeFileSync(Fe(),JSON.stringify(t,null,2),{mode:384})}function wo(){let e=Fe();P.existsSync(e)&&P.unlinkSync(e)}function L(e){let t=Me();if(!t)throw new Error('Not signed in \u2014 run "login" first.');me({...t,currentTask:e})}async function $r(e,t,r,n){let o;try{o=de(n).directoryName}catch{return null}let s=await Le(o,t,r).catch(()=>null);if(!s)return null;let i=`${r}=${s}`,a=await he(e,i).catch(()=>null);return a?{cookie:i,account:a}:null}function Ro(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 $o(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 Ao(e){let t=e.environment?Ye(e.environment):H;if(!t){console.error(`Unknown environment: ${e.environment}
|
|
18
|
+
Expected one of: ${ee.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=F[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||Ke(i),d=t===H&&!e.environment?`${t}, default`:t,l=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:s,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(C=>({...C,source:d})),u=await $r(n,i,c,e.chromeProfile);if(u){me({cookie:u.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:u.account,currentTask:null}),console.log(`${Ro(u.account)} (reused an existing Chrome session \u2014 no browser opened.)`),$o(l);return}console.log(`Opening Chrome to sign in to ${n} ...`);let g=await So({imsEndpoint:n,host:i,cookieName:c,chromeProfile:e.chromeProfile});if(!g){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let f=await he(n,g.cookie).catch(()=>null);me({cookie:g.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:f,currentTask:null}),console.log(Ro(f)),$o(l)}async function Eo(){wo(),console.log("Signed out.")}function p(){let e=Me();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 jo(e){return e.projectKey??e.key??"?"}async function No(e){let t=p(),r=m(t),n=await Ht(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=>jo(s).length))+1;for(let s of n){let i=s.title??"";console.log(`${jo(s).padEnd(o)}${i?`"${i}"`:""}`)}}function fe(e){return e.taskKey??e.key??"?"}function Po(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Ar(e){return e.projectKey||fe(e).split("-")[0]||"?"}function Ue(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 _e(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 Do(e){let t=p(),r=m(t),n=e.mine||!e.project,o=n?await Yt(r):await Wt(r,e.project);if(n&&e.project){let l=e.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===l||fe(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===l)}let s=Ue(o,Ar),i=Ue(o,Po),a=Ue(o,l=>l.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&&_e("By project",s),!n&&i.length>1&&_e("By assignee",i),a.length>1&&_e("By status",a);return}let d=Math.max(...o.map(l=>fe(l).length))+1;for(let l of o){let u=l.summary??l.title??"",g=l.status?` status=${l.status}`:"",f=n?"":` [${Po(l)}]`;console.log(`${fe(l).padEnd(d)}${u?`"${u}"`:""}${g}${f}`)}}async function Oo(e){let t=p(),r=m(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,s=await zt(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 U(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}L({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function Lo(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,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 Xt(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&&(L(null),console.log(" cleared the current task selection."))}async function Ko(e){let t=p(),r=m(t);if(!e.task){let s=await Qt(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 Zt(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 U(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||(L({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Bo(e){let t=p(),r=m(t),n=await O(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 U(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}L({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 Fo(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 Mo(e){let t=p(),r=m(t),n=await rt(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}`),b(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 Uo(e){let t=p(),r=m(t),n=await st(r,{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},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to search concepts (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function _o(e){let t=p(),r=m(t),n=await ne(r,{conceptId:e.id,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 Vo(e){let t=p(),r=m(t),n=await se(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}b(s),o.hasErrors&&(process.exitCode=1)}async function qo(e){let t=p(),r=m(t),n=await _(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 Jo(e){let t=p(),r=m(t),n=await Ot(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}`),b(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 Go(e){let t=p(),r=m(t),n=await Lt(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 Ho(e){let t=p(),r=m(t),n=await yt(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}`),b(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 Wo(e){let t=p(),r=m(t),n=await kt(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}`),b(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 Yo(e){let t=p(),r=m(t),n=await jt(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}`),b(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 zo(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 Nt(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}`),b(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 Xo(e){let t=p(),r=m(t),n=await It(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}`),b(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 Qo(e){let t=p(),r=m(t),n=await xt(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}`),b(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 Zo(e){let t=p(),r=m(t);if(e.entries){let i;try{i=JSON.parse(e.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.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 Tt(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}`),b(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 vt(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(", ")})`),b(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 en(e){let t=p(),r=m(t),n=await ht(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}`),b(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 tn(e){let t=p(),r=m(t),n=await Ct(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}`),b(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 on(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 Rt(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}`),b(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 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}let r=p(),n=m(r),o=await $t(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}`),b(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 rn(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 At(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})`:""}`),b(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 sn(e){let t=p(),r=m(t),n=await it(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 an(e){let t=p(),r=m(t),n=await wt(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 cn(e){let t=p(),r=m(t),n=await Et(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 dn(e){let t=p(),r=m(t),n=await Pt(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}function V(e){let t=e.account?.login;return t?io(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 ln(e){let t=p(),r=m(t),n=V(t),o;try{o=await qt(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 un(e){let t=p(),r=m(t),n=await Vt(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 pn(e){let t=p(),r=m(t),n=V(t),o;try{o=await Gt(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 mn(e){let t=p(),r=m(t),n=await Jt(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 fn(e){let t=p(),r=m(t),n=V(t);try{let o=await ao(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 Je=v(require("os")),q=v(require("path"));var S=v(require("fs")),Ve=v(require("os")),x=v(require("path")),$="authoring-cli",D=["claude","codex"];function ge(e){let t=[x.resolve(e,"..","skills",$),x.resolve(e,"..","..","skills",$)];for(let r of t)if(S.existsSync(x.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function Er(e){let t=[];return S.existsSync(x.join(e,".claude"))&&t.push("claude"),S.existsSync(x.join(e,".codex"))&&t.push("codex"),t}function X(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=Er(t);return r.length?r:["claude"]}var yn="# authoring-cli \u2014 SNOMED CT authoring guidance";function jr(e){let t=x.join(e,"SKILL.md"),r=x.join(e,"references","batch-authoring.md");return[yn,"",`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 ye(e){try{return x.resolve(x.dirname(e),S.readlinkSync(e))}catch{return null}}function Q(e){try{return S.lstatSync(e)}catch{return null}}function qe(e){let t=ye(e);return t?S.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:Q(e)?.isDirectory()?"an existing directory":"an existing file"}function kn(e){let t=ye(e);return t!==null&&x.basename(t)===$&&x.basename(x.dirname(t))==="skills"}function Cn(e){if(!Q(e)?.isFile())return!1;try{return S.readFileSync(e,"utf8").startsWith(yn)}catch{return!1}}function gn(e){return S.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>x.relative(e,x.join(t.parentPath,t.name))).sort()}function hn(e,t){if(!t||!S.existsSync(t))return!1;try{let r=gn(t);return r.join(`
|
|
20
|
+
`)!==gn(e).join(`
|
|
21
|
+
`)?!1:r.every(n=>S.readFileSync(x.join(e,n)).equals(S.readFileSync(x.join(t,n))))}catch{return!1}}function Nr(e,t,r){let n=e.project?x.join(r,".claude","skills"):x.join(t,".claude","skills"),o=x.join(n,$),s=e.shippedSkillDir,i=e.project&&s.startsWith(r+x.sep)?x.relative(x.dirname(o),s):s,a=Q(o),c=!1;if(a){let d=ye(o);if(d===s&&S.existsSync(d))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:s};if(!(kn(o)||hn(o,s))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:qe(o)};S.rmSync(o,{recursive:!0,force:!0}),c=!0}S.mkdirSync(n,{recursive:!0});try{return S.symlinkSync(i,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:i}}catch(d){let l=d.code;if(l!=="EPERM"&&l!=="EACCES")throw d;return S.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 Pr(e,t){let r=x.join(t,".codex","prompts"),n=x.join(r,`${$}.md`),o=jr(e.shippedSkillDir),s=Q(n),i=!1;if(s){if((s.isFile()?S.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!Cn(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:qe(n)};S.rmSync(n,{recursive:!0,force:!0}),i=!0}return S.mkdirSync(r,{recursive:!0}),S.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:i?"replaced":"installed",kind:"pointer"}}function In(e){let t=e.homeDir??Ve.homedir(),r=e.cwd??process.cwd();return(e.agents??X(void 0,t)).map(o=>o==="claude"?Nr(e,t,r):Pr(e,t))}function xn(e){let t=e.homeDir??Ve.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?x.join(e.project?x.join(r,".claude"):x.join(t,".claude"),"skills",$):x.join(t,".codex","prompts",`${$}.md`);if(!Q(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?kn(o)||hn(o,e.shippedSkillDir):Cn(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${qe(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let i=ye(o)??void 0;return S.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:i}})}function bn(e){let t=Je.homedir();return e===t||e.startsWith(t+q.sep)?q.join("~",q.relative(t,e)):e}function Dr(e){let t=bn(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${bn(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 Sn(e){let t=ge(__dirname),r=X(e.agent,Je.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=In({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 '${$}' for:`:s.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${Dr(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
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
24
|
Restart your agent, then use /${$}.`),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
|
|
26
|
-
Restart your agent to drop /authoring-cli from its command list.`)}function
|
|
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=>
|
|
28
|
-
`)}async function
|
|
25
|
+
Skipped ${i.join(", ")} (no config directory found). Pass --agent ${i.join(",")} to register anyway.`)}var Ge=v(require("os")),J=v(require("path"));function vn(e){let t=Ge.homedir();return e===t||e.startsWith(t+J.sep)?J.join("~",J.relative(t,e)):e}function Or(e){let t=vn(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${vn(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function Tn(e){let t=e.agent?X(e.agent,Ge.homedir()):[...D],r;try{r=ge(__dirname)}catch{r=void 0}let n=xn({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 '${$}' registration for:`:s.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let i of n)console.log(` ${i.agent.padEnd(7)} ${Or(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 Lr(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 Rn(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var He=[{name:"login",usage:`login [${ee.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--chrome-profile <name>] [--cookie-name <name>] (opens Chrome to sign in \u2014 no VS Code required; automatically captures the session, macOS + Chrome only at launch. Environment defaults to ${H}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>Ao({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:()=>Eo()},{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=>Sn({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=>Tn({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=>No({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=>Do({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=>Oo({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=>Lo({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=>Ko({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=>Bo({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=>Fo({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=>Mo({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] [--project <projectKey> --task <taskKey>]",run:e=>Uo({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--project <projectKey> --task <taskKey>]",required:["id"],run:e=>_o({id:e.id,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)",required:["id"],run:e=>Vo({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--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)`,run:e=>qo({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)',run:e=>Jo({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (fetches the full concept representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, for an editorial review against SNOMED CT naming and modelling standards; see skills/authoring-cli/references/review-concepts.md. This is a data-gathering step, not a validation run \u2014 it performs no Snowstorm validation of its own)",run:e=>Go({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=>Ho({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=>Xo({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=>Qo({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=>Zo({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=>Wo({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=>Yo({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=>zo({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>]",required:["id","indicator"],run:e=>en({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=>tn({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=>on({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,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=>rn({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=>nn({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 never versioned)",required:["id"],run:e=>sn({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 never versioned)",required:["id","description-id"],run:e=>an({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","axiom-id"],run:e=>cn({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 never versioned)",required:["id","axiom-id"],run:e=>dn({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=>ln({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=>un({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=>pn({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=>mn({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=>fn({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function $n(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 wn(){return["Usage: authoring-cli <command> [options]","","Commands:",...He.map(e=>` ${$n(e)}`),"",'Run "login" first to sign in \u2014 no VS Code or editor required.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
|
|
28
|
+
`)}async function An(e=process.argv){let[,,t,...r]=e,n=Lr(r),o=Rn(r);if(!t){console.log(wn());return}let s=He.find(a=>a.name===t||a.aliases?.includes(t));if(!s){console.error(`Unknown command: ${t}
|
|
29
29
|
|
|
30
|
-
${
|
|
30
|
+
${wn()}`),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
31
|
|
|
32
|
-
Usage: ${
|
|
32
|
+
Usage: ${$n(s)}`),process.exitCode=1;return}await s.run(n,o)}require.main===module&&An().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,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "authoring-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "CLI for SNOMED CT authoring against authoring-services",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"bin": {
|
|
7
|
-
"authoring-cli": "
|
|
7
|
+
"authoring-cli": "dist/index.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"dist/index.js",
|
|
@@ -432,10 +432,20 @@ Unlike `update-gci-axiom` and `delete-gci-axiom`, **`add-gci-axiom` has no publi
|
|
|
432
432
|
adds a brand-new axiom, so a released concept — or one whose existing axioms are all versioned —
|
|
433
433
|
accepts a new GCI normally. "This concept is published" is a reason you can't *rewrite* its GCI,
|
|
434
434
|
never a reason you can't *add* one. There's also no `--definition-status`: a GCI is a `SubClassOf`
|
|
435
|
-
axiom by construction and has no primitive/fully-defined distinction
|
|
435
|
+
axiom by construction and has no primitive/fully-defined distinction — but the concept receiving it
|
|
436
|
+
still must be, and remain, `PRIMITIVE`; see `references/gci-modeling.md`.
|
|
436
437
|
|
|
437
438
|
Removing a GCI is still whole-axiom only — see the `update-gci-axiom` note under role groups above.
|
|
438
439
|
|
|
440
|
+
**Deciding *whether* and *how* to model with a GCI at all — for any concept type (disorder,
|
|
441
|
+
procedure, observable, ...), not just this command's mechanics — is its own judgment call.** See
|
|
442
|
+
`references/gci-modeling.md` for the formal reasoning behind why a GCI-bearing concept must stay
|
|
443
|
+
primitive, the checklist for when a GCI is the wrong tool (a tautology on an already-fully-defined
|
|
444
|
+
concept, a target already reached by stated parentage, a distinguishing condition that doesn't
|
|
445
|
+
actually discriminate), how to shape the antecedent (genus + nexus + defining attribute, and the
|
|
446
|
+
role-group partition that silently changes an axiom's meaning if got wrong), and how to derive the
|
|
447
|
+
axiom set from the terminology's own content rather than from theory alone.
|
|
448
|
+
|
|
439
449
|
## Redundant stated Is-a relationships
|
|
440
450
|
|
|
441
451
|
Adding a new stated `Is a` (`116680003`) parent to a concept that already has a broader stated
|
|
@@ -490,7 +500,7 @@ Two distinct kinds of reference, and the obvious query for each has a blind spot
|
|
|
490
500
|
|
|
491
501
|
So run both, and then close the gap with an edit-based sweep: a concept that has never been
|
|
492
502
|
released can only be referenced by something edited on the same branch, so every candidate appears
|
|
493
|
-
in `
|
|
503
|
+
in `get-concepts-for-review`. Fetch each ID from its `concepts` array with `get-concept` and scan
|
|
494
504
|
`classAxioms[].relationships[].target.conceptId` for your target. (If the concept has been promoted
|
|
495
505
|
beyond the task branch, widen that sweep to the project branch — the task's own review list won't
|
|
496
506
|
see a referrer edited on a sibling task.)
|
|
@@ -527,10 +537,10 @@ skipped a step in check 1.
|
|
|
527
537
|
- Re-validate with `validate-review-concepts`, which covers every concept with pending stated
|
|
528
538
|
changes, including the ones you edited on the way to the delete.
|
|
529
539
|
- Re-classify — deletions and axiom edits both change the stated form, so the inferred view is
|
|
530
|
-
stale until you do. After the save, `
|
|
540
|
+
stale until you do. After the save, `get-concepts-for-review`'s `conceptsClassified` array shows which
|
|
531
541
|
concepts the classification actually rewrote, which is a useful confirmation that the re-parenting
|
|
532
542
|
landed the way you intended.
|
|
533
|
-
- The deleted concept keeps appearing in `
|
|
543
|
+
- The deleted concept keeps appearing in `get-concepts-for-review` indefinitely — the branch's traceability
|
|
534
544
|
log records that it changed, and that's permanent. It's reported as `"deleted": true`, and
|
|
535
545
|
`validate-review-concepts` skips those entries, so this needs no handling on your part.
|
|
536
546
|
|
|
@@ -668,7 +678,7 @@ authoring-cli validate-review-concepts
|
|
|
668
678
|
|
|
669
679
|
That's the end-of-session check: it validates every concept with pending *stated* changes and
|
|
670
680
|
prints a per-concept result plus a tally, exiting non-zero if anything has issues. It reads the
|
|
671
|
-
same list `
|
|
681
|
+
same list `get-concepts-for-review` puts in its `concepts` array, so it covers exactly what you edited —
|
|
672
682
|
and it handles the two things that make a hand-rolled loop over those IDs go wrong: it never
|
|
673
683
|
touches the `conceptsClassified` bucket (concepts a *previous* classification's inferred-
|
|
674
684
|
relationship side effects touched, not your edits), and it skips concepts deleted on this branch
|
|
@@ -680,6 +690,22 @@ The names are deliberately distinct: `validate-task` validates the entire task b
|
|
|
680
690
|
job, like `classify`); `validate-concept` is a synchronous, read-only check of a single concept;
|
|
681
691
|
`validate-review-concepts` runs that per-concept check across your pending edits.
|
|
682
692
|
|
|
693
|
+
## Reviewing concepts against SNOMED CT terminology standards
|
|
694
|
+
|
|
695
|
+
```
|
|
696
|
+
authoring-cli review-concepts
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
Fetches the full concept representation — descriptions, relationships, axioms — for every concept
|
|
700
|
+
with pending stated changes on the task, in one call. Nothing here is a validation run: the command
|
|
701
|
+
performs no Snowstorm checks of its own and reports no pass/fail. Its only job is gathering the data
|
|
702
|
+
an editorial review needs, so that review doesn't cost a manual `get-concept` per concept.
|
|
703
|
+
|
|
704
|
+
The review itself — is the naming correct, is the semantic tag right, is the concept appropriately
|
|
705
|
+
primitive or sufficiently defined, is the modelling sound — is a judgment call against the SNOMED CT
|
|
706
|
+
Editorial Guide, not something any command can decide. See `references/review-concepts.md` for that
|
|
707
|
+
checklist.
|
|
708
|
+
|
|
683
709
|
## Large multi-session batches
|
|
684
710
|
|
|
685
711
|
Generating many structurally-parallel concepts from a large source list (tens to thousands of
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
# Modelling with GCI axioms
|
|
2
|
+
|
|
3
|
+
General method for using `authoring-cli add-gci-axiom` to make one concept classify under another
|
|
4
|
+
without making the target concept fully defined — applicable to any semantic type (disorder,
|
|
5
|
+
procedure, observable, finding, and so on), not just disease aetiology. `SKILL.md`'s "Adding a GCI
|
|
6
|
+
axiom" section covers the command mechanics (direction of assertion, group handling, the
|
|
7
|
+
publication-gate difference from `update-gci-axiom`/`delete-gci-axiom`); this file covers the
|
|
8
|
+
modelling judgment around it — deciding whether a GCI is the right tool at all, and if so, what its
|
|
9
|
+
antecedent should say.
|
|
10
|
+
|
|
11
|
+
## Contents
|
|
12
|
+
|
|
13
|
+
- [What a GCI is, and why it exists](#what-a-gci-is-and-why-it-exists)
|
|
14
|
+
- [The hard constraint: PRIMITIVE, and stays PRIMITIVE](#the-hard-constraint-primitive-and-stays-primitive)
|
|
15
|
+
- [Before authoring anything: is a GCI even the right tool?](#before-authoring-anything-is-a-gci-even-the-right-tool)
|
|
16
|
+
- [Confirming the concept's current state](#confirming-the-concepts-current-state)
|
|
17
|
+
- [The antecedent: genus, nexus, defining attribute](#the-antecedent-genus-nexus-defining-attribute)
|
|
18
|
+
- [Choosing the defining attribute for the domain](#choosing-the-defining-attribute-for-the-domain)
|
|
19
|
+
- [Deriving the axiom set from content, not just from theory](#deriving-the-axiom-set-from-content-not-just-from-theory)
|
|
20
|
+
- [The two-way test](#the-two-way-test)
|
|
21
|
+
- [Authoring, validating, classifying](#authoring-validating-classifying)
|
|
22
|
+
- [Reporting the outcome](#reporting-the-outcome)
|
|
23
|
+
|
|
24
|
+
## What a GCI is, and why it exists
|
|
25
|
+
|
|
26
|
+
SNOMED CT has exactly two definition-status values, and the distinction is about necessary vs.
|
|
27
|
+
sufficient conditions, not about GCIs directly:
|
|
28
|
+
|
|
29
|
+
- **Defined (`FULLY_DEFINED`)** — the concept has conditions that are both necessary *and*
|
|
30
|
+
sufficient: one equivalent-classes axiom, `A ≡ C`. Formally that's two class-inclusion axioms at
|
|
31
|
+
once, `A ⊑ C` (C is necessary) and `C ⊑ A` (C is sufficient).
|
|
32
|
+
- **Primitive (`PRIMITIVE`)** — the concept's stated conditions are necessary but *not* sufficient.
|
|
33
|
+
Plenty of things satisfying the class axiom aren't this concept.
|
|
34
|
+
|
|
35
|
+
**A primitive concept can also carry conditions that are sufficient without being necessary — that
|
|
36
|
+
is what a GCI is.** Where the class axiom reads `TargetConcept ⊑ genus ⊓ nexus`, a GCI reads
|
|
37
|
+
`genus ⊓ nexus ⊓ extra-condition ⊑ TargetConcept` — the reverse direction, attached separately. It
|
|
38
|
+
lets something that satisfies the extra condition classify *under* the target concept without
|
|
39
|
+
asserting that everything under the target concept satisfies that condition.
|
|
40
|
+
|
|
41
|
+
**GCIs exist because SNOMED CT's logic profile (OWL 2 EL) has no primitive for true logical OR
|
|
42
|
+
inside a definition.** When a concept's real membership condition is genuinely a union of
|
|
43
|
+
alternatives — "reachable via cause 1, or cause 2, or context 3" — you can't write that as one
|
|
44
|
+
expression. Each GCI is one disjunct of that union, expressed as its own independent
|
|
45
|
+
sufficient-condition axiom, standing in for the missing OR. This is the same device used to model
|
|
46
|
+
"colorectal cancer = colon or rectum or both" (`781382000`), just with the disjuncts being different
|
|
47
|
+
originating conditions instead of different sites. Two things follow directly from this:
|
|
48
|
+
|
|
49
|
+
- **A GCI a concept "doesn't need yet" isn't overreach — a union with a missing disjunct is an
|
|
50
|
+
incomplete union.** This is why a canonical GCI is authored prospectively, even when nothing
|
|
51
|
+
currently in the terminology satisfies its antecedent.
|
|
52
|
+
- **A false capture on one GCI is fatal to that GCI alone, not to the others.** Each disjunct is
|
|
53
|
+
checked independently — narrowing or dropping one axiom because it over-matches says nothing about
|
|
54
|
+
whether a different axiom on the same concept is safe.
|
|
55
|
+
|
|
56
|
+
Contrast this with **conjunction**, which SNOMED CT expresses natively with role groups on a single
|
|
57
|
+
axiom — no GCI needed. If what you're modelling is really "one thing with two simultaneous
|
|
58
|
+
properties" rather than "one thing reachable by several alternative routes", it's an ordinary
|
|
59
|
+
axiom with multiple groups, not a GCI. Getting this distinction right is a judgment call about
|
|
60
|
+
which formal shape the real-world "and"/"or" actually denotes — see the SNOMED CT Editorial Guide's
|
|
61
|
+
`general-modeling/general-concept-inclusions-gcis.md` for the authoritative definition.
|
|
62
|
+
|
|
63
|
+
## The hard constraint: PRIMITIVE, and stays PRIMITIVE
|
|
64
|
+
|
|
65
|
+
**A concept that carries a GCI must be, and must remain, `PRIMITIVE`.** A concept can't coherently
|
|
66
|
+
be both fully defined by its own class axiom *and* need an extra sufficient condition bolted on
|
|
67
|
+
without either the class axiom being incomplete or the GCI being redundant — decomposing what
|
|
68
|
+
should be one equivalent-classes axiom into a primitive class axiom plus a reverse-implication GCI
|
|
69
|
+
is a syntax anti-pattern, not an equivalent way of saying the same thing.
|
|
70
|
+
|
|
71
|
+
**Pre-flight, before every `add-gci-axiom` call: confirm `definitionStatus` is `PRIMITIVE`.** If the
|
|
72
|
+
target is `FULLY_DEFINED`, stop and check whether the GCI you're about to write is already entailed
|
|
73
|
+
by the existing equivalence (see the tautology check below) before assuming a GCI is even
|
|
74
|
+
applicable. A small number of released concepts are `FULLY_DEFINED` while still carrying a GCI
|
|
75
|
+
(e.g. `128092005 |Secondary autoimmune thrombocytopenia|`) — that combination is a legacy exception
|
|
76
|
+
in existing content, never a pattern to replicate in new authoring.
|
|
77
|
+
|
|
78
|
+
**Corollary for authoring a concept meant to fall under a GCI-bearing target: never state the
|
|
79
|
+
target as a parent by hand to force it to classify.** If the new concept's own definition already
|
|
80
|
+
satisfies one of the target's GCI antecedents, inference places it there automatically once
|
|
81
|
+
classification runs — provided the antecedent is genuinely satisfied. A hand-added stated parent is
|
|
82
|
+
redundant at best, and at worst it masks a real gap in the GCI's own coverage that a future reader
|
|
83
|
+
would otherwise have caught.
|
|
84
|
+
|
|
85
|
+
## Before authoring anything: is a GCI even the right tool?
|
|
86
|
+
|
|
87
|
+
Run this checklist before writing any axiom. Each item that fires ends the question for that
|
|
88
|
+
concept — most candidates that look like GCI work turn out not to need one, and recognising that
|
|
89
|
+
early is a complete, useful outcome in itself, not a failure to find something to author.
|
|
90
|
+
|
|
91
|
+
1. **Is the target `FULLY_DEFINED` with the distinguishing condition already inside the
|
|
92
|
+
definition?** Then the GCI would be a tautology: if `Target ≡ genus ⊓ nexus ⊓ ∃attr.Value`, then
|
|
93
|
+
`genus ⊓ nexus ⊓ ∃attr.Value ⊑ Target` is already one half of that equivalence and adds nothing.
|
|
94
|
+
This is the one check here that's *logically* necessary rather than empirical — trust it over any
|
|
95
|
+
other signal. Don't "generalise" such a definition into a broader GCI either: widening the
|
|
96
|
+
defining attribute's target to something looser reopens exactly the over-matching the tight
|
|
97
|
+
definition was written to avoid.
|
|
98
|
+
2. **Is the distinguishing condition already stated as necessary on a `PRIMITIVE` version of the
|
|
99
|
+
target**, or is the target a plain specialisation of an already-more-specific parent that carries
|
|
100
|
+
its own qualifier (severity, site, morphology, clinical course) rather than a genuinely
|
|
101
|
+
independent condition? Either way, the necessary side already does the discriminating work a GCI
|
|
102
|
+
would duplicate.
|
|
103
|
+
3. **Does the target already get its intended descendants through stated parentage instead?** Some
|
|
104
|
+
groupers are maintained entirely by hand — every intended member states `Is a <target>` directly,
|
|
105
|
+
sometimes via a mid-level sub-grouper, with zero GCIs. Check this *before* assuming an empty or
|
|
106
|
+
sparse inferred-descendant set means "unmodelled, needs a GCI": adding one here risks duplicating
|
|
107
|
+
existing structure and introducing a false capture the hand-placement was deliberately avoiding.
|
|
108
|
+
See the structural screen below for how to tell which design a candidate is already in.
|
|
109
|
+
4. **Does the antecedent's discriminating condition actually discriminate**, or is it shared broadly
|
|
110
|
+
across both the population you want and the population you don't? A condition satisfied by
|
|
111
|
+
hundreds of concepts on both sides of the intended line can't separate them, and usually signals
|
|
112
|
+
that no axiom exists (or should) rather than that one is missing.
|
|
113
|
+
5. **Does the genus you're about to build the antecedent on actually contain the content you're
|
|
114
|
+
trying to reach?** If `<<stated-genus AND <the-genus-the-content-actually-lives-in>` returns 0, no
|
|
115
|
+
antecedent built on that genus can ever reach that content — this is a re-parenting problem, not a
|
|
116
|
+
GCI problem, and needs flagging as such rather than papering over with a broader antecedent.
|
|
117
|
+
6. **Is the qualifying word in the target's name even expressing the relationship you assume?**
|
|
118
|
+
Words like "secondary", "acquired", "iatrogenic", or "atypical" carry more than one sense
|
|
119
|
+
depending on the hierarchy — sometimes causal/aetiological (a GCI genuinely applies), sometimes
|
|
120
|
+
temporal or ordinal ("second in a sequence", not "caused by"), sometimes positional or
|
|
121
|
+
level-of-anatomy (e.g. an endocrine axis, where the modifier points at *where* the disease process
|
|
122
|
+
sits rather than *what caused* it — and a causal GCI there doesn't just over-reach, it inverts the
|
|
123
|
+
population). Read the class axiom's own parent and defining attributes before assuming the
|
|
124
|
+
aetiological reading; the concept's own stated genus and finding site usually give the real sense
|
|
125
|
+
away.
|
|
126
|
+
7. **Otherwise**, the target is a genuine candidate — proceed to confirm its current state and then
|
|
127
|
+
design the antecedent.
|
|
128
|
+
|
|
129
|
+
### The structural screen
|
|
130
|
+
|
|
131
|
+
Before sweeping content or reading literature, ask how the target concept already gets its intended
|
|
132
|
+
members, if it gets any at all:
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
authoring-cli search-concepts --ecl "<<TARGET_ID>" --limit 1 # read .total, not the row count
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Then `get-concept` a couple of the hits and check whether they **state** `Is a <target>` in their
|
|
139
|
+
own class axiom, or arrive purely by inference.
|
|
140
|
+
|
|
141
|
+
- **Many descendants, all stated** → maintained by hand (checklist item 3). A GCI here is likely
|
|
142
|
+
redundant and risks a false capture the hand-placement avoided.
|
|
143
|
+
- **Zero descendants** → the classic "possibly unmodelled" symptom — worth investigating further,
|
|
144
|
+
but not yet evidence a GCI is missing (see the calibration caution below).
|
|
145
|
+
- **Descendants that arrive without stating the target** → check whether a *fully-defined
|
|
146
|
+
intermediate* between them and the target accounts for the arrival before crediting it to a GCI —
|
|
147
|
+
a fully-defined child concept that states the target classifies its own sub-branch on its own,
|
|
148
|
+
with the target itself carrying no GCI at all. Walk the stated parents upward before concluding a
|
|
149
|
+
GCI is responsible for an inferred-only arrival.
|
|
150
|
+
|
|
151
|
+
**Calibrate before trusting an empty result from any of this.** The inferred view can lag the axiom
|
|
152
|
+
set, particularly on the most recently authored content — a GCI can exist and currently classify
|
|
153
|
+
nothing, especially just after being added and before classification has run. Confirm at least one
|
|
154
|
+
genuine inference-only arrival under the target (or accept that the branch hasn't been classified
|
|
155
|
+
recently enough to show one) before reading a `0` result as "no GCI exists" rather than "no
|
|
156
|
+
information yet."
|
|
157
|
+
|
|
158
|
+
## Confirming the concept's current state
|
|
159
|
+
|
|
160
|
+
Read the live axioms before assuming anything about what's already there — a candidate can already
|
|
161
|
+
be modelled and simply not annotated as such in whatever list surfaced it:
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
authoring-cli get-concept --id <SCTID> | sed -n '/^{/,$p' | jq -r '
|
|
165
|
+
"\(.fsn.term) [\(.definitionStatus)] gci=\(.gciAxioms|length)",
|
|
166
|
+
(.classAxioms[] | "CLASS " + ([.relationships[]|select(.active)|"g\(.groupId):\(.type.pt.term)=\(.target.conceptId)|\(.target.fsn.term)"]|join(" | "))),
|
|
167
|
+
(.gciAxioms[] | "GCI " + ([.relationships[]|select(.active)|"g\(.groupId):\(.type.pt.term)=\(.target.conceptId)|\(.target.fsn.term)"]|join(" | ")))'
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
`gci=0` means there's no existing GCI on this concept — but check the checklist above before
|
|
171
|
+
concluding one is *needed*; the common outcome across any grouper-style hierarchy is that most
|
|
172
|
+
candidates correctly get none. Anything else means you're reviewing existing axioms, which is a
|
|
173
|
+
different job from authoring new ones — say so rather than adding duplicates on top.
|
|
174
|
+
|
|
175
|
+
## The antecedent: genus, nexus, defining attribute
|
|
176
|
+
|
|
177
|
+
Every GCI antecedent is built from the same three parts:
|
|
178
|
+
|
|
179
|
+
```
|
|
180
|
+
g0 Is a = <the genus the target concept specialises>
|
|
181
|
+
gN <enough of the target's own nexus to stop the axiom over-matching> (sometimes none at all)
|
|
182
|
+
gM <one distinguishing attribute = one value>
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
- **Genus.** Usually one concept — the thing the target *is a kind of* — and not necessarily every
|
|
186
|
+
parent the class axiom states, nor necessarily a stated parent at all. Prefer the **inferred**
|
|
187
|
+
genus, and prefer a genus that isn't itself a member of the same "grouper family" as the target
|
|
188
|
+
(using an already-specialised sibling as the genus just recreates the specialisation problem one
|
|
189
|
+
level down). When the class axiom states more than one parent and a single simpler genus doesn't
|
|
190
|
+
capture what's needed, copy the full stated parent list instead of guessing at one.
|
|
191
|
+
- **Nexus — exists to compensate for a vague genus.** When the genus is broad (e.g. a top-level
|
|
192
|
+
category like `Disease`, `Procedure`, or `Finding`), keep enough of the target's own class-axiom
|
|
193
|
+
nexus (site, morphology, component, method — whatever pins the concept down) to stop the antecedent
|
|
194
|
+
matching everything under that broad genus. When the genus is already a *specific* concept that
|
|
195
|
+
pins the entity down on its own, the nexus is usually redundant and gets dropped — even if the
|
|
196
|
+
class axiom carried an elaborate one.
|
|
197
|
+
- **Defining attribute.** The one condition that, combined with the genus and nexus, is sufficient
|
|
198
|
+
(not necessary) for membership. Exactly one per GCI axiom — a disease's "caused by X, or Y, or Z"
|
|
199
|
+
is several separate GCIs, not one axiom with several attributes.
|
|
200
|
+
|
|
201
|
+
The antecedent is **not** a mechanical copy of the class axiom in either direction — it can drop
|
|
202
|
+
groups the class axiom has, or add attributes the class axiom lacks, when the target's own real
|
|
203
|
+
definition calls for it. Read a live, already-signed-off exemplar in the same subhierarchy before
|
|
204
|
+
deciding what to keep or drop; conventions in any given area drift over time, and the most recently
|
|
205
|
+
released exemplar wins over anything written down in a reference file.
|
|
206
|
+
|
|
207
|
+
### Role-group partition
|
|
208
|
+
|
|
209
|
+
The one rule here that's a hard constraint rather than a judgment call, because getting it wrong is
|
|
210
|
+
invisible — nothing rejects the save, and validation passes regardless:
|
|
211
|
+
|
|
212
|
+
- An attribute that describes **the same process/entity the nexus already describes** (e.g. a
|
|
213
|
+
causative agent or pathological process acting on the site+morphology the nexus already names)
|
|
214
|
+
goes **inside** the nexus's own role group.
|
|
215
|
+
- An attribute that relates the target to a **separate, independent entity** (e.g. "due to",
|
|
216
|
+
"after", "associated with" pointing at a different disease, event, or procedure) gets a **separate**
|
|
217
|
+
group of its own.
|
|
218
|
+
|
|
219
|
+
This partition was derived from **multi-attribute** nexuses (e.g. a site+morphology pair together).
|
|
220
|
+
When the nexus is a single lone attribute with nothing else, both the nexus attribute and the
|
|
221
|
+
defining attribute end up in separate groups instead — don't assume "inside the nexus group" extends
|
|
222
|
+
automatically to a single-attribute nexus; verify against a live exemplar.
|
|
223
|
+
|
|
224
|
+
Absolute group *numbers* carry no meaning on their own — only the partition does. Build the whole
|
|
225
|
+
antecedent for one GCI in a single `add-gci-axiom` call with explicit `groupId`s (see SKILL.md's
|
|
226
|
+
"Adding a GCI axiom" for the command itself and the direction-of-assertion caveat) rather than
|
|
227
|
+
composing it from several calls.
|
|
228
|
+
|
|
229
|
+
## Choosing the defining attribute for the domain
|
|
230
|
+
|
|
231
|
+
There's no single attribute list that fits every semantic type — the right attribute is whatever
|
|
232
|
+
the domain models the distinguishing relationship with, and it should be looked up for the concept
|
|
233
|
+
type actually in front of you rather than assumed from a different domain's convention:
|
|
234
|
+
|
|
235
|
+
- **Disorders/clinical findings** — causal or associative attributes: `Due to` (asserts causation),
|
|
236
|
+
`After` (asserts only temporal sequence — a disease, procedure, or event that preceded this one,
|
|
237
|
+
without claiming it caused it), `Associated with` (weaker still — literature claims association,
|
|
238
|
+
not causation), `Causative agent` (a substance, organism, or physical force), `Pathological
|
|
239
|
+
process` (e.g. infectious, autoimmune). See the SNOMED CT Editorial Guide's
|
|
240
|
+
`domain-specific-modeling/clinical-finding-and-disorder/` for the full attribute range and MRCM
|
|
241
|
+
constraints.
|
|
242
|
+
- **Procedures** — the distinguishing condition is usually a method, device, or approach attribute
|
|
243
|
+
rather than a cause: `Method`, `Using device`, `Direct substance`, `Access`, or a site/laterality
|
|
244
|
+
attribute, depending on what actually varies between the members you want to catch and the ones
|
|
245
|
+
you don't. See `domain-specific-modeling/procedure/`.
|
|
246
|
+
- **Observable entities / findings defined by measurement** — `Component`, `Direct site`,
|
|
247
|
+
`Technique`, `Scale type`, or an `Interprets`/`Has interpretation` pair, when the distinguishing
|
|
248
|
+
condition is about *what* is measured or *how*, not about cause. See
|
|
249
|
+
`domain-specific-modeling/observable-entity/`.
|
|
250
|
+
- Whatever the attribute, **verify its target's SCTID and range live** with `get-concept` rather than
|
|
251
|
+
trusting a hardcoded list from memory or an old note — terminology content and MRCM ranges drift,
|
|
252
|
+
and a stale reference confidently points at the wrong concept.
|
|
253
|
+
|
|
254
|
+
**Choose the level of generality deliberately.** A broader target (e.g. a top-level category over a
|
|
255
|
+
narrow subtype) catches more, which is exactly the tradeoff the two-way test below is for: broad
|
|
256
|
+
enough to be worth authoring prospectively, narrow enough not to sweep in something that must stay
|
|
257
|
+
out. When a broad target would over-catch, narrow it rather than abandoning the axiom entirely —
|
|
258
|
+
that sequence (broad → would it capture something excluded? → narrow → only if nothing separates
|
|
259
|
+
them, drop it) is the single most commonly skipped step, and skipping it is what silently loses an
|
|
260
|
+
otherwise-correct axiom.
|
|
261
|
+
|
|
262
|
+
## Deriving the axiom set from content, not just from theory
|
|
263
|
+
|
|
264
|
+
Reasoning top-down from what the domain literature or documentation says *should* be a valid
|
|
265
|
+
distinguishing condition is necessary but not sufficient — the terminology's actual content is the
|
|
266
|
+
more reliable source, and reading it first avoids two symmetric failure modes: predicting an axiom
|
|
267
|
+
that turns out to catch a false-positive population, and omitting an axiom that turns out to be
|
|
268
|
+
well attested once you look.
|
|
269
|
+
|
|
270
|
+
A GCI's antecedent has the form `genus ⊓ nexus ⊓ condition ⊑ Target`, so anything it could ever
|
|
271
|
+
classify must already be a subconcept of the genus. That makes the genus's own subconcepts the
|
|
272
|
+
exact candidate set to sweep — enumerate them and read which attributes they actually carry, rather
|
|
273
|
+
than guessing:
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
G=<genus SCTID>
|
|
277
|
+
# Read .total, never the row count alone — --limit truncates `items` silently, and a
|
|
278
|
+
# returned-count that happens to equal your limit is a cap, not a total.
|
|
279
|
+
authoring-cli search-concepts --ecl "<$G:<candidate-attribute>=*" --limit 300
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
`get-concept` each hit and read its **real axiom**, not its name — a name can mislead about which
|
|
283
|
+
attribute actually carries the cause or mechanism, and only the axiom tells you which candidate
|
|
284
|
+
attribute would actually catch it. ECL matches the **inferred** view, which is the right view: it's
|
|
285
|
+
what classification itself will match against, and it also surfaces concepts that reach the genus
|
|
286
|
+
through a fully-defined definition rather than a stated `Is a`, which a stated-only enumeration
|
|
287
|
+
would miss entirely.
|
|
288
|
+
|
|
289
|
+
Then, per candidate attribute:
|
|
290
|
+
|
|
291
|
+
- **ADD** it if genuinely-in-scope hits exist that no attribute in your current candidate set would
|
|
292
|
+
catch.
|
|
293
|
+
- **SUBTRACT** it if it would capture something that must be excluded (a form the target concept is
|
|
294
|
+
specifically *not* meant to reach) — decisive even against strong positive evidence for the same
|
|
295
|
+
attribute elsewhere.
|
|
296
|
+
- **NARROW** the target rather than dropping the attribute outright when hits are mixed — this is
|
|
297
|
+
usually possible and is the step most often skipped.
|
|
298
|
+
- **Don't let an empty sweep alone suppress an attribute the domain genuinely supports** — absence
|
|
299
|
+
of matching content today isn't evidence the condition doesn't apply; a GCI can be, and often
|
|
300
|
+
should be, authored prospectively. Conversely, don't let "some content exists" stand in as proof
|
|
301
|
+
the axiom is wanted — check the direction and nature of what it would catch.
|
|
302
|
+
|
|
303
|
+
**A single candidate concept isn't always enough to settle absence.** When the target itself has too
|
|
304
|
+
few descendants to sample (0 or 1), the same logic runs in reverse as a **negative test**: pick one
|
|
305
|
+
or several subconcepts of the genus that satisfy a candidate antecedent exactly — subsumed by the
|
|
306
|
+
genus, carrying every nexus attribute, causal/defining target verifiably under the candidate value —
|
|
307
|
+
and check `search-concepts --ecl "<<TARGET AND CANDIDATE"`. `0` means that axiom doesn't exist (once
|
|
308
|
+
you've first confirmed the target's inferred view is live at all, by finding some inference-only
|
|
309
|
+
arrival elsewhere — without that check a `0` here means "no information", not "no axiom"). Several
|
|
310
|
+
independent candidates tested this way, all absent, is as decisive as one, and more trustworthy than
|
|
311
|
+
a single thin sample.
|
|
312
|
+
|
|
313
|
+
## The two-way test
|
|
314
|
+
|
|
315
|
+
Apply this **per candidate axiom, not per concept** — each GCI is checked independently, because
|
|
316
|
+
each is an independent disjunct:
|
|
317
|
+
|
|
318
|
+
1. **Does it capture anything that must be excluded?** This half is decisive when authoring: a
|
|
319
|
+
single confirmed false capture disqualifies that specific axiom regardless of how much positive
|
|
320
|
+
evidence supports it. Narrow the target first; only drop the axiom if nothing narrows it enough.
|
|
321
|
+
2. **Does it catch anything currently in the terminology?** Preferable, not required — a canonical,
|
|
322
|
+
well-attested condition is authored even prospectively, against a genus with zero matching
|
|
323
|
+
subconcepts today.
|
|
324
|
+
|
|
325
|
+
Settle what should and shouldn't fall inside the target's intended scope from the domain's own
|
|
326
|
+
documentation/literature *before* judging sweep hits — don't assume the best-known or most-cited
|
|
327
|
+
cause of something is automatically the one this particular target is meant to catch; it can just as
|
|
328
|
+
easily be the population the target exists to exclude. And watch for **reverse-direction hits**: a
|
|
329
|
+
sweep can surface concepts where the target's own subject is modelled as the *cause* or *component*
|
|
330
|
+
of something else, not the reverse — these inflate an apparent hit count without meaning anything
|
|
331
|
+
for this axiom.
|
|
332
|
+
|
|
333
|
+
## Authoring, validating, classifying
|
|
334
|
+
|
|
335
|
+
See `SKILL.md`'s "Adding a GCI axiom" for the `add-gci-axiom` command itself — the direction of
|
|
336
|
+
assertion (the target concept ends up as the superclass, not the subclass), building the whole
|
|
337
|
+
relationship list including every group in one call, and reading the result back with `get-concept`
|
|
338
|
+
rather than trusting the echoed `axiomId` (Snowstorm can reassign ids across the array on save, so
|
|
339
|
+
consecutive calls may echo the same id while each having actually saved correctly).
|
|
340
|
+
|
|
341
|
+
After authoring:
|
|
342
|
+
|
|
343
|
+
```
|
|
344
|
+
authoring-cli validate-concept --id <SCTID>
|
|
345
|
+
authoring-cli classify --wait
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
Then confirm the classification did what was predicted, in **both** directions — this is the only
|
|
349
|
+
real evidence the axioms work, since validation checks conventions and says nothing about
|
|
350
|
+
subsumption:
|
|
351
|
+
|
|
352
|
+
```
|
|
353
|
+
authoring-cli search-concepts --ecl "<<SCTID>" # did the intended concepts arrive?
|
|
354
|
+
authoring-cli get-concept --id <a concept you expected to be caught> # inferred Is a includes the target?
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
A concept you predicted would be caught and wasn't is usually a group-partition mistake (see
|
|
358
|
+
above) or a case where the real content models the distinguishing condition with a different
|
|
359
|
+
attribute than assumed — go back and read that concept's own axiom again rather than loosening the
|
|
360
|
+
GCI's target until something sticks; a loosened target that happens to catch the concept you wanted
|
|
361
|
+
can just as easily catch something you didn't.
|
|
362
|
+
|
|
363
|
+
Where classification genuinely cannot complete on the environment you're working in, say so
|
|
364
|
+
explicitly rather than letting "validated clean" stand in for "verified" — subsumption stays
|
|
365
|
+
predicted rather than observed until classification actually runs, and that distinction belongs in
|
|
366
|
+
whatever you report.
|
|
367
|
+
|
|
368
|
+
## Reporting the outcome
|
|
369
|
+
|
|
370
|
+
Whether the concept ends up with new axioms or not, state:
|
|
371
|
+
|
|
372
|
+
- The GCIs authored, each with its defining condition and, where the sweep found one, the content
|
|
373
|
+
it's expected to catch.
|
|
374
|
+
- Concepts or conditions deliberately left out, and why (already covered another way, a confirmed
|
|
375
|
+
false capture, out of scope for this target).
|
|
376
|
+
- False-capture checks actually performed, not just asserted.
|
|
377
|
+
- Validation and classification results — or an explicit statement that classification didn't
|
|
378
|
+
complete and subsumption is predicted rather than confirmed.
|
|
379
|
+
- Any modelling problem noticed along the way in a *different* concept (a genus that doesn't
|
|
380
|
+
contain the content it should, a defining attribute already present on a concept that
|
|
381
|
+
contradicts what's being modelled here) — flag it as separate work rather than silently fixing it
|
|
382
|
+
in the same pass.
|
|
383
|
+
|
|
384
|
+
A correctly-reasoned decision not to author anything is a complete result, not a failure to find
|
|
385
|
+
something — the majority of candidates in most grouper-style hierarchies turn out not to need a
|
|
386
|
+
GCI at all, and saying so with the reasoning attached is exactly as useful as a set of new axioms.
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# Reviewing concepts against SNOMED CT terminology standards
|
|
2
|
+
|
|
3
|
+
`authoring-cli review-concepts` fetches the full representation — descriptions, relationships,
|
|
4
|
+
axioms — for every concept with pending stated changes on the task. It performs no validation of
|
|
5
|
+
its own; it exists purely to hand you the content to judge. This file is that judgment: a checklist
|
|
6
|
+
for whether the content is *right*, not whether it saves. A concept can be perfectly well-formed by
|
|
7
|
+
Snowstorm's own rules and still be wrong SNOMED CT content — a bad FSN, an inappropriate semantic
|
|
8
|
+
tag, an under-modelled definition, a primitive concept that should be sufficiently defined — because
|
|
9
|
+
none of that is a save-time constraint Snowstorm enforces. It's an editorial judgment call, which is
|
|
10
|
+
what this checklist is for.
|
|
11
|
+
|
|
12
|
+
Read each concept's real, current descriptions and axioms from `review-concepts`'s output — not a
|
|
13
|
+
note from earlier in the session; a concept can have changed since you last looked at it.
|
|
14
|
+
|
|
15
|
+
## Naming conventions — apply without fetching anything
|
|
16
|
+
|
|
17
|
+
These are stable, general SNOMED CT Editorial Guide rules that apply to every concept regardless of
|
|
18
|
+
hierarchy, confirmed against the guide's `general-naming-conventions/` section:
|
|
19
|
+
|
|
20
|
+
- **No articles.** "Neoplasm of respiratory tract", not "Neoplasm of the respiratory tract" — omit
|
|
21
|
+
"the"/"a"/"an" from every description.
|
|
22
|
+
- **No abbreviations or acronyms in the FSN.** Allowed in a PT/synonym only with the expansion given
|
|
23
|
+
alongside it (`IBD - inflammatory bowel disease`). The FSN prohibition has real exceptions:
|
|
24
|
+
organism names, allergen components, long-established acronyms ("laser"), imaging modality
|
|
25
|
+
abbreviations (CT, MRI), rare-disease acronyms, and protein nomenclature — don't flag those as
|
|
26
|
+
violations.
|
|
27
|
+
- **Eponyms take no apostrophe-s by default** ("Down syndrome", not "Down's syndrome"), *except*
|
|
28
|
+
when the name naturally ends in "s" already, where the apostrophe alone is correct ("Meigs'
|
|
29
|
+
syndrome", not "Meigs syndrome" or "Meig's syndrome"). This is narrower than "common usage
|
|
30
|
+
decides" — check the actual published form rather than guessing from familiarity.
|
|
31
|
+
- **Morphology-to-anatomy preposition is "of", not "in"** — "Cyst of scalp", not "Cyst in scalp".
|
|
32
|
+
- **FSN uniqueness is case-sensitive.** Two FSNs differing only in capitalization ("Weak e
|
|
33
|
+
phenotype" vs "Weak E phenotype") are both legal and distinct — don't assume a near-duplicate hit
|
|
34
|
+
in `search-concepts` is the same concept without checking case.
|
|
35
|
+
- **FSN structure**: US English spelling, singular nouns, procedures stated in present tense, ending
|
|
36
|
+
in a semantic tag. No hyphens, no forward/backslashes, no numeric ranges, no "OR" (the disjunctive
|
|
37
|
+
"and/or" is the one allowed exception, lowercase), no reference to a specific instance, and — for
|
|
38
|
+
a procedure — no reason/indication baked into the name unless it actually changes the method.
|
|
39
|
+
- **Character limit is 4,096 per description** (FSN, PT, synonym, or text definition alike) — this
|
|
40
|
+
is generous enough that hitting it at all is itself worth double-checking, not a routine
|
|
41
|
+
constraint to design around.
|
|
42
|
+
- **US English in the International Edition; GB (and other dialect) spellings live in language
|
|
43
|
+
refsets only** — this is the same rule `SKILL.md`'s spelling-variant section already covers for
|
|
44
|
+
authoring; here it's a review check, not an authoring step.
|
|
45
|
+
|
|
46
|
+
## Semantic tags and case significance
|
|
47
|
+
|
|
48
|
+
- **The semantic tag must name the concept's actual domain**, and disambiguates two concepts that
|
|
49
|
+
would otherwise share a term — "Hematoma (morphologic abnormality)" vs "Hematoma (disorder)" are
|
|
50
|
+
different concepts precisely because of the tag, not the same concept tagged two ways. A concept
|
|
51
|
+
filed with a tag that doesn't match how it's actually being used (e.g. a body-structure concept
|
|
52
|
+
carrying a `(finding)` tag) is a real content bug, not cosmetic.
|
|
53
|
+
- **A `(disorder)`-tagged concept must have `Disease (disorder)` as a parent or ancestor.** A
|
|
54
|
+
finding promoted to `(disorder)` without that ancestry is a common and easy-to-miss modelling
|
|
55
|
+
error — check it whenever you're reviewing a newly-tagged disorder.
|
|
56
|
+
- **Case significance** (`entireTermCaseSensitive` / `caseInsensitiveInitialLetter` /
|
|
57
|
+
`entireTermCaseSensitive` false, i.e. `ci`/`cI`/`CS`) should follow whether changing case would
|
|
58
|
+
change meaning: `CS` for things like "pH measurement" or "Down syndrome" where a capitalization
|
|
59
|
+
change alters the term itself; `cI` where only the first letter's case is free (most ordinary
|
|
60
|
+
clinical terms); `ci` where nothing case-sensitive occurs at all. A capitalized organism species
|
|
61
|
+
name ("Rubella virus") set to `ci`, or a lowercase disease-of-that-organism term ("rubella
|
|
62
|
+
syndrome") set to `CS`, are both worth flagging — the rule differs between naming the organism and
|
|
63
|
+
naming the disease it causes.
|
|
64
|
+
|
|
65
|
+
## Modelling-quality checks
|
|
66
|
+
|
|
67
|
+
Read the axiom from `get-concept`, not a cached summary, and check:
|
|
68
|
+
|
|
69
|
+
- **Multiple stated parentage is clinically coherent** — each parent should independently be true of
|
|
70
|
+
the concept, not just "close enough" to the intended meaning.
|
|
71
|
+
- **Attribute values aren't more general than the concept's position in the hierarchy implies.** A
|
|
72
|
+
specific disorder with an unusually generic `Finding site` is worth a second look even if nothing
|
|
73
|
+
rejects the save.
|
|
74
|
+
- **Grouping matches the Editorial Guide's grouping rules, not just "doesn't 409".** `Finding
|
|
75
|
+
site`/`Associated morphology` are grouped together whenever both are present and related to the
|
|
76
|
+
same nexus; `Occurrence`, `Causative agent`, and `Pathological process` join that same group when
|
|
77
|
+
they refer to it too. Attributes that describe the *whole* concept rather than one nexus —
|
|
78
|
+
`Associated with`, `Before`/`During`/`After`, `Due to`, `Clinical course`, `Temporally related to`
|
|
79
|
+
— are correctly self-grouped (ungrouped), and `Interprets`/`Has interpretation` group only with
|
|
80
|
+
each other. A concept where everything landed in one group, or where a self-grouped attribute got
|
|
81
|
+
swept into a clinical-finding group, has had its actual meaning changed even though it validates —
|
|
82
|
+
this is the judgment layer behind the `add-relationship --group N` compaction hazard documented in
|
|
83
|
+
`SKILL.md`.
|
|
84
|
+
- **Primitive vs. sufficiently-defined status is appropriate, not just consistent with the source
|
|
85
|
+
concept.** A concept should be sufficiently defined when its stated relationships are "adequate to
|
|
86
|
+
define it relative to its immediate supertypes" — i.e. another concept with the same parent and
|
|
87
|
+
the same attribute values would in fact be the same concept. If the defining attributes don't
|
|
88
|
+
actually distinguish it from siblings, it's genuinely primitive and forcing `FULLY_DEFINED` status
|
|
89
|
+
on it (or on a structurally-parallel batch generated from it — see `SKILL.md`'s substitution
|
|
90
|
+
pattern) misrepresents it, regardless of what `definitionStatus` the source concept happened to
|
|
91
|
+
carry.
|
|
92
|
+
- **MRCM domain/range conformance isn't fully visible from `get-concept` or `validate-concept`.**
|
|
93
|
+
Both surface Snowstorm's save-time checks, which catch cardinality and some domain/range
|
|
94
|
+
violations, but not every MRCM constraint is enforced synchronously at save. If an attribute's
|
|
95
|
+
appropriateness for the concept's domain is in doubt, cross-reference the MRCM reference sets (or
|
|
96
|
+
ask a colleague with editorial authority) rather than treating a clean save as confirmation.
|
|
97
|
+
- **Inactive descriptions still referenced by active relationships** are a known data-quality gap —
|
|
98
|
+
worth a targeted look when reviewing a concept that's had recent description churn.
|
|
99
|
+
|
|
100
|
+
## Terminology quality issues to scan for
|
|
101
|
+
|
|
102
|
+
- **Synonym conflation** — a preferred term and an acceptable synonym on the same concept that
|
|
103
|
+
actually name two different clinical ideas, not two names for the same one.
|
|
104
|
+
`set-acceptability`/`add-description` will happily save either shape; only reading the terms
|
|
105
|
+
side by side catches the conflation.
|
|
106
|
+
- **No relationships beyond `Is a`** — likely under-modelled for a concept whose hierarchy position
|
|
107
|
+
implies it should carry at least one defining attribute (e.g. a disorder with no `Finding site`
|
|
108
|
+
or `Associated morphology` at all, when siblings all have one).
|
|
109
|
+
- **A parenthetical qualifier inside the FSN body, distinct from the semantic tag** — sometimes a
|
|
110
|
+
legitimate disambiguator, but can also signal that the concept should have been split, or that the
|
|
111
|
+
qualifying detail belongs in the definition/attributes instead of the name.
|
|
112
|
+
- **Value-set-style checks**: if the review surfaces a group of concepts meant to function as a set
|
|
113
|
+
(a batch you just authored, or an existing reference set), confirm every member is active — an
|
|
114
|
+
inactive code hiding inside an otherwise-active set is easy to miss one at a time and obvious once
|
|
115
|
+
counted.
|
|
116
|
+
|
|
117
|
+
## Historical associations for inactive concepts encountered during review
|
|
118
|
+
|
|
119
|
+
If reviewing a reference chain leads to an inactive concept (an existing inactive target picked up
|
|
120
|
+
by `search-concepts`, or one you're about to inactivate yourself — see `SKILL.md`'s "Delete or
|
|
121
|
+
inactivate?"), `get-concept`'s association data is more informative than the inactivation reason
|
|
122
|
+
alone. Read the association type precisely, since each implies a different next step:
|
|
123
|
+
|
|
124
|
+
- `SAME AS` / `REPLACED BY` — a direct replacement exists; point new references at it.
|
|
125
|
+
- `WAS A` — only a partial or approximate replacement; don't auto-substitute, review the fit.
|
|
126
|
+
- `POSSIBLY EQUIVALENT TO` — genuinely uncertain; flag for a human editorial decision rather than
|
|
127
|
+
guessing.
|
|
128
|
+
- No association at all — retired with nothing to replace it; document that as a gap rather than
|
|
129
|
+
silently picking the nearest active concept.
|
|
130
|
+
|
|
131
|
+
## Domain-specific modelling — consult the Editorial Guide, don't guess
|
|
132
|
+
|
|
133
|
+
The rules above are the ones stable enough to hold in your head across every hierarchy. Beyond
|
|
134
|
+
them, modelling correctness is domain-specific, and the SNOMED CT Editorial Guide is the
|
|
135
|
+
authoritative source — fetch the relevant page when you're about to make an editorial judgment on a
|
|
136
|
+
concept of that type, not speculatively for every review:
|
|
137
|
+
|
|
138
|
+
```
|
|
139
|
+
https://raw.githubusercontent.com/SNOMED-Documents/snomed-editorial-guide/main/readme/authoring/
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
| Concept type being reviewed | Fetch |
|
|
143
|
+
|---|---|
|
|
144
|
+
| Clinical finding / Disorder | `domain-specific-modeling/clinical-finding-and-disorder/README.md` |
|
|
145
|
+
| Clinical finding attributes | `domain-specific-modeling/clinical-finding-and-disorder/clinical-finding-attributes-summary.md` |
|
|
146
|
+
| Procedure | `domain-specific-modeling/procedure/README.md` |
|
|
147
|
+
| Body structure | `domain-specific-modeling/body-structure/README.md` |
|
|
148
|
+
| Morphologic abnormality | `domain-specific-modeling/body-structure/index-2/README.md` |
|
|
149
|
+
| Observable entity | `domain-specific-modeling/observable-entity/README.md` |
|
|
150
|
+
| Organism | `domain-specific-modeling/organisms/README.md` |
|
|
151
|
+
| Substance | `domain-specific-modeling/substances/README.md` |
|
|
152
|
+
| Qualifier value | `domain-specific-modeling/qualifier-value/README.md` |
|
|
153
|
+
| Situation with explicit context | `domain-specific-modeling/situation-with-explicit-context/README.md` |
|
|
154
|
+
| Pharmaceutical / biologic product | `domain-specific-modeling/pharmaceutical-biologic-product/README.md` |
|
|
155
|
+
| Physical object | `domain-specific-modeling/physical-object/README.md` |
|
|
156
|
+
| Record artifact | `domain-specific-modeling/record-artifact/README.md` |
|
|
157
|
+
| Staging and scales | `domain-specific-modeling/staging-and-scales/README.md` |
|
|
158
|
+
| Event | `domain-specific-modeling/event/README.md` |
|
|
159
|
+
| Relationship grouping rules | `general-modeling/relationship-group.md` |
|
|
160
|
+
| Sufficiently defined vs. primitive | `general-modeling/sufficiently-defined-vs-primitive-concept.md` |
|
|
161
|
+
| GCIs | `general-modeling/general-concept-inclusions-gcis.md` |
|
|
162
|
+
| Semantic tags | `general-naming-conventions/descriptions/semantic-tags/index.md` |
|
|
163
|
+
| Case significance | `general-naming-conventions/case-significance.md` |
|
|
164
|
+
| FSN rules specifically | `general-naming-conventions/descriptions/fully-specified-name.md` |
|
|
165
|
+
| Preferred Term rules | `general-naming-conventions/descriptions/preferred-term.md` |
|
|
166
|
+
|
|
167
|
+
The general naming-conventions and grouping/primitive-vs-defined pages above have been checked
|
|
168
|
+
against the rules stated earlier in this file; the domain-specific pages haven't all been read in
|
|
169
|
+
full — treat the table as where to look, confirm what it says before relying on a specific claim
|
|
170
|
+
from a page not summarized here, and strip GitBook markup (`{% hint %}` blocks, feedback-button
|
|
171
|
+
`<a>` tags) from whatever comes back.
|
|
172
|
+
|
|
173
|
+
## What this checklist is not
|
|
174
|
+
|
|
175
|
+
This is an editorial review, not a validation run — it doesn't check what Snowstorm enforces at
|
|
176
|
+
save time (MRCM cardinality, description constraints, and the like), and it isn't a substitute for
|
|
177
|
+
whatever command does check that. Nothing here can be delegated to a CLI flag: the whole point of
|
|
178
|
+
this pass is judging whether content is *right*, not whether it saves, which is exactly the kind of
|
|
179
|
+
residue no command can absorb.
|