authoring-cli 0.1.33 → 0.1.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/HELP.md CHANGED
@@ -23,7 +23,13 @@ authoring-cli tasks --mine
23
23
  authoring-cli select-task --context PROJ-123 --project PROJ --task PROJ-123
24
24
  ```
25
25
 
26
- A context name (`--context`) is required so two sessions in the same folder can never move each other's task.
26
+ A context name (`--context`) is required so two sessions in the same folder can never move each other's task. Export it once per terminal so the commands below need no extra flags (or add `--context PROJ-123` to each one):
27
+
28
+ ```bash
29
+ export AUTHORING_CLI_CONTEXT=PROJ-123
30
+ ```
31
+
32
+ For scripts and batches, pin the task instead: `export AUTHORING_CLI_TASK=PROJ-123` — a pinned session refuses to act on any other task.
27
33
 
28
34
  ### 4. Start Authoring
29
35
  ```bash
@@ -188,8 +194,8 @@ authoring-cli validate-review-concepts
188
194
  - `authoring-cli watch-notification [--entity-type TYPE] [--timeout SECONDS]` — Wait for next notification
189
195
 
190
196
  ### Skill Management
191
- - `authoring-cli install-skill [--agent claude|codex|all] [--force]` — Register authoring guidance with your AI agent
192
- - `authoring-cli uninstall-skill [--agent claude|codex|all]` — Unregister the skill (run before uninstalling the package)
197
+ - `authoring-cli install-skill [--agent claude|codex|agents|dsh|all] [--project] [--force]` — Copy the authoring guidance skill into your AI agent(s) (Claude Code, Codex, DeepSeek Harness); re-run after upgrading
198
+ - `authoring-cli uninstall-skill [--agent claude|codex|agents|dsh|all]` — Unregister the skill (run before uninstalling the package)
193
199
 
194
200
  ---
195
201
 
@@ -242,7 +248,7 @@ authoring-cli validate-review-concepts
242
248
  ## Best Practices
243
249
 
244
250
  ### Before Starting
245
- 1. Run `authoring-cli login` and select your task
251
+ 1. Run `authoring-cli login` and select your task into a context (`select-task --context <name> ...`)
246
252
  2. Check the task status and any existing concepts: `authoring-cli get-concepts-for-review`
247
253
  3. Review project-specific metadata: `authoring-cli projects --json`
248
254
 
@@ -283,7 +289,7 @@ The package includes detailed guidance on SNOMED CT authoring best practices, Sn
283
289
  authoring-cli install-skill
284
290
  ```
285
291
 
286
- Then use `/authoring-cli` in Claude Code or your agent to get guidance while you work.
292
+ Then use `/authoring-cli` in Claude Code, Codex, DeepSeek Harness (dsh) or your agent to get guidance while you work.
287
293
 
288
294
  ### Server-side Constraints
289
295
  If you encounter a server error (4xx/5xx), check the error message carefully — it often tells you exactly what's wrong. Common issues:
@@ -307,7 +313,7 @@ https://github.com/snomed/authoring-cli
307
313
  A: The CLI runs on any Node.js 24+ environment. Automatic session capture during login works on macOS with Chrome, and on Linux with Chromium/Chrome (including a Termux:X11 proot-distro Debian on Android — `apt install chromium sqlite3`; `login` auto-starts both the Termux:X11 app and its backend so there's no manual open-once step, provided Termux has been granted Android's "Draw over other apps" permission — a one-time device setting under Settings → Apps → Termux that can't be requested from inside the proot; without it, open the Termux:X11 app by hand once instead so `login` has a display to draw its sign-in window on). `login` doesn't require any Chrome profile to already exist — it opens (and creates, if needed) a dedicated "authoring-cli" profile, so a fresh machine or CI image that has never launched Chrome before still works on the very first run. On Windows and any other unsupported platform, `login` will fail with a clear message — but you can still sign in there using `authoring-cli login --cookie <value>` with a session cookie copied from any signed-in browser's DevTools, which needs no Chrome automation at all.
308
314
 
309
315
  **Q: How do I use this with an AI agent?**
310
- A: Install the bundled authoring skill (`authoring-cli install-skill`), then invoke `/authoring-cli` in Claude Code or Codex. The skill teaches the agent about Snowstorm constraints and SNOMED CT modeling rules.
316
+ A: Install the bundled authoring skill (`authoring-cli install-skill`), then invoke `/authoring-cli` in Claude Code, Codex or DeepSeek Harness. The skill teaches the agent about Snowstorm constraints and SNOMED CT modeling rules.
311
317
 
312
318
  **Q: Can I undo a change?**
313
319
  A: There's no built-in undo. However:
package/README.md CHANGED
@@ -20,21 +20,30 @@ authoring-cli install-skill
20
20
 
21
21
  ```
22
22
  Installed skill 'authoring-cli' for:
23
- claude ~/.claude/skills/authoring-cli (symlink -> /usr/local/lib/node_modules/authoring-cli/skills/authoring-cli)
24
- codex ~/.codex/prompts/authoring-cli.md (pointer into the installed package)
23
+ claude ~/.claude/skills/authoring-cli (installed — copied from /usr/local/lib/node_modules/authoring-cli/skills/authoring-cli (v0.1.35))
24
+ dsh ~/.dsh/skills/authoring-cli (installed — copied from /usr/local/lib/node_modules/authoring-cli/skills/authoring-cli (v0.1.35))
25
25
 
26
26
  Restart your agent, then use /authoring-cli.
27
27
  ```
28
28
 
29
- Registration is a symlink back into the installed package, so `npm update -g authoring-cli` updates the guidance too — it can't drift out of step with the CLI you have. By default it registers with whichever agents are present on the machine.
29
+ Each target gets a **real copy** of the skill (`SKILL.md` + `references/`), stamped with a small `.installed-by-authoring-cli.json` marker. A copy doesn't follow the package, so **re-run `authoring-cli install-skill` after `npm update -g authoring-cli`** — it recognises its own earlier copy by the marker and refreshes it (`updated`), with no `--force`. By default it targets whichever of `claude`, `codex` and `dsh` are present on the machine (falling back to `claude`).
30
+
31
+ | Target | Skill lands in | Notes |
32
+ |---|---|---|
33
+ | `claude` | `~/.claude/skills/authoring-cli/` | `--project` puts it in `./.claude/skills/` instead |
34
+ | `codex` | `~/.codex/skills/authoring-cli/` (or `$CODEX_HOME/skills/`) | A legacy `~/.codex/prompts/authoring-cli.md` pointer from earlier versions is removed |
35
+ | `dsh` | `~/.dsh/skills/authoring-cli/` (or `$DSH_HOME/skills/`) | DeepSeek Harness — its skill catalog is separate from Claude Code's, so a Claude-only install is invisible to it. Auto-detected when `~/.dsh` exists |
36
+ | `agents` | `~/.agents/skills/authoring-cli/` (or `$DSH_AGENTS_HOME/skills/`) | The cross-tool root DSH also scans. **Never auto-selected** (it would register the skill with DSH twice) — name it explicitly |
30
37
 
31
38
  | Flag | Effect |
32
39
  |---|---|
33
- | `--agent claude\|codex\|all` | Register for specific agents (comma-separated) instead of the detected ones |
34
- | `--project` | Install into `./.claude/skills/` for this repo rather than your home directory |
35
- | `--force` | Replace an existing registration of the same name |
40
+ | `--agent claude\|codex\|agents\|dsh\|all` | Register for specific agents (comma-separated) instead of the detected ones |
41
+ | `--project` | Claude Code only: install into `./.claude/skills/` for this repo rather than your home directory |
42
+ | `--force` | Replace an existing directory of the same name that isn't recognizably ours |
43
+
44
+ A DSH session already open won't see the skill until you start a new one — its catalog is loaded at session start.
36
45
 
37
- Nothing is written outside the package until you run this — installing the npm package doesn't touch `~/.claude` or `~/.codex` on its own.
46
+ Nothing is written outside the package until you run this — installing the npm package doesn't touch `~/.claude`, `~/.codex`, `~/.dsh` or `~/.agents` on its own.
38
47
 
39
48
  ### Unregistering
40
49
 
@@ -44,9 +53,9 @@ authoring-cli uninstall-skill # run this BEFORE npm rm -g authoring-cli
44
53
 
45
54
  **Order matters.** npm 7 removed the uninstall lifecycle scripts — `preuninstall` and `postuninstall` are never run — so `npm rm -g authoring-cli` cannot clean up after itself, and by the time the package is gone, so is the command that would have. Unregister first, remove the package second.
46
55
 
47
- If you do it the other way round, nothing breaks: the leftover symlink dangles and agents skip it. A later `npm install -g authoring-cli && authoring-cli install-skill` silently reclaims it (no `--force` needed — it's recognizably ours), or you can delete `~/.claude/skills/authoring-cli` and `~/.codex/prompts/authoring-cli.md` by hand.
56
+ If you do it the other way round, nothing breaks: the leftover copies are inert files that agents simply read as a (now unmaintained) skill. A later `npm install -g authoring-cli && authoring-cli install-skill` silently refreshes them (no `--force` needed — the marker says they're ours), or you can delete the `authoring-cli` directory under each skills folder by hand.
48
57
 
49
- `uninstall-skill` only removes registrations it can recognize as its own: a symlink into some `authoring-cli` package, a byte-identical copy of the shipped skill, or a generated Codex pointer. A skill directory or prompt you wrote under the same name is reported and left alone unless you pass `--force`. It takes the same `--agent`/`--project` flags, and defaults to checking every supported agent so nothing is left behind.
58
+ `uninstall-skill` only removes registrations it can recognize as its own: a marked copy, a symlink from an earlier version of this tool (live or dangling), a byte-identical copy of the shipped skill, or a legacy Codex pointer prompt. A skill directory you wrote under the same name is reported and left alone unless you pass `--force`. It takes the same `--agent`/`--project` flags, and defaults to checking every supported agent so nothing is left behind.
50
59
 
51
60
  ## Sign in
52
61
 
@@ -111,7 +120,7 @@ authoring-cli contexts
111
120
  - `AUTHORING_CLI_TASK=<TASK-KEY>` (project derived from the key, or set `AUTHORING_CLI_PROJECT`) **pins** the process to a task with no file involved. A command given a different `--task`, or `select-task` on a different task, is refused. Best for scripts and agent batches.
112
121
  - `--project`/`--task` on a command targets that task for that call only.
113
122
 
114
- With none of these, task-targeting commands fail and `select-task`/`create-task`/`recover-task` (unless `--no-select`) refuse, rather than guess. A selection left in `session.json` by an older version is ignored. The login cookie stays shared by all contexts, and `select-task` never rewrites it.
123
+ With none of these, task-targeting commands fail and `select-task`/`create-task`/`recover-task` (unless `--no-select`) refuse, rather than guess. **There is no default task:** a selection left in `session.json` by an older version is discarded when the file is read, and nothing is ever stored there. The login cookie stays shared by all contexts, and `select-task` never rewrites it.
115
124
 
116
125
  Selecting a task also **creates its branch** if it doesn't have one yet. A task still in status `New` has no branch — that's the moment the Authoring Workbench would create it, so `select-task` does the same, and the first edit afterwards doesn't 404.
117
126
 
@@ -172,7 +181,8 @@ Run the CLI with no arguments for the full usage text, including every flag.
172
181
 
173
182
  ```bash
174
183
  authoring-cli login
175
- authoring-cli create-task --project PROJ --summary "Add hepatic synonyms"
184
+ export AUTHORING_CLI_CONTEXT=hepatic-synonyms # name this session's context once
185
+ authoring-cli create-task --project PROJ --summary "Add hepatic synonyms" # selects it into that context
176
186
  authoring-cli get-concept --id 64572001
177
187
  authoring-cli add-description --id 64572001 --term "Hepatic structure" --type SYNONYM
178
188
  authoring-cli validate-review-concepts
package/dist/index.js CHANGED
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ni=Object.create;var Ee=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var Oi=Object.getOwnPropertyNames;var Fi=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var Ki=(e,t)=>{for(var r in t)Ee(e,r,{get:t[r],enumerable:!0})},Zt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Oi(t))!Li.call(e,n)&&n!==r&&Ee(e,n,{get:()=>t[n],enumerable:!(o=Di(t,n))||o.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Ni(Fi(e)):{},Zt(t||!e||!e.__esModule?Ee(r,"default",{value:e,enumerable:!0}):r,e)),_i=e=>Zt(Ee({},"__esModule",{value:!0}),e);var _a={};Ki(_a,{COMMANDS:()=>Qt,main:()=>ji,parsePositionals:()=>Ei});module.exports=_i(_a);var z={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"}},Mi={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},Pe=Object.keys(z);function eo(e){return Mi[e.trim().toLowerCase()]??null}var ue="uat",Ba=z.uat.imsEndpoint,Ua=z.uat.terminologyServerEndpoint,Va=z.uat.authoringServicesEndpoint;var Bi=v(require("http")),Ui=v(require("https"));function x(e,t={}){let{method:r="GET",cookie:o,body:n,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(g){c(g);return}let l=d.protocol==="https:"?Ui:Bi,u=n!==void 0?JSON.stringify(n):void 0,p={accept:"application/json",...i};if(u!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(u))),o){let g=o.replace(/[^\x20-\x7e\t]/g,"");g&&(p.cookie=g)}let y=!1,k=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:p},g=>{let I="";g.on("data",E=>{I+=E}),g.on("end",()=>{if(y)return;y=!0,clearTimeout(h);let E=g.statusCode??0,N=(g.headers["content-type"]??"").includes("application/json"),O=null,$e=!1;if(I)try{O=JSON.parse(I)}catch{$e=!N}a({statusCode:E,body:O,rawBody:I,sessionExpired:$e})})});k.on("error",g=>{y||(y=!0,clearTimeout(h),c(g))});let h=setTimeout(()=>{y||(y=!0,k.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);u!==void 0&&k.write(u),k.end()})}var V="900000000000509007",Q="900000000000508004";var to={[V]:"en-us",[Q]:"en-gb"},oo={[V]:"true",[Q]:"true"},Vi={},qi={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:to,dialectDefaults:oo,readOnlyDialects:Vi,defaultLanguage:"en"};function no(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return qi;let t={[V]:"en-us"},r={},o={},n=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];t[String(e[c])]=l,n.length===0&&n.push(l)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[k,h]of Object.entries(c))k.length===2&&(d=k,l=String(h));if(!d||!l)continue;let u=c.dialectName;t[l]=typeof u=="string"?u:d;let p=c.default;p==="true"&&!n.includes(d)&&n.push(d),p!=null&&(r[l]=String(p));let y=c.readOnly;y!=null&&(o[l]=String(y))}let s=e.optionalLanguageRefsets;if(Array.isArray(s))for(let c of s)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?to:t,dialectDefaults:a?oo:r,readOnlyDialects:o,defaultLanguage:n[0]??"en"}}function lt(e,t,r,o){let n={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(o)?n[i]="PREFERRED":s.includes(e.defaultLanguage)&&(n[i]="ACCEPTABLE"):s.includes(o)&&(n[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete n[i],e.readOnlyDialects[i]==="true"&&delete n[i]}return n}function je(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[V]:"PREFERRED"}:lt(e,"PREFERRED",t,"en")}var Ji="900000000000207008";function ro(e){return e.replace(/\/$/,"")}function A(e){return ro(e.terminologyServerEndpoint)}function P(e){return ro(e.authoringServicesEndpoint)}function io(e){return`${new URL(P(e)).origin}/authoring-traceability-service`}function Z(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let o=t.projectKey||r?.projectKey,n=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!o||!n?{ok:!1,error:'No task context: pass --project/--task explicitly, or work in a named context ("--context <name>" with "select-task") or a pinned session (AUTHORING_CLI_TASK).'}:(s||(s=await ut(e,o,n)??void 0),s?{ok:!0,projectKey:o,taskKey:n,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${o}/${n}.`})}async function ee(e,t){let r=A(e),o=await x(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(o.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode>=200&&o.statusCode<300)return{ok:!0,created:!1};if(o.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${o.statusCode}).`};let n=t.split("/").filter(Boolean),i=n[n.length-1],s=n.slice(0,-1).join("/");if(!i||!s)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await x(`${r}/branches`,{method:"POST",body:{parent:s,name:i},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function ut(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body?.branchPath??null}async function so(e,t,r){let o=r?.get(t);if(o)return o;let n=`${P(e)}/projects/${t}`,s=(await x(n,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function B(e,t,r){let o=await so(e,t,r),n=o.multipleModuleEditingDisabled,i=!n||n==="false";return o.expectedExtensionModules?.length&&i?o.expectedExtensionModules[0]:o.defaultModuleId?o.defaultModuleId:Ji}async function te(e,t,r){let o=await so(e,t,r);return no(o)}async function oe(e,t){let r=e.replace(/\/$/,"")+"/auth",o=await x(r,{cookie:t,timeoutMs:8e3});return o.statusCode>=200&&o.statusCode<300&&o.body?o.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${o.statusCode} from ${r}`),null)}var co=v(require("crypto"));async function K(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body??null}function ao(e){let t=e?.trim();return t?t.toLowerCase():null}async function S(e,t){let r=ao(e.currentUsername);if(!r)return null;let o=await K(e,t.projectKey,t.taskKey),n=ao(o?.assignee?.username);return n?n!==r?{statusCode:403,body:{error:`Not allowed: ${t.projectKey}/${t.taskKey} is authored by "${n}", but the signed-in user is "${r}". Only the Task Author can make changes to a task, including classification.`}}:null:{statusCode:403,body:{error:`Task ${t.projectKey}/${t.taskKey} has no assignee. Only the Task Author may make changes to a task \u2014 including classification \u2014 and nobody is currently assigned.`}}}var Gi="116680003";function pe(e,t,r,o,n="PREFERRED",i=!1){let s=e==="FSN"?je(o,i):lt(o,n,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function lo(e,t,r,o=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let{projectKey:s,taskKey:a,branchPath:c}=n,d=Z(c),l=t.moduleId||await B(e,s,o),u=await te(e,s,o),p=t.preferredTerm||t.fsn,y=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,k={conceptId:null,moduleId:l,definitionStatus:"PRIMITIVE",active:!0,descriptions:[pe("FSN",y,l,u,"PREFERRED",!0),pe("SYNONYM",p,l,u,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:co.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:Gi},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${d}/${s}/${a}/concepts/?validate=true`,g=await x(h,{method:"POST",body:k,cookie:e.cookie});if(g.sessionExpired){let D="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: SESSION EXPIRED`),{statusCode:401,body:{error:D}}}let I=g.body,E=I&&"conceptId"in I?I.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: ${g.statusCode<300?"OK":"FAILED ("+g.statusCode+")"} \u2014 ${y}`+(E?` \u2192 ${E}`:"")),typeof E=="string"&&e.onValidationResults?.(E,I?.validationResults),{statusCode:g.statusCode,body:g.body}}var Hi=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],Wi={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function Yi(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(o=>o.active!==!1).length}function uo(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(o=>o.characteristicType===t)}function me(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function fe(e){return typeof e=="object"&&e!==null}function Xi(e,t,r){let o=Array.isArray(e[r])?e[r]:[],n=[];for(let i of o){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let d=a.type;if((fe(d)?d.conceptId:void 0)!==t)return;let u=a.target;n.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:fe(u)?u.conceptId:void 0,targetFsn:fe(u)&&fe(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return n}async function Ne(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};if(!t.attributeType){let a=Hi.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>Wi[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${o.branchPath}/concepts/${t.conceptId}`,c=await x(a,{cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:c.statusCode,body:c.body}}let n=`${A(e)}/browser/${o.branchPath}/concepts/${t.conceptId}`,i=await x(n,{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||!fe(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=Xi(s,t.attributeType,a);return{statusCode:i.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:c}}}if(t.descriptions){let a=Array.isArray(s.descriptions)?s.descriptions.filter(c=>c.active!==!1):[];return{statusCode:i.statusCode,body:{...me(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...me(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...me(s),classAxioms:s.classAxioms??[],relationships:uo(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...me(s),relationships:uo(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...me(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:Yi(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var zi=500,Qi=1e4;async function De(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n={expand:"fsn()"};t.term&&(n.termFilter=t.term),t.ecl&&(n.eclFilter=t.ecl),typeof t.active=="boolean"&&(n.activeFilter=t.active);let i=`${A(e)}/${o.branchPath}/concepts/search`,s=l=>({conceptId:l.conceptId,fsn:l.fsn?.term,pt:l.pt?.term,active:l.active,moduleId:l.moduleId});if(t.limit!==void 0){let l=await x(i,{method:"POST",body:{...n,limit:t.limit},cookie:e.cookie});if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let u=(l.body?.items??[]).map(s);return{statusCode:l.statusCode,body:{total:l.body?.total??u.length,items:u}}}let a=[],c=0,d=0;for(;;){let l=Math.min(zi,Qi-d);if(l<=0)break;let u=await x(i,{method:"POST",body:{...n,limit:l,offset:d},cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(u.statusCode<200||u.statusCode>=300)return{statusCode:u.statusCode,body:u.body??{error:"Concept search failed."}};let p=u.body?.items??[];if(a.push(...p.map(s)),c=u.body?.total??a.length,d+=p.length,p.length===0||d>=c)break}return{statusCode:200,body:{total:c,items:a,...a.length<c?{truncated:!0,message:`Only ${a.length} of ${c} matches returned \u2014 Snowstorm caps unsorted search at offset+limit 10,000. Narrow the query (--term/--ecl/--active) to see the rest.`}:{}}}}var ge=1e3;function Zi(e){let t=new Map;for(let r of e)for(let o of r){let n=o.referenceType?.conceptId??"",i=t.get(n);i?i.referencingConcepts=[...i.referencingConcepts??[],...o.referencingConcepts??[]]:t.set(n,{...o,referencingConcepts:[...o.referencingConcepts??[]]})}return[...t.values()]}async function po(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=`${A(e)}/${o.branchPath}/concepts/${t.conceptId}/references`,i=(l,u)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(l)),p.set("offset",String(u)),x(`${n}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let l=await i(t.limit??ge,t.offset??0);return l.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:l.statusCode,body:l.body}}let s=[],a=0,c=0,d=0;for(;;){let l=await i(ge,d);if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(l.statusCode<200||l.statusCode>=300)return{statusCode:l.statusCode,body:l.body??{error:"Could not fetch references."}};let u=l.body?.referencesByType??[];s.push(u),a=l.body?.total??a;let p=u.reduce((y,k)=>y+(k.referencingConcepts?.length??0),0);if(c+=p,p===0||p<ge||c>=a)break;d+=ge}return{statusCode:200,body:{total:a,limit:ge,offset:0,referencesByType:Zi(s)}}}var ft=v(require("crypto"));function mo(e){return typeof e=="object"&&e!==null}function es(e){let t=e.type,r=e.target,o=mo(t)?t.conceptId:void 0,n=mo(r)?r.conceptId:void 0;return typeof o=="string"&&typeof n=="string"?{typeId:o,targetId:n}:null}function ts(e,t){let r=[...t];for(let o of e){let n=r.findIndex(i=>i.typeId===o.typeId&&i.targetId===o.targetId);if(n===-1)return!1;r.splice(n,1)}return!0}function fo(e,t,r){let o=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=o.get(a);c?c.push(s):o.set(a,[s])}let n=[];for(let[s,a]of o){if(r!=null?s!==r:s===0)continue;let c=a.map(es).filter(d=>d!=null);ts(t,c)&&n.push(s)}if(n.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(n.length>1)return{ok:!1,statusCode:409,error:`has ${n.length} role groups matching the given attributes (groupIds: ${n.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let i=n[0];return{ok:!0,groupId:i,relationships:o.get(i)}}var os=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],ns=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],rs=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],is=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],ss=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],gt=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function So(e){return gt.includes(e)}function ye(e,t){let r={};for(let o of t)o in e&&(r[o]=e[o]);return r}function Oe(e){return typeof e=="object"&&e!==null}function go(e){return Oe(e)?ye(e,is):e}function wo(e){if(!Oe(e))return e;let t=ye(e,rs);return"type"in t&&(t.type=go(t.type)),"target"in t&&(t.target=go(t.target)),t}function as(e){return Oe(e)?ye(e,ns):e}function yo(e){if(!Oe(e))return e;let t=ye(e,ss);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(wo)),t}function yt(e){let t=ye(e,os);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(as)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(wo)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(yo)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(yo)),t}function cs(e){return new Promise(t=>setTimeout(t,e))}function ds(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var pt=[300,600,1200,2400,4800],ho=new Map;function ls(e,t){let o=(ho.get(e)??Promise.resolve()).then(t,t);return ho.set(e,o.then(()=>{},()=>{})),o}async function $(e,t,r,o){try{return await ls(t.branchPath,()=>us(e,t,r,o))}catch(n){return{statusCode:500,body:{error:n instanceof Error?n.message:String(n)}}}}async function us(e,t,r,o){for(let n=0;;n++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,d=o(c);if(d)return d;let l=Z(t.branchPath),u=`${i}/browser/${l}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await x(u,{method:"PUT",body:yt(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(ds(p)&&n<pt.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${n+1}/${pt.length})`),await cs(pt[n]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let y=p.body;return e.onValidationResults?.(r,y?.validationResults),{statusCode:p.statusCode,body:p.body}}}var ko=["PREFERRED","ACCEPTABLE"];async function To(e,t,r,o=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&&!ko.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${ko.join(", ")}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[];return l.push(pe(t.type,c,s,a,t.acceptability??"ACCEPTABLE",!1)),d.descriptions=l,null})}async function Ao(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=t.axiomIndex??0;return $(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];if(!c)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}};let d=Array.isArray(c.relationships)?c.relationships:[];return d.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),c.relationships=d,null})}async function Ro(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=t.axiomIndex??0;return $(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];return c?(c.definitionStatus=t.status,s.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}}})}async function $o(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>i.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(i.active=!1,i.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(i.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null))}async function Eo(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&&!So(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(a.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(a.term=t.term),t.caseSignificance&&(a.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Po(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!So(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?(a.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}var mt=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Co(e){return mt.includes(e)}function jo(e){return e.us&&!Co(e.us)?{statusCode:400,body:{error:`us must be one of: ${mt.join(", ")}.`}}:e.gb&&!Co(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${mt.join(", ")}.`}}:null}function No(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.`}}:jo(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function ht(e,t,r){let o=e.find(i=>i.descriptionId===r.descriptionId);if(!o)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(o.lang=r.lang);let n={...o.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete n[V]:n[V]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete n[Q]:n[Q]=r.gb),o.active!==!1&&Object.keys(n).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.`}}:(o.acceptabilityMap=n,null)}async function Do(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},n=No(o);if(n)return n;let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await S(e,i);return s||$(e,i,t.conceptId,a=>{let c=Array.isArray(a.descriptions)?a.descriptions:[];return ht(c,t.conceptId,o)})}async function Oo(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 i of t.entries){let s=No(i);if(s)return s}let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[];for(let a of t.entries){let c=ht(s,t.conceptId,a);if(c)return c}return null})}async function Fo(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[],a=s.findIndex(c=>c.descriptionId===t.descriptionId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(s.splice(a,1),i.descriptions=s,null)})}var Fe="REFERS_TO";async function Lo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(a.active=!1,a.inactivationIndicator=t.indicator,a.acceptabilityMap={},t.associationTargetId&&(a.associationTargets={[Fe]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}function xo(e,t,r){for(let o of e){if(o.descriptionId===t||o.active===!1||o.type!=="SYNONYM")continue;let n=o.acceptabilityMap;n?.[r]==="PREFERRED"&&(o.acceptabilityMap={...n,[r]:"ACCEPTABLE"})}}async function Ko(e,t,r,o=new Map){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},i=jo(n);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await C(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await S(e,a);if(c)return c;let d=await te(e,a.projectKey,o);return $(e,a,t.conceptId,l=>{let u=Array.isArray(l.descriptions)?l.descriptions:[],p=u.find(k=>k.descriptionId===t.descriptionId);if(!p)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(p.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(p.type==="FSN"){if(s)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let k=u.filter(h=>h.type==="FSN"&&h.active!==!1&&h.descriptionId!==t.descriptionId);if(k.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${k.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(k.length===1){let h=k[0];if(h.effectiveTime==null)u.splice(u.indexOf(h),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(h.descriptionId)} in the same save.`}};h.active=!1,h.inactivationIndicator=t.indicator,h.acceptabilityMap={},t.associationTargetId&&(h.associationTargets={[Fe]:[t.associationTargetId]})}}return p.active=!0,delete p.inactivationIndicator,delete p.associationTargets,p.acceptabilityMap=je(d,!1),l.descriptions=u,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};p.active=!0,delete p.inactivationIndicator,delete p.associationTargets;let y=ht(u,t.conceptId,n);return y||(n.us==="PREFERRED"&&xo(u,t.descriptionId,V),n.gb==="PREFERRED"&&xo(u,t.descriptionId,Q),null)})}var ps="900000000000490003",Io=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function _o(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!Io.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${Io.join(", ")}.`}};if(t.reason==="NOT_SEMANTICALLY_EQUIVALENT"){if(!t.targetId)return{statusCode:400,body:{error:"reason NOT_SEMANTICALLY_EQUIVALENT requires --target-id \u2014 the concept this description actually belongs under."}}}else if(t.targetId)return{statusCode:400,body:{error:`--target-id only applies to reason NOT_SEMANTICALLY_EQUIVALENT (paired with a REFERS_TO association) \u2014 omit it for ${t.reason}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${ps}&active=true`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:a.body}};let c=(a.body.items??[])[0];return c?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(c.effectiveTime)}) and cannot be changed.`}}:$(e,o,t.conceptId,d=>{let u=(Array.isArray(d.descriptions)?d.descriptions:[]).find(p=>p.descriptionId===t.descriptionId);return u?u.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(u.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?u.associationTargets={[Fe]:[t.targetId]}:delete u.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Mo(e,t,r,o=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[],u;if(t.descriptionId){if(u=l.find(p=>p.descriptionId===t.descriptionId),!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(u.type)}, not an FSN.`}}}else{let p=l.filter(y=>y.type==="FSN"&&y.active!==!1);if(p.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${p.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};u=p[0]}return u.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(u.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(u.active=!1,u.inactivationIndicator=t.indicator,u.acceptabilityMap={},t.associationTargetId&&(u.associationTargets={[Fe]:[t.associationTargetId]}),l.push(pe("FSN",c,s,a,"PREFERRED",!1)),d.descriptions=l,null)})}function Bo(e,t,r){return $(e,t,r.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(s=>s.axiomId===r.axiomId);return i?(i.relationships=r.relationships,r.active!=null&&(i.active=r.active),null):{statusCode:404,body:{error:`Concept ${r.conceptId} has no class axiom ${r.axiomId}.`}}})}async function Uo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||Bo(e,o,t)}async function Vo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.gciAxioms)?i.gciAxioms:[]).find(c=>c.axiomId===t.axiomId);return a?(a.relationships=t.relationships,t.active!=null&&(a.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}})}async function qo(e,t,r,o=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.classAxioms)?a.classAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.classAxioms=c,null})}async function Jo(e,t,r,o=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 n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.gciAxioms)?a.gciAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.gciAxioms=c,null})}async function Go(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(s.splice(a,1),i.classAxioms=s,null)})}async function Ho(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(a.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(a.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:c.every(d=>d.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished class axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-axiom to edit ${t.axiomId}'s content in place instead.`}}:(a.active=!1,null)})}var ms="116680003";function bo(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function fs(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let i of r)i?.id&&t.push({active:!0,groupId:0,type:{conceptId:ms},target:{conceptId:i.id}});let o=Array.isArray(e.attributes)?e.attributes:[];for(let i of o)t.push(bo(i,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((i,s)=>{let a=Array.isArray(i.attributes)?i.attributes:[];for(let c of a)t.push(bo(c,s+1))}),t}async function Wo(e,t,r,o){let n=A(e),i=await x(`${n}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(i.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{ok:!1,result:{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body,undetermined:!0}}};let s=Array.isArray(i.body.classAxioms)?i.body.classAxioms:[],a;if(o){if(a=s.find(c=>c.axiomId===o),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${o}.`,undetermined:!0}}}}else{let c=s.filter(d=>d.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var gs="116680003";function ys(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==gs?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function hs(e,t,r){let o=A(e),n=await x(`${o}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(n.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(n.statusCode<200||n.statusCode>=300||!n.body)return{ok:!1,result:{statusCode:n.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:n.body,undetermined:!0}}};let i=fs(n.body);return i.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`,undetermined:!0}}}:{ok:!0,value:i}}async function ks(e,t,r,o){let n=await Wo(e,t,r,o);if(!n.ok)return n;let i=await hs(e,t,r);return i.ok?{ok:!0,value:{axiom:n.value.axiom,axiomId:n.value.axiomId,targetRelationships:i.value}}:i}function Cs(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let o=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${o}`}function vo(e){let t=new Map;for(let n of e){if(n.active===!1)continue;let i=typeof n.groupId=="number"?n.groupId:0,s=t.get(i)??[];s.push(Cs(n)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),o=[];for(let[n,i]of t)n!==0&&o.push(i.slice().sort());return{ungrouped:r,groups:o}}function xs(e,t){let r=vo(e),o=vo(t);if(r.ungrouped.join("|")!==o.ungrouped.join("|"))return!1;let n=r.groups.map(s=>s.join("|")).sort(),i=o.groups.map(s=>s.join("|")).sort();return n.join("||")===i.join("||")}async function Yo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=await ks(e,o,t.conceptId,t.axiomId);if(!i.ok)return i.result;let{axiom:s,axiomId:a,targetRelationships:c}=i.value,d=Array.isArray(s.relationships)?s.relationships:[];return xs(d,c)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${o.projectKey}/${o.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:a,alreadyConformed:!0}}):Bo(e,o,{conceptId:t.conceptId,axiomId:a,relationships:c})}async function Le(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Wo(e,o,t.conceptId,t.axiomId);if(!n.ok)return n.result;let{axiom:i,axiomId:s}=n.value,a=Array.isArray(i.relationships)?i.relationships:[];return ys(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function Xo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=t.relationshipId?c.findIndex(u=>u.relationshipId===t.relationshipId):t.relationshipIndex,l=d>=0?c[d]:void 0;return l?l.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${d}`} has effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(c.splice(d,1),a.relationships=c,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}})}async function zo(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 i of t.attributes)if(!i||typeof i.typeId!="string"||typeof i.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=fo(c,t.attributes,t.groupId);if(!d.ok)return{statusCode:d.statusCode,body:{error:`Axiom ${t.axiomId} ${d.error}`}};let l=d.relationships.find(u=>u.effectiveTime!=null);return l?{statusCode:409,body:{error:`Role group (groupId ${d.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(l.relationshipId)}) with effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.relationships=c.filter(u=>(typeof u.groupId=="number"?u.groupId:0)!==d.groupId),null)})}async function Qo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(s.splice(a,1),i.gciAxioms=s,null)})}async function Zo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(a.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}};if(a.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length>0&&c.every(d=>d.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating GCI axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished GCI axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-gci-axiom to edit ${t.axiomId}'s content in place instead.`}}:(a.active=!1,null)})}var Is=8;async function Ke(e,t,r,o){let n=[],i=[],s=0,a=async()=>{for(;;){let d=s++;if(d>=r.length)return;let l=r[d];try{let u=await Le(e,{conceptId:l.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),p=u.body;if(u.statusCode<200||u.statusCode>=300){i.push({...l,error:p?.error??`HTTP ${u.statusCode}`});continue}p?.conclusive&&n.push({...l,axiomId:p.axiomId})}catch(u){i.push({...l,error:u instanceof Error?u.message:String(u)})}}},c=Math.min(Is,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:n,skipped:i}}async function en(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await De(e,{...t,branchPath:o.branchPath},r);if(n.statusCode<200||n.statusCode>=300)return n;let i=n.body?.items??[],s=i.map(d=>({conceptId:d.conceptId,fsn:d.fsn,pt:d.pt})),{matched:a,skipped:c}=await Ke(e,o,s,r);return{statusCode:200,body:{branchPath:o.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function tn(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=A(e),s=`${i}/browser/${o.branchPath}/concepts/${t.conceptId}`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:a.body}};if(a.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let c=`${i}/${o.branchPath}/concepts/${t.conceptId}`,d=await x(c,{method:"DELETE",cookie:e.cookie});return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${o.projectKey}/${o.taskKey}: ${d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.conceptId}`),d.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:d.body}}:{statusCode:d.statusCode,body:d.body})}var he="733073007",on=["Import","SubClassOf","EquivalentClasses","DisjointClasses","DisjointUnion","Annotation","AnnotationAssertion","SubAnnotationPropertyOf","AnnotationPropertyDomain","AnnotationPropertyRange","HasKey","Declaration","InverseObjectProperties","DatatypeDefinition","SubObjectPropertyOf","EquivalentObjectProperties","DisjointObjectProperties","ObjectPropertyDomain","ObjectPropertyRange","FunctionalObjectProperty","InverseFunctionalObjectProperty","ReflexiveObjectProperty","IrreflexiveObjectProperty","SymmetricObjectProperty","AsymmetricObjectProperty","TransitiveObjectProperty","SubDataPropertyOf","EquivalentDataProperties","DisjointDataProperties","DataPropertyDomain","DataPropertyRange","FunctionalDataProperty","SameIndividual","DifferentIndividuals","ClassAssertion","ObjectPropertyAssertion","NegativeObjectPropertyAssertion","DataPropertyAssertion","NegativeDataPropertyAssertion","DLSafeRule"];function bs(e){let t=e.trim(),r=0;for(let n of t)if(n==="(")r+=1;else if(n===")"&&(r-=1,r<0))return"Unbalanced parentheses in OWL expression (an unmatched ')' ) \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.";if(r!==0)return`Unbalanced parentheses in OWL expression (${r} unclosed '(') \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.`;let o=/^([A-Za-z]+)\s*\(/.exec(t)?.[1];return!o||!on.includes(o)?`OWL expression doesn't start with a recognized top-level axiom keyword${o?` (saw "${o}")`:""} \u2014 expected one of ${on.slice(0,6).join(", ")}, ... Refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly. This is only a shallow keyword/paren check, not a real OWL parser \u2014 passing it doesn't guarantee the expression is actually valid.`:null}async function nn(e,t,r,o=new Map){if(!t.propertyId)return{statusCode:400,body:{error:"propertyId is required."}};if(!t.owlExpression||!t.owlExpression.trim())return{statusCode:400,body:{error:"owlExpression is required."}};let n=bs(t.owlExpression);if(n)return{statusCode:400,body:{error:n}};let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await S(e,i);if(s)return s;let a=t.moduleId||await B(e,i.projectKey,o),d=`${A(e)}/${i.branchPath}/members`,l=await x(d,{method:"POST",cookie:e.cookie,body:{active:!0,moduleId:a,refsetId:he,referencedComponentId:t.propertyId,additionalFields:{owlExpression:t.owlExpression}}});return l.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] add-property-axiom ${i.projectKey}/${i.taskKey}: ${l.statusCode>=200&&l.statusCode<300?"OK":"FAILED ("+l.statusCode+")"} \u2014 ${t.propertyId}`),{statusCode:l.statusCode,body:l.body})}async function rn(e,t,r,o=200,n=0){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let a=`${A(e)}/${i.branchPath}/members?referencedComponentId=${encodeURIComponent(t.conceptId)}&referenceSet=${he}&limit=${o}&offset=${n}`;t.activeOnly&&(a+="&active=true");let c=await x(a,{cookie:e.cookie});if(c.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(c.statusCode<200||c.statusCode>=300||!c.body)return{statusCode:c.statusCode||500,body:{error:`Could not fetch property axioms for ${t.conceptId}.`,details:c.body}};let l=(c.body.items??[]).map(u=>({memberId:u.memberId,active:u.active,released:u.released,effectiveTime:u.effectiveTime??null,moduleId:u.moduleId,owlExpression:u.additionalFields?.owlExpression??null}));return{statusCode:200,body:{conceptId:t.conceptId,refsetId:he,total:c.body.total??l.length,axioms:l}}}async function sn(e,t,r){if(!t.conceptId||!t.memberId)return{statusCode:400,body:{error:"conceptId and memberId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members/${encodeURIComponent(t.memberId)}`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode===404)return{statusCode:404,body:{error:`No reference set member ${t.memberId} on this branch.`}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||500,body:{error:`Could not fetch property axiom ${t.memberId}.`,details:a.body}};let c=a.body;if(c.refsetId!==he)return{statusCode:400,body:{error:`Member ${t.memberId} is not an OWL Axiom reference set member (refsetId ${String(c.refsetId??"unknown")}) \u2014 delete-property-axiom only removes members of refset ${he}.`}};if(String(c.referencedComponentId)!==t.conceptId)return{statusCode:400,body:{error:`Member ${t.memberId} belongs to concept ${String(c.referencedComponentId)}, not ${t.conceptId} \u2014 refusing to delete; double check the conceptId/memberId pair against get-property-axioms output.`}};let d=await x(s,{method:"DELETE",cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(e.onLog?.(`[${new Date().toISOString()}] delete-property-axiom ${o.projectKey}/${o.taskKey}: ${d.statusCode>=200&&d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.memberId}`),d.statusCode>=200&&d.statusCode<300){let l=c.additionalFields;return{statusCode:200,body:{deleted:!0,conceptId:t.conceptId,memberId:t.memberId,owlExpression:l?.owlExpression??null}}}return{statusCode:d.statusCode,body:d.body??{error:`Failed to delete property axiom ${t.memberId}.`}}}function vs(e){let t=[];for(let r of e)t.some(n=>n.componentId===r.componentId&&n.severity===r.severity&&n.conceptId===r.conceptId&&n.message===r.message)||t.push(r);return t}async function _e(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=A(e),i=`${n}/browser/${o.branchPath}/concepts/${t.conceptId}`,s=await x(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};let a=Z(o.branchPath),c=`${n}/browser/${a}/${o.projectKey}/${o.taskKey}/validate/concept`,d=await x(c,{method:"POST",body:yt(s.body),cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let l=Array.isArray(d.body)?vs(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 an=200;async function Ss(e,t,r){let o=new Map;if(r.length===0)return{terms:o,resolved:!0};let n=`${A(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=an){let a=r.slice(s,s+an),c=await x(n,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let d of c.body)o.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:o,resolved:i}}async function q(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=[],i=0;for(;;){let h=`${io(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(o.branchPath)}`,g=await x(h,{cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(g.statusCode===404)return{statusCode:200,body:{branchPath:o.branchPath,concepts:[],conceptsClassified:[]}};if(g.statusCode<200||g.statusCode>=300)return{statusCode:g.statusCode,body:{error:"Could not fetch traceability for branch.",details:g.body}};n.push(...g.body?.content??[]);let I=g.body?.totalPages??1;if(g.body?.last!==!1||i+1>=I)break;i+=1}let s=new Map,a=new Map,c=(h,g,I,E)=>{let D=h.get(g);D?(E.forEach(N=>N&&D.componentSubTypes.add(N)),D.lastUpdatedTime=I):h.set(g,{conceptId:g,lastUpdatedTime:I,componentSubTypes:new Set(E.filter(N=>!!N))})};for(let h of n)if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let g of h.conceptChanges??[]){let I=String(g.conceptId),E=g.componentChanges??[],D=E.map(O=>O.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,I,h.commitDate,D);continue}let N=E.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(N?s:a,I,h.commitDate,D)}for(let h of s.keys())a.delete(h);let d=[...new Set([...s.keys(),...a.keys()])],{terms:l,resolved:u}=await Ss(e,o.branchPath,d),p=h=>[...h.values()].sort((g,I)=>(I.lastUpdatedTime??"").localeCompare(g.lastUpdatedTime??"")).map(g=>{let I=u&&!l.has(g.conceptId);return{conceptId:g.conceptId,fsn:l.get(g.conceptId)?.fsn,pt:l.get(g.conceptId)?.pt,...I?{deleted:!0}:{},lastUpdatedTime:g.lastUpdatedTime,changedComponentTypes:[...g.componentSubTypes]}}),y=p(s),k=p(a);return{statusCode:200,body:{branchPath:o.branchPath,...u?{summary:{concepts:y.length,conceptsDeleted:y.filter(h=>h.deleted).length,conceptsClassified:k.length}}:{},concepts:y,conceptsClassified:k}}}async function cn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let l=n.body;return{statusCode:n.statusCode,body:{error:l.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=i.filter(l=>!l.deleted),a=s.map(l=>({conceptId:l.conceptId,fsn:l.fsn})),{matched:c,skipped:d}=await Ke(e,o,a,r);return{statusCode:200,body:{branchPath:o.branchPath,totalReviewed:s.length,matched:c.length,skipped:d.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:d}}}async function ws(e,t,r,o){let n=[];for(let i of r){if(i.deleted){n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await _e(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),a=s.body;if(s.statusCode<200||s.statusCode>=300){n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return n}async function dn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=await ws(e,o,i,r),a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.branchPath,summary:{total:s.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:s}}}async function ln(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=[];for(let[c,d]of i.entries()){if(d.deleted){s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"deleted"});continue}let l=await Ne(e,{conceptId:d.conceptId,projectKey:o.projectKey,taskKey:o.taskKey,branchPath:o.branchPath},r),u=l.body,p=`(${c+1}/${i.length})`;if(l.statusCode<200||l.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: FAILED (${l.statusCode}) \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"failed",error:u?.error??`HTTP ${l.statusCode}`});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: OK \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"fetched",concept:l.body})}let a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.branchPath,summary:{total:s.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:s}}}var kt=new Set;function un(e){if(!(!e||typeof e!="object"))for(let t of kt)t(e)}function Ts(e){return kt.add(e),()=>kt.delete(e)}function As(e,t){return t.entityType!==void 0&&e.entityType!==t.entityType?!1:e.task?e.task===t.taskKey&&e.project===t.projectKey:e.project?e.project===t.projectKey:e.branchPath===t.branchPath}function Me(e){let t=()=>{};return{promise:new Promise(o=>{t=Ts(n=>{As(n,e)&&(t(),o(n))})}),cancel:t}}var bt=["RUNNING","BUILDING","SCHEDULED","QUEUED"],vt=["QUEUED","SCHEDULED","RUNNING"],Rs=["Promoted","Completed"],pn=5e3;function It(e){return new Promise(t=>setTimeout(t,e))}async function $s(e,t,r){let o=0;for(;;){let{done:n,value:i}=await e();if(n)return{value:i,timedOut:!1};if(o>=r)return{value:i,timedOut:!0};o++,await It(t)}}function Es(){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 Ps=Es(),js=180;function Ns(){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 Ds=Ns(),Os=900;async function gn(e,t,r,o,n){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=o?Me(o):void 0,l=await Promise.race(d?[It(c).then(()=>{}),d.promise]:[It(c).then(()=>{})]);if(d?.cancel(),l){let y=l.event;n?.(`[${new Date().toISOString()}] woken by notification${y?`: ${y}`:""}`)}let{done:u,value:p}=await e();if(u)return{value:p,timedOut:!1};if(Date.now()-s>=i)return{value:p,timedOut:!0};a++}}async function yn(e,t,r){let o=await K(e,t,r);if(!o)return{error:`Could not fetch task ${t}/${r}.`};if(o.status&&Rs.includes(o.status))return{error:`Task ${t}/${r} is ${o.status} \u2014 cannot start a new job.`};if(o.status==="New"){let n=`${P(e)}/projects/${t}/tasks/${r}`;await x(n,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function St(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await x(o,{method:"POST",body:{},cookie:e.cookie}),(await K(e,t,r))?.latestClassificationJson}async function mn(e,t,r,o,n){let i,{value:s,timedOut:a}=await gn(async()=>{let d=(await St(e,t,r))?.status;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||bt.includes(d)),value:d}},Ps,n,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function Ct(e,t,r){let o=`${A(e)}/${t}/classifications`,n=await x(o,{cookie:e.cookie});if(n.body?.items?.length)return n.body.items.find(i=>i.id===r)??n.body.items[n.body.items.length-1]}async function hn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,s=await St(e,n,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:bt.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function kn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let{projectKey:i,taskKey:s,branchPath:a}=o,c=await yn(e,i,s);if(c.error)return{statusCode:400,body:{error:c.error}};let d=t.timeoutSeconds??js,l=await St(e,i,s),u=l?.status,p=l?.id;if(p&&u&&bt.includes(u)){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:N,timedOut:O}=await mn(e,i,s,a,d),$e=await Ct(e,a,p),dt={accepted:!1};return!O&&N==="COMPLETED"&&(dt=await xt(e,a,i,s,p)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: attached job ${p} final status ${N??"unknown"}${O?" (timed out waiting)":""}, save ${JSON.stringify(dt)}`),{statusCode:200,body:{jobId:p,finalStatus:N,timedOut:O,details:$e,save:dt,attachedToExisting:!0}}}if(p&&u==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let N=await Ct(e,a,p),O=await xt(e,a,i,s,p);return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: accepted existing job ${p}, save ${JSON.stringify(O)}`),{statusCode:200,body:{jobId:p,finalStatus:"COMPLETED",timedOut:!1,details:N,save:O,acceptedExisting:!0}}}let y=`${P(e)}/projects/${i}/tasks/${s}/classifications`,k=await x(y,{method:"POST",body:{},cookie:e.cookie});if(k.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!k.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: start failed (HTTP ${k.statusCode}) \u2014 raw body: ${k.rawBody}`),{statusCode:k.statusCode||500,body:{error:"Failed to start classification.",details:k.body??k.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: started (${k.body.status??"unknown"})`);let h=k.body.id;if(!t.wait)return{statusCode:200,body:{jobId:h,status:k.body.status}};let{finalStatus:g,timedOut:I}=await mn(e,i,s,a,d),E=await Ct(e,a,h),D={accepted:!1};return!I&&g==="COMPLETED"&&(D=await xt(e,a,i,s,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: final status ${g??"unknown"}${I?" (timed out waiting)":""}, save ${JSON.stringify(D)}`),{statusCode:200,body:{jobId:h,finalStatus:g,timedOut:I,details:E,save:D}}}var Fs=["SAVED","STALE","SAVE_FAILED"],Ls=120;async function xt(e,t,r,o,n){let i=`${A(e)}/${t}/classifications/${n}`,s=await x(i,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(s.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(s.statusCode<200||s.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${s.statusCode}).`};let a=Math.ceil(Ls*1e3/pn),{value:c,timedOut:d}=await $s(async()=>{let u=(await x(i,{cookie:e.cookie})).body?.status;return{done:!!u&&Fs.includes(u),value:u}},pn,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 Cn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,a=(await K(e,n,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&vt.includes(a)}}}async function fn(e,t,r,o,n){let i,{value:s,timedOut:a}=await gn(async()=>{let d=(await K(e,t,r))?.latestValidationStatus;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||vt.includes(d)),value:d}},Ds,n,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function xn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=await yn(e,n,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Os,l=(await K(e,n,i))?.latestValidationStatus;if(l&&vt.includes(l)){e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:h,timedOut:g}=await fn(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: attached run final status ${h??"unknown"}${g?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:h,timedOut:g,attachedToExisting:!0}}}let u=`${P(e)}/projects/${n}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await x(u,{method:"POST",body:{},cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(p.statusCode<200||p.statusCode>=300)return{statusCode:p.statusCode,body:{error:"Failed to start validation.",details:p.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:y,timedOut:k}=await fn(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: final status ${y??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:y,timedOut:k}}}async function In(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",o=`${P(e)}/projects${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function bn(e,t){let r=`${P(e)}/projects/${t}/tasks`;return(await x(r,{cookie:e.cookie})).body??[]}async function vn(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",o=`${P(e)}/projects/my-tasks${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function Sn(e,t){let r=`${P(e)}/projects/${t.projectKey}/tasks`,o={summary:t.summary};t.description!==void 0&&(o.description=t.description),t.assigneeUsername&&(o.assignee={username:t.assigneeUsername});let n=await x(r,{method:"POST",body:o,cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}async function wn(e,t){let r=`${P(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,o=await x(r,{cookie:e.cookie});return Array.isArray(o.body)?o.body:[]}var Ks="IN_PROGRESS";async function Tn(e,t){let r=`${P(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,o=await x(r,{cookie:e.cookie});if(o.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode<200||o.statusCode>=300||!o.body)return{statusCode:o.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode}).`};if(o.body.status!=="Deleted")return{statusCode:200,task:o.body,notDeleted:!0};let n=await x(r,{method:"PUT",body:{status:Ks},cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}function An(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 wt(e){return JSON.stringify([e])}function Rn(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",o="";for(let n=0;n<8;n++)o+=r[Math.floor(e()*r.length)];return`${t}/${o}/websocket`}function Tt(e,t={},r=""){let o=Object.entries(t).map(([n,i])=>`${n}:${i}`);return[e,...o,"",r].join(`
3
- `)+"\0"}function $n(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
2
+ "use strict";var Li=Object.create;var $e=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var Mi=Object.getPrototypeOf,Bi=Object.prototype.hasOwnProperty;var Ui=(e,t)=>{for(var r in t)$e(e,r,{get:t[r],enumerable:!0})},eo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ki(t))!Bi.call(e,n)&&n!==r&&$e(e,n,{get:()=>t[n],enumerable:!(o=_i(t,n))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?Li(Mi(e)):{},eo(t||!e||!e.__esModule?$e(r,"default",{value:e,enumerable:!0}):r,e)),Vi=e=>eo($e({},"__esModule",{value:!0}),e);var Wa={};Ui(Wa,{COMMANDS:()=>Zt,main:()=>Fi,parsePositionals:()=>Di});module.exports=Vi(Wa);var z={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"}},qi={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},Ee=Object.keys(z);function to(e){return qi[e.trim().toLowerCase()]??null}var ue="uat",Xa=z.uat.imsEndpoint,za=z.uat.terminologyServerEndpoint,Qa=z.uat.authoringServicesEndpoint;var Hi=S(require("http")),Ji=S(require("https"));function x(e,t={}){let{method:r="GET",cookie:o,body:n,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(g){c(g);return}let l=d.protocol==="https:"?Ji:Hi,u=n!==void 0?JSON.stringify(n):void 0,p={accept:"application/json",...i};if(u!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(u))),o){let g=o.replace(/[^\x20-\x7e\t]/g,"");g&&(p.cookie=g)}let y=!1,k=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:p},g=>{let I="";g.on("data",E=>{I+=E}),g.on("end",()=>{if(y)return;y=!0,clearTimeout(h);let E=g.statusCode??0,N=(g.headers["content-type"]??"").includes("application/json"),O=null,Re=!1;if(I)try{O=JSON.parse(I)}catch{Re=!N}a({statusCode:E,body:O,rawBody:I,sessionExpired:Re})})});k.on("error",g=>{y||(y=!0,clearTimeout(h),c(g))});let h=setTimeout(()=>{y||(y=!0,k.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);u!==void 0&&k.write(u),k.end()})}var V="900000000000509007",Q="900000000000508004";var oo={[V]:"en-us",[Q]:"en-gb"},no={[V]:"true",[Q]:"true"},Gi={},Wi={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:oo,dialectDefaults:no,readOnlyDialects:Gi,defaultLanguage:"en"};function ro(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Wi;let t={[V]:"en-us"},r={},o={},n=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];t[String(e[c])]=l,n.length===0&&n.push(l)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[k,h]of Object.entries(c))k.length===2&&(d=k,l=String(h));if(!d||!l)continue;let u=c.dialectName;t[l]=typeof u=="string"?u:d;let p=c.default;p==="true"&&!n.includes(d)&&n.push(d),p!=null&&(r[l]=String(p));let y=c.readOnly;y!=null&&(o[l]=String(y))}let s=e.optionalLanguageRefsets;if(Array.isArray(s))for(let c of s)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?oo:t,dialectDefaults:a?no:r,readOnlyDialects:o,defaultLanguage:n[0]??"en"}}function lt(e,t,r,o){let n={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(o)?n[i]="PREFERRED":s.includes(e.defaultLanguage)&&(n[i]="ACCEPTABLE"):s.includes(o)&&(n[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete n[i],e.readOnlyDialects[i]==="true"&&delete n[i]}return n}function Pe(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[V]:"PREFERRED"}:lt(e,"PREFERRED",t,"en")}var Yi="900000000000207008";function io(e){return e.replace(/\/$/,"")}function A(e){return io(e.terminologyServerEndpoint)}function P(e){return io(e.authoringServicesEndpoint)}function so(e){return`${new URL(P(e)).origin}/authoring-traceability-service`}function Z(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let o=t.projectKey||r?.projectKey,n=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!o||!n?{ok:!1,error:'No task context: pass --project/--task explicitly, or work in a named context ("--context <name>" with "select-task") or a pinned session (AUTHORING_CLI_TASK).'}:(s||(s=await ut(e,o,n)??void 0),s?{ok:!0,projectKey:o,taskKey:n,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${o}/${n}.`})}async function ee(e,t){let r=A(e),o=await x(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(o.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode>=200&&o.statusCode<300)return{ok:!0,created:!1};if(o.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${o.statusCode}).`};let n=t.split("/").filter(Boolean),i=n[n.length-1],s=n.slice(0,-1).join("/");if(!i||!s)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await x(`${r}/branches`,{method:"POST",body:{parent:s,name:i},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function ut(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body?.branchPath??null}async function ao(e,t,r){let o=r?.get(t);if(o)return o;let n=`${P(e)}/projects/${t}`,s=(await x(n,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function B(e,t,r){let o=await ao(e,t,r),n=o.multipleModuleEditingDisabled,i=!n||n==="false";return o.expectedExtensionModules?.length&&i?o.expectedExtensionModules[0]:o.defaultModuleId?o.defaultModuleId:Yi}async function te(e,t,r){let o=await ao(e,t,r);return ro(o)}async function oe(e,t){let r=e.replace(/\/$/,"")+"/auth",o=await x(r,{cookie:t,timeoutMs:8e3});return o.statusCode>=200&&o.statusCode<300&&o.body?o.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${o.statusCode} from ${r}`),null)}var lo=S(require("crypto"));async function _(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body??null}function co(e){let t=e?.trim();return t?t.toLowerCase():null}async function w(e,t){let r=co(e.currentUsername);if(!r)return null;let o=await _(e,t.projectKey,t.taskKey),n=co(o?.assignee?.username);return n?n!==r?{statusCode:403,body:{error:`Not allowed: ${t.projectKey}/${t.taskKey} is authored by "${n}", but the signed-in user is "${r}". Only the Task Author can make changes to a task, including classification.`}}:null:{statusCode:403,body:{error:`Task ${t.projectKey}/${t.taskKey} has no assignee. Only the Task Author may make changes to a task \u2014 including classification \u2014 and nobody is currently assigned.`}}}var Xi="116680003";function pe(e,t,r,o,n="PREFERRED",i=!1){let s=e==="FSN"?Pe(o,i):lt(o,n,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function uo(e,t,r,o=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await w(e,n);if(i)return i;let{projectKey:s,taskKey:a,branchPath:c}=n,d=Z(c),l=t.moduleId||await B(e,s,o),u=await te(e,s,o),p=t.preferredTerm||t.fsn,y=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,k={conceptId:null,moduleId:l,definitionStatus:"PRIMITIVE",active:!0,descriptions:[pe("FSN",y,l,u,"PREFERRED",!0),pe("SYNONYM",p,l,u,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:lo.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:Xi},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${d}/${s}/${a}/concepts/?validate=true`,g=await x(h,{method:"POST",body:k,cookie:e.cookie});if(g.sessionExpired){let D="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: SESSION EXPIRED`),{statusCode:401,body:{error:D}}}let I=g.body,E=I&&"conceptId"in I?I.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: ${g.statusCode<300?"OK":"FAILED ("+g.statusCode+")"} \u2014 ${y}`+(E?` \u2192 ${E}`:"")),typeof E=="string"&&e.onValidationResults?.(E,I?.validationResults),{statusCode:g.statusCode,body:g.body}}var zi=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],Qi={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function Zi(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(o=>o.active!==!1).length}function po(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(o=>o.characteristicType===t)}function me(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function fe(e){return typeof e=="object"&&e!==null}function es(e,t,r){let o=Array.isArray(e[r])?e[r]:[],n=[];for(let i of o){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let d=a.type;if((fe(d)?d.conceptId:void 0)!==t)return;let u=a.target;n.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:fe(u)?u.conceptId:void 0,targetFsn:fe(u)&&fe(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return n}async function je(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};if(!t.attributeType){let a=zi.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>Qi[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${o.branchPath}/concepts/${t.conceptId}`,c=await x(a,{cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:c.statusCode,body:c.body}}let n=`${A(e)}/browser/${o.branchPath}/concepts/${t.conceptId}`,i=await x(n,{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||!fe(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=es(s,t.attributeType,a);return{statusCode:i.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:c}}}if(t.descriptions){let a=Array.isArray(s.descriptions)?s.descriptions.filter(c=>c.active!==!1):[];return{statusCode:i.statusCode,body:{...me(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...me(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...me(s),classAxioms:s.classAxioms??[],relationships:po(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...me(s),relationships:po(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...me(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:Zi(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var ts=500,os=1e4;async function Ne(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n={expand:"fsn()"};t.term&&(n.termFilter=t.term),t.ecl&&(n.eclFilter=t.ecl),typeof t.active=="boolean"&&(n.activeFilter=t.active);let i=`${A(e)}/${o.branchPath}/concepts/search`,s=l=>({conceptId:l.conceptId,fsn:l.fsn?.term,pt:l.pt?.term,active:l.active,moduleId:l.moduleId});if(t.limit!==void 0){let l=await x(i,{method:"POST",body:{...n,limit:t.limit},cookie:e.cookie});if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let u=(l.body?.items??[]).map(s);return{statusCode:l.statusCode,body:{total:l.body?.total??u.length,items:u}}}let a=[],c=0,d=0;for(;;){let l=Math.min(ts,os-d);if(l<=0)break;let u=await x(i,{method:"POST",body:{...n,limit:l,offset:d},cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(u.statusCode<200||u.statusCode>=300)return{statusCode:u.statusCode,body:u.body??{error:"Concept search failed."}};let p=u.body?.items??[];if(a.push(...p.map(s)),c=u.body?.total??a.length,d+=p.length,p.length===0||d>=c)break}return{statusCode:200,body:{total:c,items:a,...a.length<c?{truncated:!0,message:`Only ${a.length} of ${c} matches returned \u2014 Snowstorm caps unsorted search at offset+limit 10,000. Narrow the query (--term/--ecl/--active) to see the rest.`}:{}}}}var ge=1e3;function ns(e){let t=new Map;for(let r of e)for(let o of r){let n=o.referenceType?.conceptId??"",i=t.get(n);i?i.referencingConcepts=[...i.referencingConcepts??[],...o.referencingConcepts??[]]:t.set(n,{...o,referencingConcepts:[...o.referencingConcepts??[]]})}return[...t.values()]}async function mo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=`${A(e)}/${o.branchPath}/concepts/${t.conceptId}/references`,i=(l,u)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(l)),p.set("offset",String(u)),x(`${n}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let l=await i(t.limit??ge,t.offset??0);return l.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:l.statusCode,body:l.body}}let s=[],a=0,c=0,d=0;for(;;){let l=await i(ge,d);if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(l.statusCode<200||l.statusCode>=300)return{statusCode:l.statusCode,body:l.body??{error:"Could not fetch references."}};let u=l.body?.referencesByType??[];s.push(u),a=l.body?.total??a;let p=u.reduce((y,k)=>y+(k.referencingConcepts?.length??0),0);if(c+=p,p===0||p<ge||c>=a)break;d+=ge}return{statusCode:200,body:{total:a,limit:ge,offset:0,referencesByType:ns(s)}}}var ft=S(require("crypto"));function fo(e){return typeof e=="object"&&e!==null}function rs(e){let t=e.type,r=e.target,o=fo(t)?t.conceptId:void 0,n=fo(r)?r.conceptId:void 0;return typeof o=="string"&&typeof n=="string"?{typeId:o,targetId:n}:null}function is(e,t){let r=[...t];for(let o of e){let n=r.findIndex(i=>i.typeId===o.typeId&&i.targetId===o.targetId);if(n===-1)return!1;r.splice(n,1)}return!0}function go(e,t,r){let o=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=o.get(a);c?c.push(s):o.set(a,[s])}let n=[];for(let[s,a]of o){if(r!=null?s!==r:s===0)continue;let c=a.map(rs).filter(d=>d!=null);is(t,c)&&n.push(s)}if(n.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(n.length>1)return{ok:!1,statusCode:409,error:`has ${n.length} role groups matching the given attributes (groupIds: ${n.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let i=n[0];return{ok:!0,groupId:i,relationships:o.get(i)}}var ss=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],as=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],cs=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],ds=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],ls=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],gt=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function wo(e){return gt.includes(e)}function ye(e,t){let r={};for(let o of t)o in e&&(r[o]=e[o]);return r}function De(e){return typeof e=="object"&&e!==null}function yo(e){return De(e)?ye(e,ds):e}function To(e){if(!De(e))return e;let t=ye(e,cs);return"type"in t&&(t.type=yo(t.type)),"target"in t&&(t.target=yo(t.target)),t}function us(e){return De(e)?ye(e,as):e}function ho(e){if(!De(e))return e;let t=ye(e,ls);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(To)),t}function yt(e){let t=ye(e,ss);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(us)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(To)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(ho)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(ho)),t}function ps(e){return new Promise(t=>setTimeout(t,e))}function ms(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var pt=[300,600,1200,2400,4800],ko=new Map;function fs(e,t){let o=(ko.get(e)??Promise.resolve()).then(t,t);return ko.set(e,o.then(()=>{},()=>{})),o}async function $(e,t,r,o){try{return await fs(t.branchPath,()=>gs(e,t,r,o))}catch(n){return{statusCode:500,body:{error:n instanceof Error?n.message:String(n)}}}}async function gs(e,t,r,o){for(let n=0;;n++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,d=o(c);if(d)return d;let l=Z(t.branchPath),u=`${i}/browser/${l}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await x(u,{method:"PUT",body:yt(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(ms(p)&&n<pt.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${n+1}/${pt.length})`),await ps(pt[n]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let y=p.body;return e.onValidationResults?.(r,y?.validationResults),{statusCode:p.statusCode,body:p.body}}}var Co=["PREFERRED","ACCEPTABLE"];async function Ao(e,t,r,o=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&&!Co.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${Co.join(", ")}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[];return l.push(pe(t.type,c,s,a,t.acceptability??"ACCEPTABLE",!1)),d.descriptions=l,null})}async function Ro(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let i=t.axiomIndex??0;return $(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];if(!c)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}};let d=Array.isArray(c.relationships)?c.relationships:[];return d.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),c.relationships=d,null})}async function $o(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let i=t.axiomIndex??0;return $(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];return c?(c.definitionStatus=t.status,s.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}}})}async function Eo(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>i.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(i.active=!1,i.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(i.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null))}async function Po(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&&!wo(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(a.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(a.term=t.term),t.caseSignificance&&(a.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function jo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!wo(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?(a.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}var mt=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function xo(e){return mt.includes(e)}function No(e){return e.us&&!xo(e.us)?{statusCode:400,body:{error:`us must be one of: ${mt.join(", ")}.`}}:e.gb&&!xo(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${mt.join(", ")}.`}}:null}function Do(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.`}}:No(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function ht(e,t,r){let o=e.find(i=>i.descriptionId===r.descriptionId);if(!o)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(o.lang=r.lang);let n={...o.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete n[V]:n[V]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete n[Q]:n[Q]=r.gb),o.active!==!1&&Object.keys(n).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.`}}:(o.acceptabilityMap=n,null)}async function Oo(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},n=Do(o);if(n)return n;let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await w(e,i);return s||$(e,i,t.conceptId,a=>{let c=Array.isArray(a.descriptions)?a.descriptions:[];return ht(c,t.conceptId,o)})}async function Fo(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 i of t.entries){let s=Do(i);if(s)return s}let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[];for(let a of t.entries){let c=ht(s,t.conceptId,a);if(c)return c}return null})}async function Lo(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[],a=s.findIndex(c=>c.descriptionId===t.descriptionId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(s.splice(a,1),i.descriptions=s,null)})}var Oe="REFERS_TO";async function _o(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(a.active=!1,a.inactivationIndicator=t.indicator,a.acceptabilityMap={},t.associationTargetId&&(a.associationTargets={[Oe]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}function Io(e,t,r){for(let o of e){if(o.descriptionId===t||o.active===!1||o.type!=="SYNONYM")continue;let n=o.acceptabilityMap;n?.[r]==="PREFERRED"&&(o.acceptabilityMap={...n,[r]:"ACCEPTABLE"})}}async function Ko(e,t,r,o=new Map){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},i=No(n);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await C(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await w(e,a);if(c)return c;let d=await te(e,a.projectKey,o);return $(e,a,t.conceptId,l=>{let u=Array.isArray(l.descriptions)?l.descriptions:[],p=u.find(k=>k.descriptionId===t.descriptionId);if(!p)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(p.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(p.type==="FSN"){if(s)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let k=u.filter(h=>h.type==="FSN"&&h.active!==!1&&h.descriptionId!==t.descriptionId);if(k.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${k.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(k.length===1){let h=k[0];if(h.effectiveTime==null)u.splice(u.indexOf(h),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(h.descriptionId)} in the same save.`}};h.active=!1,h.inactivationIndicator=t.indicator,h.acceptabilityMap={},t.associationTargetId&&(h.associationTargets={[Oe]:[t.associationTargetId]})}}return p.active=!0,delete p.inactivationIndicator,delete p.associationTargets,p.acceptabilityMap=Pe(d,!1),l.descriptions=u,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};p.active=!0,delete p.inactivationIndicator,delete p.associationTargets;let y=ht(u,t.conceptId,n);return y||(n.us==="PREFERRED"&&Io(u,t.descriptionId,V),n.gb==="PREFERRED"&&Io(u,t.descriptionId,Q),null)})}var ys="900000000000490003",bo=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function Mo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!bo.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${bo.join(", ")}.`}};if(t.reason==="NOT_SEMANTICALLY_EQUIVALENT"){if(!t.targetId)return{statusCode:400,body:{error:"reason NOT_SEMANTICALLY_EQUIVALENT requires --target-id \u2014 the concept this description actually belongs under."}}}else if(t.targetId)return{statusCode:400,body:{error:`--target-id only applies to reason NOT_SEMANTICALLY_EQUIVALENT (paired with a REFERS_TO association) \u2014 omit it for ${t.reason}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${ys}&active=true`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:a.body}};let c=(a.body.items??[])[0];return c?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(c.effectiveTime)}) and cannot be changed.`}}:$(e,o,t.conceptId,d=>{let u=(Array.isArray(d.descriptions)?d.descriptions:[]).find(p=>p.descriptionId===t.descriptionId);return u?u.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(u.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?u.associationTargets={[Oe]:[t.targetId]}:delete u.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Bo(e,t,r,o=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[],u;if(t.descriptionId){if(u=l.find(p=>p.descriptionId===t.descriptionId),!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(u.type)}, not an FSN.`}}}else{let p=l.filter(y=>y.type==="FSN"&&y.active!==!1);if(p.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${p.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};u=p[0]}return u.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(u.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(u.active=!1,u.inactivationIndicator=t.indicator,u.acceptabilityMap={},t.associationTargetId&&(u.associationTargets={[Oe]:[t.associationTargetId]}),l.push(pe("FSN",c,s,a,"PREFERRED",!1)),d.descriptions=l,null)})}function Uo(e,t,r){return $(e,t,r.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(s=>s.axiomId===r.axiomId);return i?(i.relationships=r.relationships,r.active!=null&&(i.active=r.active),null):{statusCode:404,body:{error:`Concept ${r.conceptId} has no class axiom ${r.axiomId}.`}}})}async function Vo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||Uo(e,o,t)}async function qo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.gciAxioms)?i.gciAxioms:[]).find(c=>c.axiomId===t.axiomId);return a?(a.relationships=t.relationships,t.active!=null&&(a.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}})}async function Ho(e,t,r,o=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.classAxioms)?a.classAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.classAxioms=c,null})}async function Jo(e,t,r,o=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 n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.gciAxioms)?a.gciAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.gciAxioms=c,null})}async function Go(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(s.splice(a,1),i.classAxioms=s,null)})}async function Wo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(a.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(a.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:c.every(d=>d.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished class axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-axiom to edit ${t.axiomId}'s content in place instead.`}}:(a.active=!1,null)})}var hs="116680003";function vo(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function ks(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let i of r)i?.id&&t.push({active:!0,groupId:0,type:{conceptId:hs},target:{conceptId:i.id}});let o=Array.isArray(e.attributes)?e.attributes:[];for(let i of o)t.push(vo(i,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((i,s)=>{let a=Array.isArray(i.attributes)?i.attributes:[];for(let c of a)t.push(vo(c,s+1))}),t}async function Yo(e,t,r,o){let n=A(e),i=await x(`${n}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(i.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{ok:!1,result:{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body,undetermined:!0}}};let s=Array.isArray(i.body.classAxioms)?i.body.classAxioms:[],a;if(o){if(a=s.find(c=>c.axiomId===o),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${o}.`,undetermined:!0}}}}else{let c=s.filter(d=>d.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var Cs="116680003";function xs(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==Cs?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function Is(e,t,r){let o=A(e),n=await x(`${o}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(n.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(n.statusCode<200||n.statusCode>=300||!n.body)return{ok:!1,result:{statusCode:n.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:n.body,undetermined:!0}}};let i=ks(n.body);return i.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`,undetermined:!0}}}:{ok:!0,value:i}}async function bs(e,t,r,o){let n=await Yo(e,t,r,o);if(!n.ok)return n;let i=await Is(e,t,r);return i.ok?{ok:!0,value:{axiom:n.value.axiom,axiomId:n.value.axiomId,targetRelationships:i.value}}:i}function vs(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let o=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${o}`}function So(e){let t=new Map;for(let n of e){if(n.active===!1)continue;let i=typeof n.groupId=="number"?n.groupId:0,s=t.get(i)??[];s.push(vs(n)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),o=[];for(let[n,i]of t)n!==0&&o.push(i.slice().sort());return{ungrouped:r,groups:o}}function Ss(e,t){let r=So(e),o=So(t);if(r.ungrouped.join("|")!==o.ungrouped.join("|"))return!1;let n=r.groups.map(s=>s.join("|")).sort(),i=o.groups.map(s=>s.join("|")).sort();return n.join("||")===i.join("||")}async function Xo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let i=await bs(e,o,t.conceptId,t.axiomId);if(!i.ok)return i.result;let{axiom:s,axiomId:a,targetRelationships:c}=i.value,d=Array.isArray(s.relationships)?s.relationships:[];return Ss(d,c)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${o.projectKey}/${o.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:a,alreadyConformed:!0}}):Uo(e,o,{conceptId:t.conceptId,axiomId:a,relationships:c})}async function Fe(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Yo(e,o,t.conceptId,t.axiomId);if(!n.ok)return n.result;let{axiom:i,axiomId:s}=n.value,a=Array.isArray(i.relationships)?i.relationships:[];return xs(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function zo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=t.relationshipId?c.findIndex(u=>u.relationshipId===t.relationshipId):t.relationshipIndex,l=d>=0?c[d]:void 0;return l?l.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${d}`} has effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(c.splice(d,1),a.relationships=c,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}})}async function Qo(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 i of t.attributes)if(!i||typeof i.typeId!="string"||typeof i.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=go(c,t.attributes,t.groupId);if(!d.ok)return{statusCode:d.statusCode,body:{error:`Axiom ${t.axiomId} ${d.error}`}};let l=d.relationships.find(u=>u.effectiveTime!=null);return l?{statusCode:409,body:{error:`Role group (groupId ${d.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(l.relationshipId)}) with effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.relationships=c.filter(u=>(typeof u.groupId=="number"?u.groupId:0)!==d.groupId),null)})}async function Zo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(s.splice(a,1),i.gciAxioms=s,null)})}async function en(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(a.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}};if(a.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length>0&&c.every(d=>d.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating GCI axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished GCI axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-gci-axiom to edit ${t.axiomId}'s content in place instead.`}}:(a.active=!1,null)})}var ws=8;async function Le(e,t,r,o){let n=[],i=[],s=0,a=async()=>{for(;;){let d=s++;if(d>=r.length)return;let l=r[d];try{let u=await Fe(e,{conceptId:l.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),p=u.body;if(u.statusCode<200||u.statusCode>=300){i.push({...l,error:p?.error??`HTTP ${u.statusCode}`});continue}p?.conclusive&&n.push({...l,axiomId:p.axiomId})}catch(u){i.push({...l,error:u instanceof Error?u.message:String(u)})}}},c=Math.min(ws,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:n,skipped:i}}async function tn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Ne(e,{...t,branchPath:o.branchPath},r);if(n.statusCode<200||n.statusCode>=300)return n;let i=n.body?.items??[],s=i.map(d=>({conceptId:d.conceptId,fsn:d.fsn,pt:d.pt})),{matched:a,skipped:c}=await Le(e,o,s,r);return{statusCode:200,body:{branchPath:o.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function on(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let i=A(e),s=`${i}/browser/${o.branchPath}/concepts/${t.conceptId}`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:a.body}};if(a.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let c=`${i}/${o.branchPath}/concepts/${t.conceptId}`,d=await x(c,{method:"DELETE",cookie:e.cookie});return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${o.projectKey}/${o.taskKey}: ${d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.conceptId}`),d.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:d.body}}:{statusCode:d.statusCode,body:d.body})}var he="733073007",nn=["Import","SubClassOf","EquivalentClasses","DisjointClasses","DisjointUnion","Annotation","AnnotationAssertion","SubAnnotationPropertyOf","AnnotationPropertyDomain","AnnotationPropertyRange","HasKey","Declaration","InverseObjectProperties","DatatypeDefinition","SubObjectPropertyOf","EquivalentObjectProperties","DisjointObjectProperties","ObjectPropertyDomain","ObjectPropertyRange","FunctionalObjectProperty","InverseFunctionalObjectProperty","ReflexiveObjectProperty","IrreflexiveObjectProperty","SymmetricObjectProperty","AsymmetricObjectProperty","TransitiveObjectProperty","SubDataPropertyOf","EquivalentDataProperties","DisjointDataProperties","DataPropertyDomain","DataPropertyRange","FunctionalDataProperty","SameIndividual","DifferentIndividuals","ClassAssertion","ObjectPropertyAssertion","NegativeObjectPropertyAssertion","DataPropertyAssertion","NegativeDataPropertyAssertion","DLSafeRule"];function Ts(e){let t=e.trim(),r=0;for(let n of t)if(n==="(")r+=1;else if(n===")"&&(r-=1,r<0))return"Unbalanced parentheses in OWL expression (an unmatched ')' ) \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.";if(r!==0)return`Unbalanced parentheses in OWL expression (${r} unclosed '(') \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.`;let o=/^([A-Za-z]+)\s*\(/.exec(t)?.[1];return!o||!nn.includes(o)?`OWL expression doesn't start with a recognized top-level axiom keyword${o?` (saw "${o}")`:""} \u2014 expected one of ${nn.slice(0,6).join(", ")}, ... Refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly. This is only a shallow keyword/paren check, not a real OWL parser \u2014 passing it doesn't guarantee the expression is actually valid.`:null}async function rn(e,t,r,o=new Map){if(!t.propertyId)return{statusCode:400,body:{error:"propertyId is required."}};if(!t.owlExpression||!t.owlExpression.trim())return{statusCode:400,body:{error:"owlExpression is required."}};let n=Ts(t.owlExpression);if(n)return{statusCode:400,body:{error:n}};let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await w(e,i);if(s)return s;let a=t.moduleId||await B(e,i.projectKey,o),d=`${A(e)}/${i.branchPath}/members`,l=await x(d,{method:"POST",cookie:e.cookie,body:{active:!0,moduleId:a,refsetId:he,referencedComponentId:t.propertyId,additionalFields:{owlExpression:t.owlExpression}}});return l.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] add-property-axiom ${i.projectKey}/${i.taskKey}: ${l.statusCode>=200&&l.statusCode<300?"OK":"FAILED ("+l.statusCode+")"} \u2014 ${t.propertyId}`),{statusCode:l.statusCode,body:l.body})}async function sn(e,t,r,o=200,n=0){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let a=`${A(e)}/${i.branchPath}/members?referencedComponentId=${encodeURIComponent(t.conceptId)}&referenceSet=${he}&limit=${o}&offset=${n}`;t.activeOnly&&(a+="&active=true");let c=await x(a,{cookie:e.cookie});if(c.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(c.statusCode<200||c.statusCode>=300||!c.body)return{statusCode:c.statusCode||500,body:{error:`Could not fetch property axioms for ${t.conceptId}.`,details:c.body}};let l=(c.body.items??[]).map(u=>({memberId:u.memberId,active:u.active,released:u.released,effectiveTime:u.effectiveTime??null,moduleId:u.moduleId,owlExpression:u.additionalFields?.owlExpression??null}));return{statusCode:200,body:{conceptId:t.conceptId,refsetId:he,total:c.body.total??l.length,axioms:l}}}async function an(e,t,r){if(!t.conceptId||!t.memberId)return{statusCode:400,body:{error:"conceptId and memberId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members/${encodeURIComponent(t.memberId)}`,a=await x(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode===404)return{statusCode:404,body:{error:`No reference set member ${t.memberId} on this branch.`}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||500,body:{error:`Could not fetch property axiom ${t.memberId}.`,details:a.body}};let c=a.body;if(c.refsetId!==he)return{statusCode:400,body:{error:`Member ${t.memberId} is not an OWL Axiom reference set member (refsetId ${String(c.refsetId??"unknown")}) \u2014 delete-property-axiom only removes members of refset ${he}.`}};if(String(c.referencedComponentId)!==t.conceptId)return{statusCode:400,body:{error:`Member ${t.memberId} belongs to concept ${String(c.referencedComponentId)}, not ${t.conceptId} \u2014 refusing to delete; double check the conceptId/memberId pair against get-property-axioms output.`}};let d=await x(s,{method:"DELETE",cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(e.onLog?.(`[${new Date().toISOString()}] delete-property-axiom ${o.projectKey}/${o.taskKey}: ${d.statusCode>=200&&d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.memberId}`),d.statusCode>=200&&d.statusCode<300){let l=c.additionalFields;return{statusCode:200,body:{deleted:!0,conceptId:t.conceptId,memberId:t.memberId,owlExpression:l?.owlExpression??null}}}return{statusCode:d.statusCode,body:d.body??{error:`Failed to delete property axiom ${t.memberId}.`}}}function As(e){let t=[];for(let r of e)t.some(n=>n.componentId===r.componentId&&n.severity===r.severity&&n.conceptId===r.conceptId&&n.message===r.message)||t.push(r);return t}async function _e(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=A(e),i=`${n}/browser/${o.branchPath}/concepts/${t.conceptId}`,s=await x(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};let a=Z(o.branchPath),c=`${n}/browser/${a}/${o.projectKey}/${o.taskKey}/validate/concept`,d=await x(c,{method:"POST",body:yt(s.body),cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let l=Array.isArray(d.body)?As(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 cn=200;async function Rs(e,t,r){let o=new Map;if(r.length===0)return{terms:o,resolved:!0};let n=`${A(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=cn){let a=r.slice(s,s+cn),c=await x(n,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let d of c.body)o.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:o,resolved:i}}async function q(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=[],i=0;for(;;){let h=`${so(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(o.branchPath)}`,g=await x(h,{cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(g.statusCode===404)return{statusCode:200,body:{branchPath:o.branchPath,concepts:[],conceptsClassified:[]}};if(g.statusCode<200||g.statusCode>=300)return{statusCode:g.statusCode,body:{error:"Could not fetch traceability for branch.",details:g.body}};n.push(...g.body?.content??[]);let I=g.body?.totalPages??1;if(g.body?.last!==!1||i+1>=I)break;i+=1}let s=new Map,a=new Map,c=(h,g,I,E)=>{let D=h.get(g);D?(E.forEach(N=>N&&D.componentSubTypes.add(N)),D.lastUpdatedTime=I):h.set(g,{conceptId:g,lastUpdatedTime:I,componentSubTypes:new Set(E.filter(N=>!!N))})};for(let h of n)if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let g of h.conceptChanges??[]){let I=String(g.conceptId),E=g.componentChanges??[],D=E.map(O=>O.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,I,h.commitDate,D);continue}let N=E.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(N?s:a,I,h.commitDate,D)}for(let h of s.keys())a.delete(h);let d=[...new Set([...s.keys(),...a.keys()])],{terms:l,resolved:u}=await Rs(e,o.branchPath,d),p=h=>[...h.values()].sort((g,I)=>(I.lastUpdatedTime??"").localeCompare(g.lastUpdatedTime??"")).map(g=>{let I=u&&!l.has(g.conceptId);return{conceptId:g.conceptId,fsn:l.get(g.conceptId)?.fsn,pt:l.get(g.conceptId)?.pt,...I?{deleted:!0}:{},lastUpdatedTime:g.lastUpdatedTime,changedComponentTypes:[...g.componentSubTypes]}}),y=p(s),k=p(a);return{statusCode:200,body:{branchPath:o.branchPath,...u?{summary:{concepts:y.length,conceptsDeleted:y.filter(h=>h.deleted).length,conceptsClassified:k.length}}:{},concepts:y,conceptsClassified:k}}}async function dn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let l=n.body;return{statusCode:n.statusCode,body:{error:l.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=i.filter(l=>!l.deleted),a=s.map(l=>({conceptId:l.conceptId,fsn:l.fsn})),{matched:c,skipped:d}=await Le(e,o,a,r);return{statusCode:200,body:{branchPath:o.branchPath,totalReviewed:s.length,matched:c.length,skipped:d.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:d}}}async function $s(e,t,r,o){let n=[];for(let i of r){if(i.deleted){n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await _e(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),a=s.body;if(s.statusCode<200||s.statusCode>=300){n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return n}async function ln(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=await $s(e,o,i,r),a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.branchPath,summary:{total:s.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:s}}}async function un(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=[];for(let[c,d]of i.entries()){if(d.deleted){s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"deleted"});continue}let l=await je(e,{conceptId:d.conceptId,projectKey:o.projectKey,taskKey:o.taskKey,branchPath:o.branchPath},r),u=l.body,p=`(${c+1}/${i.length})`;if(l.statusCode<200||l.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: FAILED (${l.statusCode}) \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"failed",error:u?.error??`HTTP ${l.statusCode}`});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: OK \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"fetched",concept:l.body})}let a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.branchPath,summary:{total:s.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:s}}}var kt=new Set;function pn(e){if(!(!e||typeof e!="object"))for(let t of kt)t(e)}function Es(e){return kt.add(e),()=>kt.delete(e)}function Ps(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 Ke(e){let t=()=>{};return{promise:new Promise(o=>{t=Es(n=>{Ps(n,e)&&(t(),o(n))})}),cancel:t}}var bt=["RUNNING","BUILDING","SCHEDULED","QUEUED"],vt=["QUEUED","SCHEDULED","RUNNING"],js=["Promoted","Completed"],mn=5e3;function It(e){return new Promise(t=>setTimeout(t,e))}async function Ns(e,t,r){let o=0;for(;;){let{done:n,value:i}=await e();if(n)return{value:i,timedOut:!1};if(o>=r)return{value:i,timedOut:!0};o++,await It(t)}}function Ds(){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 Os=Ds(),Fs=180;function Ls(){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 _s=Ls(),Ks=900;async function yn(e,t,r,o,n){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=o?Ke(o):void 0,l=await Promise.race(d?[It(c).then(()=>{}),d.promise]:[It(c).then(()=>{})]);if(d?.cancel(),l){let y=l.event;n?.(`[${new Date().toISOString()}] woken by notification${y?`: ${y}`:""}`)}let{done:u,value:p}=await e();if(u)return{value:p,timedOut:!1};if(Date.now()-s>=i)return{value:p,timedOut:!0};a++}}async function hn(e,t,r){let o=await _(e,t,r);if(!o)return{error:`Could not fetch task ${t}/${r}.`};if(o.status&&js.includes(o.status))return{error:`Task ${t}/${r} is ${o.status} \u2014 cannot start a new job.`};if(o.status==="New"){let n=`${P(e)}/projects/${t}/tasks/${r}`;await x(n,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function St(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await x(o,{method:"POST",body:{},cookie:e.cookie}),(await _(e,t,r))?.latestClassificationJson}async function fn(e,t,r,o,n){let i,{value:s,timedOut:a}=await yn(async()=>{let d=(await St(e,t,r))?.status;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||bt.includes(d)),value:d}},Os,n,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function Ct(e,t,r){let o=`${A(e)}/${t}/classifications`,n=await x(o,{cookie:e.cookie});if(n.body?.items?.length)return n.body.items.find(i=>i.id===r)??n.body.items[n.body.items.length-1]}async function kn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,s=await St(e,n,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:bt.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function Cn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let{projectKey:i,taskKey:s,branchPath:a}=o,c=await hn(e,i,s);if(c.error)return{statusCode:400,body:{error:c.error}};let d=t.timeoutSeconds??Fs,l=await St(e,i,s),u=l?.status,p=l?.id;if(p&&u&&bt.includes(u)){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:N,timedOut:O}=await fn(e,i,s,a,d),Re=await Ct(e,a,p),dt={accepted:!1};return!O&&N==="COMPLETED"&&(dt=await xt(e,a,i,s,p)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: attached job ${p} final status ${N??"unknown"}${O?" (timed out waiting)":""}, save ${JSON.stringify(dt)}`),{statusCode:200,body:{jobId:p,finalStatus:N,timedOut:O,details:Re,save:dt,attachedToExisting:!0}}}if(p&&u==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let N=await Ct(e,a,p),O=await xt(e,a,i,s,p);return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: accepted existing job ${p}, save ${JSON.stringify(O)}`),{statusCode:200,body:{jobId:p,finalStatus:"COMPLETED",timedOut:!1,details:N,save:O,acceptedExisting:!0}}}let y=`${P(e)}/projects/${i}/tasks/${s}/classifications`,k=await x(y,{method:"POST",body:{},cookie:e.cookie});if(k.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!k.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: start failed (HTTP ${k.statusCode}) \u2014 raw body: ${k.rawBody}`),{statusCode:k.statusCode||500,body:{error:"Failed to start classification.",details:k.body??k.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: started (${k.body.status??"unknown"})`);let h=k.body.id;if(!t.wait)return{statusCode:200,body:{jobId:h,status:k.body.status}};let{finalStatus:g,timedOut:I}=await fn(e,i,s,a,d),E=await Ct(e,a,h),D={accepted:!1};return!I&&g==="COMPLETED"&&(D=await xt(e,a,i,s,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: final status ${g??"unknown"}${I?" (timed out waiting)":""}, save ${JSON.stringify(D)}`),{statusCode:200,body:{jobId:h,finalStatus:g,timedOut:I,details:E,save:D}}}var Ms=["SAVED","STALE","SAVE_FAILED"],Bs=120;async function xt(e,t,r,o,n){let i=`${A(e)}/${t}/classifications/${n}`,s=await x(i,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(s.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(s.statusCode<200||s.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${s.statusCode}).`};let a=Math.ceil(Bs*1e3/mn),{value:c,timedOut:d}=await Ns(async()=>{let u=(await x(i,{cookie:e.cookie})).body?.status;return{done:!!u&&Ms.includes(u),value:u}},mn,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 xn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,a=(await _(e,n,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&vt.includes(a)}}}async function gn(e,t,r,o,n){let i,{value:s,timedOut:a}=await yn(async()=>{let d=(await _(e,t,r))?.latestValidationStatus;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||vt.includes(d)),value:d}},_s,n,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function In(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=await hn(e,n,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Ks,l=(await _(e,n,i))?.latestValidationStatus;if(l&&vt.includes(l)){e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:h,timedOut:g}=await gn(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: attached run final status ${h??"unknown"}${g?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:h,timedOut:g,attachedToExisting:!0}}}let u=`${P(e)}/projects/${n}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await x(u,{method:"POST",body:{},cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(p.statusCode<200||p.statusCode>=300)return{statusCode:p.statusCode,body:{error:"Failed to start validation.",details:p.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:y,timedOut:k}=await gn(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: final status ${y??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:y,timedOut:k}}}async function bn(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",o=`${P(e)}/projects${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function vn(e,t){let r=`${P(e)}/projects/${t}/tasks`;return(await x(r,{cookie:e.cookie})).body??[]}async function Sn(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",o=`${P(e)}/projects/my-tasks${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function wn(e,t){let r=`${P(e)}/projects/${t.projectKey}/tasks`,o={summary:t.summary};t.description!==void 0&&(o.description=t.description),t.assigneeUsername&&(o.assignee={username:t.assigneeUsername});let n=await x(r,{method:"POST",body:o,cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}async function Tn(e,t){let r=`${P(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,o=await x(r,{cookie:e.cookie});return Array.isArray(o.body)?o.body:[]}var Us="IN_PROGRESS";async function An(e,t){let r=`${P(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,o=await x(r,{cookie:e.cookie});if(o.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode<200||o.statusCode>=300||!o.body)return{statusCode:o.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode}).`};if(o.body.status!=="Deleted")return{statusCode:200,task:o.body,notDeleted:!0};let n=await x(r,{method:"PUT",body:{status:Us},cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}function Rn(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 wt(e){return JSON.stringify([e])}function $n(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",o="";for(let n=0;n<8;n++)o+=r[Math.floor(e()*r.length)];return`${t}/${o}/websocket`}function Tt(e,t={},r=""){let o=Object.entries(t).map(([n,i])=>`${n}:${i}`);return[e,...o,"",r].join(`
3
+ `)+"\0"}function En(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
4
4
 
5
5
  `),o=r===-1?t:t.slice(0,r),n=r===-1?"":t.slice(r+2),i=o.split(`
6
- `),s=i[0],a={};for(let c of i.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:s,headers:a,body:n}}var Pn=v(require("ws"));var En=[1e3,2e3,5e3,1e4,3e4];function jn(e,t={}){let r=t.createSocket??((l,u)=>new Pn.default(l,u)),o=!1,n,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(o)return;let l=En[Math.min(i,En.length-1)];i+=1,s=setTimeout(d,l)};function d(){if(o)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${Rn()}`,p=r(u,a?{headers:{cookie:a}}:{});n=p,p.on("message",y=>{let k=An(y.toString());if(k.type==="open"){p.send(wt(Tt("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(k.type==="close"){p.close();return}if(k.type==="message")for(let h of k.messages){let g=$n(h);if(g){if(g.command==="CONNECTED"){i=0;let I=`/topic/user/${e.login}/notifications`;p.send(wt(Tt("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:I})));continue}if(g.command==="MESSAGE"){try{e.onNotification(JSON.parse(g.body))}catch(I){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",I)}continue}g.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",g.headers,g.body)}}}),p.on("unexpected-response",(y,k)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${k.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",y=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",y.message)}),p.on("close",c)}return d(),{stop(){o=!0,s&&clearTimeout(s),n?.removeAllListeners(),n?.close()}}}function Nn(e,t,r={}){let o=r.startRelay??jn,n=r.onNotification??un,i=o({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:n});return{stop:()=>i.stop()}}var _s=60;async function Dn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=t.timeoutSeconds??_s,c=Me({entityType:t.entityType,projectKey:n,taskKey:i,branchPath:s}),d,l=new Promise(y=>{d=setTimeout(()=>y({kind:"timeout"}),a*1e3)}),u=c.promise.then(y=>({kind:"notification",payload:y})),p=await Promise.race([u,l]);return c.cancel(),clearTimeout(d),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function b(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",o=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",n=t.componentId??t.conceptId??"?";console.log(`${o} ${r} [${n}] ${t.message??""}`)}}var sr=v(require("http")),Ze=require("child_process"),ar=require("util");var Be=v(require("fs")),On=v(require("os")),Ue=v(require("path"));function Rt(){return Ue.join(On.homedir(),".authoring-cli-chrome")}function J(){return Ue.join(Rt(),"profile")}function Ms(){return Ue.join(J(),"Local State")}function Bs(){let e=Ms();if(!Be.existsSync(e))return[];let t;try{t=JSON.parse(Be.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([o,n])=>({directoryName:o,displayName:typeof n?.name=="string"&&n.name?n.name:o}))}var At="authoring-cli";function Ve(e=Bs()){return e.find(r=>r.directoryName===At)??{directoryName:At,displayName:At}}var Bn=require("child_process"),Un=require("util"),ke=v(require("fs")),Xe=v(require("os")),Ce=v(require("path"));var Fn=require("child_process"),Ln=require("util"),qe=v(require("crypto")),H=v(require("fs")),Us=(0,Ln.promisify)(Fn.exec);function $t(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}var Vs="peanuts";async function Et(e=process.platform){if(e==="darwin"){let{stdout:t}=await Us('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}if(e==="linux")return Vs;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}var Kn=1003,qs=1;function Pt(e){if(e==="darwin")return Kn;if(e==="linux")return qs;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function jt(e,t=Kn){return qe.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function Nt(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let o=r.subarray(0,3).toString("utf8");if(o!=="v10"&&o!=="v11")return null;let n=Buffer.alloc(16,32),i=r.subarray(3),s;try{let d=qe.createDecipheriv("aes-128-cbc",t,n);s=Buffer.concat([d.update(i),d.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&$t(a)&&!$t(s)&&(c=a),$t(c)?c.toString("utf8"):null}function Je(e,t){H.copyFileSync(e,t);for(let r of["-wal","-shm"]){let o=e+r;H.existsSync(o)&&H.copyFileSync(o,t+r)}}function Ge(e){for(let t of[e,e+"-wal",e+"-shm"])try{H.unlinkSync(t)}catch{}}var _n=v(require("fs"));var Mn=[{path:"/usr/bin/chromium",configDir:"chromium"},{path:"/usr/bin/chromium-browser",configDir:"chromium"},{path:"/usr/bin/google-chrome-stable",configDir:"google-chrome"},{path:"/usr/bin/google-chrome",configDir:"google-chrome"},{path:"/snap/bin/chromium",configDir:"chromium"}],cl=Array.from(new Set(Mn.map(e=>e.configDir)));function He(){return Mn.find(e=>_n.existsSync(e.path))??null}function We(e){let t=null;return async(r,o)=>{if(!r)return!1;if(!e)return r!==o;if(r===t)return!1;let n=await e(r);return n||(t=r),n}}var Vn=(0,Un.promisify)(Bn.exec),Ye=class extends Error{},ne=class extends Error{};function Dt(e){return Ce.join(J(),e,"Cookies")}function Js(e=process.platform){return e==="linux"?He()!==null:ke.existsSync("/Applications/Google Chrome.app")}function Gs(e){let t=e.split(".").filter(Boolean),r=[];for(let o=0;o+1<t.length;o++){let n=t.slice(o).join(".");r.push(n,`.${n}`)}return r}function Hs(e){let t=e?.code;return t==="EPERM"||t==="EACCES"}async function Ot(e,t,r,o=process.platform){let n=Dt(e);if(!n||!ke.existsSync(n))return null;let i=Ce.join(Xe.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);try{Je(n,i);let s;try{s=await Et(o)}catch{return null}let a=jt(s,Pt(o)),c=p=>`'${p.replace(/'/g,"''")}'`,l=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Gs(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await Vn(`sqlite3 "${i}" "${l}"`);return Nt(u.trim(),a)}catch{return null}finally{Ge(i)}}async function Ws(e,t=process.platform,r=25){let o=Dt(e);if(!o||!ke.existsSync(o))return{checked:0,decrypted:0};let n=Ce.join(Xe.tmpdir(),`authoring-cli-chrome-cookies-diag-${process.pid}-${Date.now()}.db`);try{Je(o,n);let i;try{i=await Et(t)}catch{return{checked:0,decrypted:0}}let s=jt(i,Pt(t)),{stdout:a}=await Vn(`sqlite3 "${n}" "SELECT hex(encrypted_value) FROM cookies WHERE length(encrypted_value) > 0 LIMIT ${r};"`),c=a.split(`
7
- `).map(l=>l.trim()).filter(Boolean),d=0;for(let l of c)Nt(l,s)!==null&&d++;return{checked:c.length,decrypted:d}}catch{return{checked:0,decrypted:0}}finally{Ge(n)}}function Ys(e){let t=Dt(e);if(!ke.existsSync(t))return null;let r=Ce.join(Xe.tmpdir(),`authoring-cli-chrome-cookies-precheck-${process.pid}-${Date.now()}.db`);try{return Je(t,r),null}catch(o){return Hs(o)?`Cannot read Chrome's cookie file for profile "${e}" at ${t} (permission denied). This is this app's own dedicated directory, not a protected system location \u2014 check its permissions, and that nothing else (an unusual sandboxing setup, a read-only filesystem mount, etc.) is restricting access to it, then try again.`:null}finally{Ge(r)}}function Xs(e){return new Promise(t=>setTimeout(t,e))}async function qn(e,t={}){let r=t.platform??process.platform,o=t.isChromeInstalled??(()=>Js(r));if(r!=="darwin"&&r!=="linux")throw new Ye(`Automatic session capture is only supported on macOS or Linux with Chrome/Chromium. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!o())throw new Ye(r==="darwin"?"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.":'Automatic session capture requires a Chromium/Chrome binary (checked common Debian install paths), but none was found. Install one (e.g. "apt install chromium" in this proot-distro Debian), or use the manual cookie-paste fallback instead.');let n=t.readCookie??((g,I,E)=>Ot(g,I,E,r)),i=t.sleep??Xs,s=t.onWarning??(g=>console.error(g)),a=t.checkCookieFileReadable??Ys,c=t.diagnoseDecryption??Ws,d=We(t.validateCookie),l=e.pollIntervalMs??750,u=e.timeoutMs??15e3,p=a(e.profileDirectory);p&&s(p);let y=await n(e.profileDirectory,e.host,e.cookieName);if(await d(y,y))return y;let k=Date.now()+u;for(;Date.now()<k;){let g=await n(e.profileDirectory,e.host,e.cookieName);if(await d(g,y))return g;await i(l)}let h=await c(e.profileDirectory,r).catch(()=>({checked:0,decrypted:0}));throw h.checked>0&&h.decrypted===0?new ne(`Timed out after ${u}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host} in Chrome profile "${e.profileDirectory}" \u2014 but this is NOT the usual "signed into the wrong window" mistake: ${h.checked} existing cookie(s) already in this exact profile's own jar all failed to decrypt with this tool's current decryption routine (0 of ${h.checked} readable). That means the sign-in almost certainly worked, but the installed Chrome has changed its cookie-encryption format to something this version of authoring-cli no longer knows how to decrypt \u2014 most likely from a Chrome auto-update since the last time login worked. Retrying login will not help. Use the manual cookie-paste fallback instead: open this same Chrome profile, open DevTools \u2192 Application/Storage \u2192 Cookies \u2192 ${e.host}, copy the "${e.cookieName}" row's Value, and run "authoring-cli login --cookie <value>".`):new ne(`Timed out after ${u}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host} in Chrome profile "${e.profileDirectory}" \u2014 the one and only profile this command ever reads or writes to. A common cause: sign-in happened in a DIFFERENT, already-open Chrome window/profile instead of the one this command opened \u2014 check that window's profile avatar (top-right corner) reads "${e.profileDirectory}", and that the window actually shows the real IMS login form rather than an unrelated already-signed-in page from another profile. Otherwise use the manual cookie-paste fallback (authoring-cli login --cookie <value>).`)}var re=v(require("fs")),Lt=v(require("path")),Jn=v(require("ws"));var W=class extends Error{};function Gn(e){try{re.unlinkSync(Lt.join(e,"DevToolsActivePort"))}catch{}}async function zs(e,t=1e4,r=100){let o=Lt.join(e,"DevToolsActivePort"),n=Date.now()+t;for(;;){if(re.existsSync(o)){let i=re.readFileSync(o,"utf8").trim().split(`
8
- `),[s,a]=i;if(s&&a)return`ws://127.0.0.1:${s}${a}`}if(Date.now()>=n)throw new W(`Timed out after ${t}ms waiting for Chrome's DevToolsActivePort file at ${o} \u2014 --remote-debugging-port may not be supported on this Chrome build/platform.`);await new Promise(i=>setTimeout(i,r))}}var Ft=class e{constructor(t){this.socket=t;t.on("message",r=>{let o;try{o=JSON.parse(r.toString())}catch{return}let n=this.pending.get(o.id);n&&(this.pending.delete(o.id),o.error?n.reject(new Error(o.error.message)):n.resolve(o.result))})}socket;nextId=1;pending=new Map;static async connect(t,r=1e4,o=i=>new Jn.default(i),n=150){let i=Date.now()+r,s;for(;;)try{return await e.attemptConnect(t,Math.max(i-Date.now(),1),o)}catch(c){if(s=c,Date.now()>=i)break;await new Promise(d=>setTimeout(d,n))}let a=s instanceof Error?s.message:String(s);throw new W(`Could not connect to CDP at ${t} within ${r}ms: ${a}`)}static attemptConnect(t,r,o){return new Promise((n,i)=>{let s=o(t),a=setTimeout(()=>{s.terminate(),i(new Error(`timed out after ${r}ms`))},r);s.once("open",()=>{clearTimeout(a),n(new e(s))}),s.once("error",c=>{clearTimeout(a),i(c)})})}send(t,r={},o){let n=this.nextId++,i={id:n,method:t,params:r};return o&&(i.sessionId=o),new Promise((s,a)=>{this.pending.set(n,{resolve:s,reject:a}),this.socket.send(JSON.stringify(i),c=>{c&&(this.pending.delete(n),a(c))})})}close(){this.socket.close()}};async function Qs(e,t,r=100){let o=Date.now()+t;for(;;){let{targetInfos:n}=await e.send("Target.getTargets"),i=n.find(s=>s.type==="page");if(i)return i.targetId;if(Date.now()>=o)throw new W(`No page target appeared via CDP within ${t}ms.`);await new Promise(s=>setTimeout(s,r))}}async function Hn(e,t={}){let r=t.waitForPort??zs,o=t.connect??Ft.connect,n=t.sleep??(u=>new Promise(p=>setTimeout(p,u))),i=e.setupTimeoutMs??1e4,s=e.pollIntervalMs??750,a=e.timeoutMs??12e4,c=We(t.validateCookie),d=await r(e.userDataDir,i),l=await o(d,i);try{let u=await Qs(l,i),{sessionId:p}=await l.send("Target.attachToTarget",{targetId:u,flatten:!0});await l.send("Network.enable",{},p);let y=async()=>{let{cookies:g}=await l.send("Network.getCookies",{urls:[e.cookieUrl]},p);return g.find(I=>I.name===e.cookieName)?.value??null},k=await y();if(await c(k,k))return k;let h=Date.now()+a;for(;Date.now()<h;){let g=await y();if(await c(g,k))return g;await n(s)}throw new ne(`Timed out after ${a}ms waiting for a valid "${e.cookieName}" cookie for ${e.host} via Chrome's own DevTools Protocol \u2014 Chrome itself reports no live session, which rules out a decryption problem (this path never decrypts anything; Chrome hands the value over directly). A common cause: sign-in happened in a DIFFERENT, already-open Chrome window/profile instead of the one this command opened. Otherwise use the manual cookie-paste fallback (authoring-cli login --cookie <value>).`)}finally{l.close()}}var Qe=require("child_process"),Yn=require("util"),F=v(require("fs")),Xn=v(require("net")),zn=(0,Yn.promisify)(Qe.exec),ze=1,xe=`:${ze}`,Zs=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"],Kt="/data/data/com.termux/files/usr/bin",Wn="com.termux.x11",ea=`${Wn}/${Wn}.MainActivity`,ta="termux-x11-start-app";function _t(e){return`/tmp/.X11-unix/X${e}`}async function oa(){for(let e of Zs){if(e.startsWith("/")){if(F.existsSync(e))return e;continue}try{return await zn(`command -v ${e}`),e}catch{}}return null}function na(e,t=500){return new Promise(r=>{let o=_t(e);if(!F.existsSync(o)){r(!1);return}let n=Xn.createConnection({path:o}),i=s=>{n.removeAllListeners(),n.destroy(),r(s)};n.setTimeout(t),n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.once("timeout",()=>i(!1))})}function ra(e,t=1e4){let r=Date.now()+t;return new Promise((o,n)=>{let i=()=>{if(F.existsSync(_t(e))){o();return}if(Date.now()>r){n(new Error(`Termux:X11's display socket for :${e} never appeared within ${t}ms`));return}setTimeout(i,100)};i()})}async function ia(){if(!F.existsSync(Kt))return;let e=`${Kt}/${ta}`,t=`${Kt}/bash`,o=`#!${F.existsSync(t)?t:"/bin/sh"}
9
- am start --user 0 -n ${ea} >/dev/null 2>&1
10
- `;try{F.writeFileSync(e,o,{mode:493}),F.chmodSync(e,493),await zn(e,{timeout:5e3})}catch{}}async function Qn(e=process.platform){if(e!=="linux"||await na(ze))return xe;await ia();let t=await oa();if(t===null)return xe;try{F.unlinkSync(_t(ze))}catch{}return(0,Qe.spawn)(t,[xe],{detached:!0,stdio:"ignore"}).unref(),await ra(ze),xe}var L=v(require("fs")),er=v(require("os")),U=v(require("path"));var Ie=class extends Error{},sa="com.ysgao.authoring-cli.chrome-login",tr="authoring-cli-chrome",aa="/Applications/Google Chrome.app";function ca(e=aa,t=L.existsSync){let r=U.join(e,"Contents","MacOS","Google Chrome");if(t(r))return r;throw new Ie(`No Google Chrome installation found at ${e}. Install Google Chrome to use automatic session capture.`)}function Zn(e){return`'${e.replace(/'/g,"'\\''")}'`}function da(e,t){return["#!/bin/sh","# Generated by authoring-cli. Do not edit \u2014 rewritten on every login launch.","# Flags are baked in deliberately: `open --args` does not reliably reach a script bundle","# executable, and Launch Services drops --args entirely when it hands off to an","# already-running Chrome instead of starting a genuinely new process \u2014 see","# assertLaunchFlagsBaked in chromeWrapperApp.ts.",`exec ${Zn(e)} \\`,t.map(r=>` ${Zn(r)}`).join(` \\
6
+ `),s=i[0],a={};for(let c of i.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:s,headers:a,body:n}}var jn=S(require("ws"));var Pn=[1e3,2e3,5e3,1e4,3e4];function Nn(e,t={}){let r=t.createSocket??((l,u)=>new jn.default(l,u)),o=!1,n,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(o)return;let l=Pn[Math.min(i,Pn.length-1)];i+=1,s=setTimeout(d,l)};function d(){if(o)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${$n()}`,p=r(u,a?{headers:{cookie:a}}:{});n=p,p.on("message",y=>{let k=Rn(y.toString());if(k.type==="open"){p.send(wt(Tt("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(k.type==="close"){p.close();return}if(k.type==="message")for(let h of k.messages){let g=En(h);if(g){if(g.command==="CONNECTED"){i=0;let I=`/topic/user/${e.login}/notifications`;p.send(wt(Tt("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:I})));continue}if(g.command==="MESSAGE"){try{e.onNotification(JSON.parse(g.body))}catch(I){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",I)}continue}g.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",g.headers,g.body)}}}),p.on("unexpected-response",(y,k)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${k.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",y=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",y.message)}),p.on("close",c)}return d(),{stop(){o=!0,s&&clearTimeout(s),n?.removeAllListeners(),n?.close()}}}function Dn(e,t,r={}){let o=r.startRelay??Nn,n=r.onNotification??pn,i=o({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:n});return{stop:()=>i.stop()}}var Vs=60;async function On(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=t.timeoutSeconds??Vs,c=Ke({entityType:t.entityType,projectKey:n,taskKey:i,branchPath:s}),d,l=new Promise(y=>{d=setTimeout(()=>y({kind:"timeout"}),a*1e3)}),u=c.promise.then(y=>({kind:"notification",payload:y})),p=await Promise.race([u,l]);return c.cancel(),clearTimeout(d),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function b(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",o=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",n=t.componentId??t.conceptId??"?";console.log(`${o} ${r} [${n}] ${t.message??""}`)}}var ar=S(require("http")),Qe=require("child_process"),cr=require("util");var Me=S(require("fs")),Fn=S(require("os")),Be=S(require("path"));function Rt(){return Be.join(Fn.homedir(),".authoring-cli-chrome")}function H(){return Be.join(Rt(),"profile")}function qs(){return Be.join(H(),"Local State")}function Hs(){let e=qs();if(!Me.existsSync(e))return[];let t;try{t=JSON.parse(Me.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([o,n])=>({directoryName:o,displayName:typeof n?.name=="string"&&n.name?n.name:o}))}var At="authoring-cli";function Ue(e=Hs()){return e.find(r=>r.directoryName===At)??{directoryName:At,displayName:At}}var Un=require("child_process"),Vn=require("util"),ke=S(require("fs")),Ye=S(require("os")),Ce=S(require("path"));var Ln=require("child_process"),_n=require("util"),Ve=S(require("crypto")),G=S(require("fs")),Js=(0,_n.promisify)(Ln.exec);function $t(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}var Gs="peanuts";async function Et(e=process.platform){if(e==="darwin"){let{stdout:t}=await Js('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}if(e==="linux")return Gs;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}var Kn=1003,Ws=1;function Pt(e){if(e==="darwin")return Kn;if(e==="linux")return Ws;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function jt(e,t=Kn){return Ve.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function Nt(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let o=r.subarray(0,3).toString("utf8");if(o!=="v10"&&o!=="v11")return null;let n=Buffer.alloc(16,32),i=r.subarray(3),s;try{let d=Ve.createDecipheriv("aes-128-cbc",t,n);s=Buffer.concat([d.update(i),d.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&$t(a)&&!$t(s)&&(c=a),$t(c)?c.toString("utf8"):null}function qe(e,t){G.copyFileSync(e,t);for(let r of["-wal","-shm"]){let o=e+r;G.existsSync(o)&&G.copyFileSync(o,t+r)}}function He(e){for(let t of[e,e+"-wal",e+"-shm"])try{G.unlinkSync(t)}catch{}}var Mn=S(require("fs"));var Bn=[{path:"/usr/bin/chromium",configDir:"chromium"},{path:"/usr/bin/chromium-browser",configDir:"chromium"},{path:"/usr/bin/google-chrome-stable",configDir:"google-chrome"},{path:"/usr/bin/google-chrome",configDir:"google-chrome"},{path:"/snap/bin/chromium",configDir:"chromium"}],hl=Array.from(new Set(Bn.map(e=>e.configDir)));function Je(){return Bn.find(e=>Mn.existsSync(e.path))??null}function Ge(e){let t=null;return async(r,o)=>{if(!r)return!1;if(!e)return r!==o;if(r===t)return!1;let n=await e(r);return n||(t=r),n}}var qn=(0,Vn.promisify)(Un.exec),We=class extends Error{},ne=class extends Error{};function Dt(e){return Ce.join(H(),e,"Cookies")}function Ys(e=process.platform){return e==="linux"?Je()!==null:ke.existsSync("/Applications/Google Chrome.app")}function Xs(e){let t=e.split(".").filter(Boolean),r=[];for(let o=0;o+1<t.length;o++){let n=t.slice(o).join(".");r.push(n,`.${n}`)}return r}function zs(e){let t=e?.code;return t==="EPERM"||t==="EACCES"}async function Ot(e,t,r,o=process.platform){let n=Dt(e);if(!n||!ke.existsSync(n))return null;let i=Ce.join(Ye.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);try{qe(n,i);let s;try{s=await Et(o)}catch{return null}let a=jt(s,Pt(o)),c=p=>`'${p.replace(/'/g,"''")}'`,l=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Xs(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await qn(`sqlite3 "${i}" "${l}"`);return Nt(u.trim(),a)}catch{return null}finally{He(i)}}async function Qs(e,t=process.platform,r=25){let o=Dt(e);if(!o||!ke.existsSync(o))return{checked:0,decrypted:0};let n=Ce.join(Ye.tmpdir(),`authoring-cli-chrome-cookies-diag-${process.pid}-${Date.now()}.db`);try{qe(o,n);let i;try{i=await Et(t)}catch{return{checked:0,decrypted:0}}let s=jt(i,Pt(t)),{stdout:a}=await qn(`sqlite3 "${n}" "SELECT hex(encrypted_value) FROM cookies WHERE length(encrypted_value) > 0 LIMIT ${r};"`),c=a.split(`
7
+ `).map(l=>l.trim()).filter(Boolean),d=0;for(let l of c)Nt(l,s)!==null&&d++;return{checked:c.length,decrypted:d}}catch{return{checked:0,decrypted:0}}finally{He(n)}}function Zs(e){let t=Dt(e);if(!ke.existsSync(t))return null;let r=Ce.join(Ye.tmpdir(),`authoring-cli-chrome-cookies-precheck-${process.pid}-${Date.now()}.db`);try{return qe(t,r),null}catch(o){return zs(o)?`Cannot read Chrome's cookie file for profile "${e}" at ${t} (permission denied). This is this app's own dedicated directory, not a protected system location \u2014 check its permissions, and that nothing else (an unusual sandboxing setup, a read-only filesystem mount, etc.) is restricting access to it, then try again.`:null}finally{He(r)}}function ea(e){return new Promise(t=>setTimeout(t,e))}async function Hn(e,t={}){let r=t.platform??process.platform,o=t.isChromeInstalled??(()=>Ys(r));if(r!=="darwin"&&r!=="linux")throw new We(`Automatic session capture is only supported on macOS or Linux with Chrome/Chromium. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!o())throw new We(r==="darwin"?"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.":'Automatic session capture requires a Chromium/Chrome binary (checked common Debian install paths), but none was found. Install one (e.g. "apt install chromium" in this proot-distro Debian), or use the manual cookie-paste fallback instead.');let n=t.readCookie??((g,I,E)=>Ot(g,I,E,r)),i=t.sleep??ea,s=t.onWarning??(g=>console.error(g)),a=t.checkCookieFileReadable??Zs,c=t.diagnoseDecryption??Qs,d=Ge(t.validateCookie),l=e.pollIntervalMs??750,u=e.timeoutMs??15e3,p=a(e.profileDirectory);p&&s(p);let y=await n(e.profileDirectory,e.host,e.cookieName);if(await d(y,y))return y;let k=Date.now()+u;for(;Date.now()<k;){let g=await n(e.profileDirectory,e.host,e.cookieName);if(await d(g,y))return g;await i(l)}let h=await c(e.profileDirectory,r).catch(()=>({checked:0,decrypted:0}));throw h.checked>0&&h.decrypted===0?new ne(`Timed out after ${u}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host} in Chrome profile "${e.profileDirectory}" \u2014 but this is NOT the usual "signed into the wrong window" mistake: ${h.checked} existing cookie(s) already in this exact profile's own jar all failed to decrypt with this tool's current decryption routine (0 of ${h.checked} readable). That means the sign-in almost certainly worked, but the installed Chrome has changed its cookie-encryption format to something this version of authoring-cli no longer knows how to decrypt \u2014 most likely from a Chrome auto-update since the last time login worked. Retrying login will not help. Use the manual cookie-paste fallback instead: open this same Chrome profile, open DevTools \u2192 Application/Storage \u2192 Cookies \u2192 ${e.host}, copy the "${e.cookieName}" row's Value, and run "authoring-cli login --cookie <value>".`):new ne(`Timed out after ${u}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host} in Chrome profile "${e.profileDirectory}" \u2014 the one and only profile this command ever reads or writes to. A common cause: sign-in happened in a DIFFERENT, already-open Chrome window/profile instead of the one this command opened \u2014 check that window's profile avatar (top-right corner) reads "${e.profileDirectory}", and that the window actually shows the real IMS login form rather than an unrelated already-signed-in page from another profile. Otherwise use the manual cookie-paste fallback (authoring-cli login --cookie <value>).`)}var re=S(require("fs")),Lt=S(require("path")),Jn=S(require("ws"));var W=class extends Error{};function Gn(e){try{re.unlinkSync(Lt.join(e,"DevToolsActivePort"))}catch{}}async function ta(e,t=1e4,r=100){let o=Lt.join(e,"DevToolsActivePort"),n=Date.now()+t;for(;;){if(re.existsSync(o)){let i=re.readFileSync(o,"utf8").trim().split(`
8
+ `),[s,a]=i;if(s&&a)return`ws://127.0.0.1:${s}${a}`}if(Date.now()>=n)throw new W(`Timed out after ${t}ms waiting for Chrome's DevToolsActivePort file at ${o} \u2014 --remote-debugging-port may not be supported on this Chrome build/platform.`);await new Promise(i=>setTimeout(i,r))}}var Ft=class e{constructor(t){this.socket=t;t.on("message",r=>{let o;try{o=JSON.parse(r.toString())}catch{return}let n=this.pending.get(o.id);n&&(this.pending.delete(o.id),o.error?n.reject(new Error(o.error.message)):n.resolve(o.result))})}socket;nextId=1;pending=new Map;static async connect(t,r=1e4,o=i=>new Jn.default(i),n=150){let i=Date.now()+r,s;for(;;)try{return await e.attemptConnect(t,Math.max(i-Date.now(),1),o)}catch(c){if(s=c,Date.now()>=i)break;await new Promise(d=>setTimeout(d,n))}let a=s instanceof Error?s.message:String(s);throw new W(`Could not connect to CDP at ${t} within ${r}ms: ${a}`)}static attemptConnect(t,r,o){return new Promise((n,i)=>{let s=o(t),a=setTimeout(()=>{s.terminate(),i(new Error(`timed out after ${r}ms`))},r);s.once("open",()=>{clearTimeout(a),n(new e(s))}),s.once("error",c=>{clearTimeout(a),i(c)})})}send(t,r={},o){let n=this.nextId++,i={id:n,method:t,params:r};return o&&(i.sessionId=o),new Promise((s,a)=>{this.pending.set(n,{resolve:s,reject:a}),this.socket.send(JSON.stringify(i),c=>{c&&(this.pending.delete(n),a(c))})})}close(){this.socket.close()}};async function oa(e,t,r=100){let o=Date.now()+t;for(;;){let{targetInfos:n}=await e.send("Target.getTargets"),i=n.find(s=>s.type==="page");if(i)return i.targetId;if(Date.now()>=o)throw new W(`No page target appeared via CDP within ${t}ms.`);await new Promise(s=>setTimeout(s,r))}}async function Wn(e,t={}){let r=t.waitForPort??ta,o=t.connect??Ft.connect,n=t.sleep??(u=>new Promise(p=>setTimeout(p,u))),i=e.setupTimeoutMs??1e4,s=e.pollIntervalMs??750,a=e.timeoutMs??12e4,c=Ge(t.validateCookie),d=await r(e.userDataDir,i),l=await o(d,i);try{let u=await oa(l,i),{sessionId:p}=await l.send("Target.attachToTarget",{targetId:u,flatten:!0});await l.send("Network.enable",{},p);let y=async()=>{let{cookies:g}=await l.send("Network.getCookies",{urls:[e.cookieUrl]},p);return g.find(I=>I.name===e.cookieName)?.value??null},k=await y();if(await c(k,k))return k;let h=Date.now()+a;for(;Date.now()<h;){let g=await y();if(await c(g,k))return g;await n(s)}throw new ne(`Timed out after ${a}ms waiting for a valid "${e.cookieName}" cookie for ${e.host} via Chrome's own DevTools Protocol \u2014 Chrome itself reports no live session, which rules out a decryption problem (this path never decrypts anything; Chrome hands the value over directly). A common cause: sign-in happened in a DIFFERENT, already-open Chrome window/profile instead of the one this command opened. Otherwise use the manual cookie-paste fallback (authoring-cli login --cookie <value>).`)}finally{l.close()}}var ze=require("child_process"),Xn=require("util"),F=S(require("fs")),zn=S(require("net")),Qn=(0,Xn.promisify)(ze.exec),Xe=1,xe=`:${Xe}`,na=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"],_t="/data/data/com.termux/files/usr/bin",Yn="com.termux.x11",ra=`${Yn}/${Yn}.MainActivity`,ia="termux-x11-start-app";function Kt(e){return`/tmp/.X11-unix/X${e}`}async function sa(){for(let e of na){if(e.startsWith("/")){if(F.existsSync(e))return e;continue}try{return await Qn(`command -v ${e}`),e}catch{}}return null}function aa(e,t=500){return new Promise(r=>{let o=Kt(e);if(!F.existsSync(o)){r(!1);return}let n=zn.createConnection({path:o}),i=s=>{n.removeAllListeners(),n.destroy(),r(s)};n.setTimeout(t),n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.once("timeout",()=>i(!1))})}function ca(e,t=1e4){let r=Date.now()+t;return new Promise((o,n)=>{let i=()=>{if(F.existsSync(Kt(e))){o();return}if(Date.now()>r){n(new Error(`Termux:X11's display socket for :${e} never appeared within ${t}ms`));return}setTimeout(i,100)};i()})}async function da(){if(!F.existsSync(_t))return;let e=`${_t}/${ia}`,t=`${_t}/bash`,o=`#!${F.existsSync(t)?t:"/bin/sh"}
9
+ am start --user 0 -n ${ra} >/dev/null 2>&1
10
+ `;try{F.writeFileSync(e,o,{mode:493}),F.chmodSync(e,493),await Qn(e,{timeout:5e3})}catch{}}async function Zn(e=process.platform){if(e!=="linux"||await aa(Xe))return xe;await da();let t=await sa();if(t===null)return xe;try{F.unlinkSync(Kt(Xe))}catch{}return(0,ze.spawn)(t,[xe],{detached:!0,stdio:"ignore"}).unref(),await ca(Xe),xe}var L=S(require("fs")),tr=S(require("os")),U=S(require("path"));var Ie=class extends Error{},la="com.ysgao.authoring-cli.chrome-login",or="authoring-cli-chrome",ua="/Applications/Google Chrome.app";function pa(e=ua,t=L.existsSync){let r=U.join(e,"Contents","MacOS","Google Chrome");if(t(r))return r;throw new Ie(`No Google Chrome installation found at ${e}. Install Google Chrome to use automatic session capture.`)}function er(e){return`'${e.replace(/'/g,"'\\''")}'`}function ma(e,t){return["#!/bin/sh","# Generated by authoring-cli. Do not edit \u2014 rewritten on every login launch.","# Flags are baked in deliberately: `open --args` does not reliably reach a script bundle","# executable, and Launch Services drops --args entirely when it hands off to an","# already-running Chrome instead of starting a genuinely new process \u2014 see","# assertLaunchFlagsBaked in chromeWrapperApp.ts.",`exec ${er(e)} \\`,t.map(r=>` ${er(r)}`).join(` \\
11
11
  `),""].join(`
12
- `)}function la(){return`<?xml version="1.0" encoding="UTF-8"?>
12
+ `)}function fa(){return`<?xml version="1.0" encoding="UTF-8"?>
13
13
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
14
14
  <plist version="1.0">
15
15
  <dict>
16
- <key>CFBundleExecutable</key><string>${tr}</string>
17
- <key>CFBundleIdentifier</key><string>${sa}</string>
16
+ <key>CFBundleExecutable</key><string>${or}</string>
17
+ <key>CFBundleIdentifier</key><string>${la}</string>
18
18
  <key>CFBundleName</key><string>authoring-cli sign-in</string>
19
19
  <key>CFBundlePackageType</key><string>APPL</string>
20
20
  <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
21
21
  <key>CFBundleShortVersionString</key><string>1.0</string>
22
22
  </dict>
23
23
  </plist>
24
- `}function ua(e,t){let r=[];if(e.includes(`--profile-directory=${t}`)||r.push(`--profile-directory=${t}`),e.includes("--user-data-dir=")||r.push("--user-data-dir="),r.length>0)throw new Ie(`Refusing to launch Chrome: its generated launch script is missing ${r.join(" and ")}. Launching without them would open a window in whichever profile the user's own Chrome already has active, instead of the dedicated "${t}" profile this command reads/writes cookies for.`)}function or(){return[U.join(Rt(),"launcher"),U.join(er.tmpdir(),"authoring-cli-chrome-launcher")]}function nr(){return`login-${process.pid}.app`}function rr(e){let t=e.chromeBinary??ca(),r=da(t,e.flags);ua(r,e.profileDirectory);let o=e.dirCandidates??or(),n=[];for(let i of o){let s=U.join(i,nr()),a=U.join(s,"Contents","MacOS");try{L.mkdirSync(a,{recursive:!0}),L.writeFileSync(U.join(s,"Contents","Info.plist"),la());let c=U.join(a,tr);return L.writeFileSync(c,r,{mode:493}),L.chmodSync(c,493),s}catch(c){n.push(`${i}: ${c instanceof Error?c.message:String(c)}`)}}throw new Ie(`Could not create the Chrome launcher bundle in any candidate directory (${n.join("; ")}).`)}function ir(e=or()){for(let t of e)try{L.rmSync(U.join(t,nr()),{recursive:!0,force:!0})}catch{}}var cr=(0,ar.promisify)(Ze.exec);function Mt(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}var pa=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"],dr=["--no-first-run","--no-default-browser-check","--remote-debugging-port=0"];async function ma(e,t){let r=He();if(!r)throw new Error('No Chromium/Chrome binary found (checked common Debian install paths). Install one (e.g. "apt install chromium" in this proot-distro Debian) and try again.');let o=process.env.DISPLAY||await Qn();(0,Ze.spawn)(r.path,[...dr,...pa,`--user-data-dir=${J()}`,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:o}}).unref()}async function fa(e,t){let r=`--user-data-dir=${J()}`,o=[r,`--profile-directory=${t}`,...dr,e],n=rr({flags:o,profileDirectory:t});await cr(`open -n -a ${(s=>`'${s.replace(/'/g,"'\\''")}'`)(n)}`),ka(r).then(s=>{s&&ir()})}var ga=1e4,ya=250;function ha(e){return new Promise(t=>setTimeout(t,e))}async function ka(e,t=ga,r=ya){let o=i=>`'${i.replace(/'/g,"'\\''")}'`,n=Date.now()+t;for(;;){try{let{stdout:i}=await cr(`pgrep -f ${o(e)}`);if(i.trim().length>0)return!0}catch{}if(Date.now()>=n)return!1;await ha(r)}}function Ca(e,t,r){return r==="linux"?ma(e,t):fa(e,t)}function xa(){return`<!DOCTYPE html>
24
+ `}function ga(e,t){let r=[];if(e.includes(`--profile-directory=${t}`)||r.push(`--profile-directory=${t}`),e.includes("--user-data-dir=")||r.push("--user-data-dir="),r.length>0)throw new Ie(`Refusing to launch Chrome: its generated launch script is missing ${r.join(" and ")}. Launching without them would open a window in whichever profile the user's own Chrome already has active, instead of the dedicated "${t}" profile this command reads/writes cookies for.`)}function nr(){return[U.join(Rt(),"launcher"),U.join(tr.tmpdir(),"authoring-cli-chrome-launcher")]}function rr(){return`login-${process.pid}.app`}function ir(e){let t=e.chromeBinary??pa(),r=ma(t,e.flags);ga(r,e.profileDirectory);let o=e.dirCandidates??nr(),n=[];for(let i of o){let s=U.join(i,rr()),a=U.join(s,"Contents","MacOS");try{L.mkdirSync(a,{recursive:!0}),L.writeFileSync(U.join(s,"Contents","Info.plist"),fa());let c=U.join(a,or);return L.writeFileSync(c,r,{mode:493}),L.chmodSync(c,493),s}catch(c){n.push(`${i}: ${c instanceof Error?c.message:String(c)}`)}}throw new Ie(`Could not create the Chrome launcher bundle in any candidate directory (${n.join("; ")}).`)}function sr(e=nr()){for(let t of e)try{L.rmSync(U.join(t,rr()),{recursive:!0,force:!0})}catch{}}var dr=(0,cr.promisify)(Qe.exec);function Mt(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}var ya=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"],lr=["--no-first-run","--no-default-browser-check","--remote-debugging-port=0"];async function ha(e,t){let r=Je();if(!r)throw new Error('No Chromium/Chrome binary found (checked common Debian install paths). Install one (e.g. "apt install chromium" in this proot-distro Debian) and try again.');let o=process.env.DISPLAY||await Zn();(0,Qe.spawn)(r.path,[...lr,...ya,`--user-data-dir=${H()}`,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:o}}).unref()}async function ka(e,t){let r=`--user-data-dir=${H()}`,o=[r,`--profile-directory=${t}`,...lr,e],n=ir({flags:o,profileDirectory:t});await dr(`open -n -a ${(s=>`'${s.replace(/'/g,"'\\''")}'`)(n)}`),ba(r).then(s=>{s&&sr()})}var Ca=1e4,xa=250;function Ia(e){return new Promise(t=>setTimeout(t,e))}async function ba(e,t=Ca,r=xa){let o=i=>`'${i.replace(/'/g,"'\\''")}'`,n=Date.now()+t;for(;;){try{let{stdout:i}=await dr(`pgrep -f ${o(e)}`);if(i.trim().length>0)return!0}catch{}if(Date.now()>=n)return!1;await Ia(r)}}function va(e,t,r){return r==="linux"?ha(e,t):ka(e,t)}function Sa(){return`<!DOCTYPE html>
25
25
  <html>
26
26
  <head>
27
27
  <meta charset="utf-8">
@@ -32,20 +32,20 @@ am start --user 0 -n ${ea} >/dev/null 2>&1
32
32
  <h3>You're signed in.</h3>
33
33
  <p>Return to your terminal \u2014 the CLI is finishing sign-in automatically. You can close this tab.</p>
34
34
  </body>
35
- </html>`}async function Ia(e){let t=Date.now();try{return await Hn({userDataDir:J(),host:e.host,cookieName:e.cookieName,cookieUrl:`https://${e.host}/`,timeoutMs:e.timeoutMs},{validateCookie:e.validateCookie})}catch(r){if(!(r instanceof W))throw r;let o=Math.max(e.timeoutMs-(Date.now()-t),5e3);return qn({...e,timeoutMs:o},{validateCookie:e.validateCookie})}}function lr(e,t={}){let r=e.cookieName??Mt(e.host),o=t.platform??process.platform,n=t.openChrome??((d,l)=>Ca(d,l,o)),i=t.resolveProfile??Ve,s=t.captureCookie??Ia,a=e.timeoutMs??12e4,c=i();return new Promise((d,l)=>{let u=!1,p=k=>{u||(u=!0,y.close(),k())},y=sr.createServer((k,h)=>{if((k.url||"/").split("?")[0]==="/callback"){h.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),h.end(xa());return}h.writeHead(404),h.end()});y.listen(0,"127.0.0.1",()=>{let h=`http://localhost:${y.address().port}/callback`,g=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(h)}`;(async()=>{try{Gn(J()),await n(g,c.directoryName);let I=await s({profileDirectory:c.directoryName,host:e.host,cookieName:r,timeoutMs:a,validateCookie:t.validateCookie});p(()=>d({cookie:`${r}=${I}`}))}catch(I){p(()=>l(I))}})()}),y.on("error",k=>p(()=>l(k)))})}var R=v(require("fs")),G=v(require("path")),ur="AUTHORING_CLI_HOME";function ba(){return G.join(process.cwd(),".authoring-cli")}function va(){let e=process.env[ur];return e&&e.trim()!==""?G.resolve(e):null}function ve(){return va()??ba()}function be(e){return G.join(e,"session.json")}function ie(){let e=be(ve());if(!R.existsSync(e))return null;let t=R.readFileSync(e,"utf8");return JSON.parse(t)}function Se(e){let t=ve(),r={...e,updatedAt:new Date().toISOString()};try{R.mkdirSync(t,{recursive:!0,mode:448}),R.writeFileSync(be(t),JSON.stringify(r,null,2),{mode:384})}catch(o){let n=o?.code;throw n==="EPERM"||n==="EACCES"?new Error(`Couldn't write the session to ${be(t)} (${n}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${ur} to an explicit, writable location.`):o}}function pr(){let e=be(ve());R.existsSync(e)&&R.unlinkSync(e)}function we(){return be(ve())}var se="AUTHORING_CLI_CONTEXT",_="AUTHORING_CLI_TASK",et="AUTHORING_CLI_PROJECT",Sa=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function tt(e){let t=process.env[e];return t&&t.trim()!==""?t.trim():null}function mr(e){if(!Sa.test(e))throw new Error(`Invalid context name "${e}": use letters, digits, ".", "_" or "-" (max 64, starting with a letter or digit), e.g. "ANCRJAN22-1069".`);return e}function Y(){let e=tt(se);return e===null?null:mr(e)}function wa(e){let t=/^(.+)-\d+$/.exec(e);return t?t[1]:null}function Te(){let e=tt(_);if(e===null){if(tt(et)!==null)throw new Error(`${et} is set without ${_} \u2014 set both, or neither.`);return null}let t=tt(et)??wa(e);if(!t)throw new Error(`${_}=${e} doesn't look like "<PROJECT>-<n>"; also set ${et}.`);return{projectKey:t,taskKey:e,branchPath:""}}function Bt(){return G.join(ve(),"contexts")}function Ut(e){return G.join(Bt(),`${mr(e)}.json`)}function fr(e,t){let r;try{r=JSON.parse(R.readFileSync(e,"utf8"))}catch(o){throw new Error(`Context "${t}" is unreadable (${e}): ${o instanceof Error?o.message:String(o)}. Re-run select-task, or delete the file.`)}return{name:t,currentTask:r.currentTask??null,updatedAt:r.updatedAt??null}}function Ta(e){let t=Ut(e);return R.existsSync(t)?fr(t,e):null}function Vt(){let e=Bt();return R.existsSync(e)?R.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>fr(G.join(e,t),t.slice(0,-5))).sort((t,r)=>t.name.localeCompare(r.name)):[]}function gr(e){let t=Ut(e);return R.existsSync(t)?(R.unlinkSync(t),!0):!1}function qt(){let e=Y(),t=Te();return t?{task:t,source:"pin",context:e}:e?{task:Ta(e)?.currentTask??null,source:"context",context:e}:{task:null,source:"none",context:null}}function Aa(){return qt().task}var Ra=`Name this session's context with "--context <name>" (or ${se}=<name>) \u2014 e.g. one per task \u2014 or pin it with ${_}=<TASK-KEY>; or pass --project/--task on every command.`;function X(e){let t=Te();if(t){if(e&&e.taskKey!==t.taskKey)throw new Error(`This session is pinned to ${t.projectKey}/${t.taskKey} (${_}) and can't switch to ${e.projectKey}/${e.taskKey}. Use a separate session (or unset the pin) for the other task.`);if(!e)throw new Error(`This session is pinned to ${t.projectKey}/${t.taskKey} (${_}); a newly created task can't become its selection. Pass --no-select.`);return}if(!Y())throw new Error(`No context to store a task selection in. ${Ra}`)}function yr(e){let t=Te();if(t&&e&&e!==t.taskKey)throw new Error(`--task ${e} conflicts with this session's pin ${t.projectKey}/${t.taskKey} (${_}). Refusing to act on a different task from a pinned session; use a separate session for it.`)}function ae(e){X(e);let t=Y();if(!t)return;let r=Bt(),o=Ut(t),n=JSON.stringify({currentTask:e,updatedAt:new Date().toISOString()},null,2),i=`${o}.${process.pid}.tmp`;try{R.mkdirSync(r,{recursive:!0,mode:448}),R.writeFileSync(i,n,{mode:384}),R.renameSync(i,o)}catch(s){throw R.rmSync(i,{force:!0}),s}}function hr(e,t){return Vt().filter(r=>r.name!==t&&r.currentTask?.taskKey===e).map(r=>r.name)}function kr(e){return{...e,currentTask:Aa()}}async function $a(e){let t=ie();if(!t||t.imsEndpoint!==e)return null;let r=await oe(e,t.cookie).catch(()=>null);return r?{cookie:t.cookie,account:r,currentTask:t.currentTask}:null}async function Ea(e,t,r,o){let n=await Ot(o,t,r).catch(()=>null);if(!n)return null;let i=`${r}=${n}`,s=await oe(e,i).catch(()=>null);return s?{cookie:i,account:s}:null}function ot(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 nt(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:o,explicit:n,source:i}of e)console.log(` ${(o+":").padEnd(t+2)}${r} (${n?"from flag":i})`)}async function Cr(e){let t=e.environment?eo(e.environment):ue;if(!t){console.error(`Unknown environment: ${e.environment}
36
- Expected one of: ${Pe.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=z[t],o=e.imsEndpoint||r.imsEndpoint,n=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=new URL(o).hostname}catch{console.error(`Invalid --ims-endpoint: ${o}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||Mt(s),d=t===ue&&!e.environment?`${t}, default`:t,l=[{url:o,label:"IMS",explicit:!!e.imsEndpoint},{url:n,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(g=>({...g,source:d}));if(e.cookie){let g=`${c}=${e.cookie}`,I=await oe(o,g).catch(()=>null);if(!I){console.error(`That cookie value was rejected by IMS (${o}) \u2014 either it's stale/expired, or it's not the right cookie. Re-copy the current "${c}" cookie's Value from the signed-in browser's DevTools (Application/Storage tab \u2192 Cookies) and try again.`),process.exitCode=1;return}Se({cookie:g,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:I,currentTask:null}),console.log(`${ot(I)} (from --cookie \u2014 no browser opened.)`),nt(l),console.log(` Session: ${we()}`);return}let u=await $a(o);if(u){Se({cookie:u.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:u.account,currentTask:u.currentTask}),console.log(`${ot(u.account)} (reused the already-stored session \u2014 no Chrome involved at all.)`),nt(l),console.log(` Session: ${we()}`);return}let p=Ve(),y=await Ea(o,s,c,p.directoryName);if(y){Se({cookie:y.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:y.account,currentTask:null}),console.log(`${ot(y.account)} (reused an existing Chrome session in profile "${p.directoryName}" \u2014 no browser opened.)`),nt(l),console.log(` Session: ${we()}`);return}console.log(`Opening Chrome (profile "${p.directoryName}") to sign in to ${o} ...`),console.log(` This is a separate, dedicated Chrome profile for authoring-cli, isolated from your everyday browsing profile \u2014 it opens its own window and (the first time) starts out NOT signed in, even if another Chrome window/profile already is. Sign in inside THAT new window \u2014 check its profile avatar (top-right) reads "${p.directoryName}" \u2014 not whichever Chrome window happened to already be in front.`);let k;try{k=await lr({imsEndpoint:o,host:s,cookieName:c},{validateCookie:g=>oe(o,`${c}=${g}`).then(I=>I!==null)})}catch(g){console.error(g instanceof Error?g.message:String(g)),process.exitCode=1;return}if(!k){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let h=await oe(o,k.cookie).catch(()=>null);Se({cookie:k.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:h,currentTask:null}),console.log(ot(h)),nt(l),console.log(` Session: ${we()}`)}async function xr(){pr(),console.log("Signed out.")}var it=v(require("fs")),rt=v(require("path"));async function Ir(){let e=[rt.join(__dirname,"../../HELP.md"),rt.join(__dirname,"../HELP.md"),rt.join(process.cwd(),"HELP.md")];for(let t of e)try{if(it.existsSync(t)){let r=it.readFileSync(t,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function f(){let e;try{e=ie(),e&&(e=kr(e))}catch(t){console.error(t instanceof Error?t.message:String(t)),process.exit(1)}return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function Jt(e){let t=e.account;return t?.login??t?.username}function m(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,currentUsername:Jt(e),onLog:t=>console.error(t)}}function br(e){return e.projectKey??e.key??"?"}async function vr(e){let t=f(),r=m(t),o=await In(r);if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log("No projects available.");return}let n=Math.max(...o.map(i=>br(i).length))+1;for(let i of o){let s=i.title??"";console.log(`${br(i).padEnd(n)}${s?`"${s}"`:""}`)}}function st(e){return e.taskKey??e.key??"?"}function Sr(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Pa(e){return e.projectKey||st(e).split("-")[0]||"?"}function Gt(e,t){let r=new Map;for(let o of e){let n=t(o);r.set(n,(r.get(n)??0)+1)}return[...r].sort((o,n)=>n[1]-o[1]||o[0].localeCompare(n[0]))}function Ht(e,t){let r=Math.max(...t.map(([n])=>n.length)),o=Math.max(...t.map(([,n])=>String(n).length));console.log(""),console.log(`${e}:`);for(let[n,i]of t)console.log(` ${n.padEnd(r)} ${String(i).padStart(o)}`)}async function wr(e){let t=f(),r=m(t),o=e.mine||!e.project,n=o?await vn(r):await bn(r,e.project);if(o&&e.project){let l=e.project.toLowerCase();n=n.filter(u=>(u.projectKey??"").toLowerCase()===l||st(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();n=n.filter(u=>(u.status??"").toLowerCase()===l)}let i=Gt(n,Pa),s=Gt(n,Sr),a=Gt(n,l=>l.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:n.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),byStatus:Object.fromEntries(a)}:n,null,2));return}let c=[o?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(n.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${n.length} task${n.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),i.length>1&&Ht("By project",i),!o&&s.length>1&&Ht("By assignee",s),a.length>1&&Ht("By status",a);return}let d=Math.max(...n.map(l=>st(l).length))+1;for(let l of n){let u=l.summary??l.title??"",p=l.status?` status=${l.status}`:"",y=o?"":` [${Sr(l)}]`;console.log(`${st(l).padEnd(d)}${u?`"${u}"`:""}${p}${y}`)}}async function Tr(e){e.noSelect||X();let t=f(),r=m(t),o=Jt(t),n=e.unassigned?void 0:e.assignee||o,i=await Sn(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:n});if(!i.task){console.error(i.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let s=i.task,a=s.key??s.taskKey,c=s.branchPath;if(e.json)console.log(JSON.stringify(s,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${s.summary??e.summary}"${s.status?` status=${s.status}`:""}`),c&&console.log(` branch: ${c}`);let d=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await ee(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}ae({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function Ar(e){let t=f(),r=m(t);if(!e.task){let i=await wn(r,e.project);if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${i.length} deleted task${i.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let s of i){let a=s.assignee?.displayName??s.assignee?.username??"unassigned";console.log(` ${s.key} "${s.summary??""}" [${a}]`)}return}e.noSelect||X({projectKey:e.project,taskKey:e.task});let o=await Tn(r,{projectKey:e.project,taskKey:e.task});if(o.error){console.error(o.error),process.exitCode=1;return}if(o.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${o.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${o.task?.status??"In Progress"})`);let n=o.task?.branchPath;if(n){let i=await ee(r,n);if(!i.ok){console.error(`Task recovered, but its branch could not be prepared: ${i.error}`),process.exitCode=1;return}console.log(i.created?` created branch ${n}`:` branch ${n} still holds its content`)}e.noSelect||!n||(ae({projectKey:e.project,taskKey:e.task,branchPath:n}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Rr(e){X({projectKey:e.project,taskKey:e.task});let t=f(),r=m(t),o=await K(r,e.project,e.task);if(!o||!o.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let n=await ee(r,o.branchPath);if(!n.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${n.error}`),process.exitCode=1;return}ae({projectKey:e.project,taskKey:e.task,branchPath:o.branchPath});let i=Y();console.log(`\u2713 Current task set to ${e.project}/${e.task} (${o.branchPath})${i?` in context "${i}"`:""}`);let s=hr(e.task,i);s.length&&console.error(` Warning: context(s) ${s.map(a=>`"${a}"`).join(", ")} also hold ${e.task} \u2014 concurrent writes to one branch contend for its lock.`),n.created&&console.log(` created branch ${o.branchPath}`)}async function $r(e){let t=f(),r=qt();if(!r.task){r.source==="context"?console.log(`Context "${r.context}" has no task selected yet. Run "select-task --context ${r.context} --project <projectKey> --task <taskKey>".`):console.log(`No task context. Name this session with "--context <name>" (or ${se}), pin it with ${_}, or pass --project/--task explicitly to any command.`);let a=ie()?.currentTask;a&&console.log(`(Ignoring the old shared selection ${a.projectKey}/${a.taskKey} in session.json \u2014 it is no longer used.)`);return}let{projectKey:o,taskKey:n}=r.task,i=r.task.branchPath||await ut(m(t),o,n)||"(branch not resolved)",s=r.source==="pin"?`pinned via ${_}`:`context "${r.context}"`;console.log(`Current task: ${o}/${n} (${i}) [${s}]`),(e.project||e.task)&&((!e.project||e.project===o)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function Er(e){if(e.remove!==void 0){if(!e.remove){console.error("--remove needs a context name."),process.exitCode=1;return}console.log(gr(e.remove)?`\u2713 Removed context "${e.remove}".`:`No context named "${e.remove}".`);return}let t=Vt(),r=Y(),o=Te();t.length===0&&console.log("No contexts yet. Create one with: select-task --context <name> --project <projectKey> --task <taskKey>");let n=new Map;for(let i of t)i.currentTask&&n.set(i.currentTask.taskKey,[...n.get(i.currentTask.taskKey)??[],i.name]);for(let i of t){let s=i.name===r?"*":" ",a=i.currentTask,c=a&&(n.get(a.taskKey)?.length??0)>1?" (same task as another context \u2014 branch-lock contention possible)":"";console.log(`${s} ${i.name}: ${a?`${a.projectKey}/${a.taskKey} (${a.branchPath})`:"no task selected"}${i.updatedAt?` [${i.updatedAt}]`:""}${c}`)}o?console.log(`This session is pinned to ${o.projectKey}/${o.taskKey}.`):r&&console.log("(* = this session's context)")}async function Pr(e){let t=f(),r=m(t),o=await lo(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300&&n.conceptId){console.log(`Created concept ${n.conceptId}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to create concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function jr(e){let t=f(),r=m(t),o={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},n=e.checkStatedParentsDefinitionStatus?await en(r,o,t.currentTask):await De(r,o,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 Nr(e){let t=f(),r=m(t),o=await Ne(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,descriptions:e.descriptions,descriptionFull:e.descriptionFull,axioms:e.axioms,inferred:e.inferred,gciAxiomsCount:e.gciAxiomsCount,full:e.full,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get concept (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Dr(e){let t=f(),r=m(t),o=await po(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to find references (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Or(e){let t=f(),r=m(t),o=await _e(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let s=n.error?n.error:JSON.stringify(n);console.error(`Failed to validate concept (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}let i=n.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}b(i),n.hasErrors&&(process.exitCode=1)}async function Fr(e){let t=f(),r=m(t),o=e.checkStatedParentsDefinitionStatus?await cn(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await q(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to list concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function Lr(e){let t=f(),r=m(t),o=await dn(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${o.statusCode}): ${n.error??JSON.stringify(n)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(o.body,null,2)),n.summary&&(n.summary.withIssues>0||n.summary.failed>0)&&(process.exitCode=1);return}let i=n.results??[],s=n.summary;if(i.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of i){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),b(a.validationResults)}if(s){console.log("");let a=[`${s.validated} validated`,`${s.clean} clean`,`${s.withIssues} with issues`];s.skippedDeleted&&a.push(`${s.skippedDeleted} skipped (deleted on this branch)`),s.failed&&a.push(`${s.failed} failed`),console.log(a.join(", ")+".")}s&&(s.withIssues>0||s.failed>0)&&(process.exitCode=1)}async function Kr(e){let t=f(),r=m(t),o=await ln(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to fetch concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function _r(e){let t=f(),r=m(t),o=await To(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Mr(e){let t=f(),r=m(t),o=await Ao(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Br(e){let t=f(),r=m(t),o=await Xo(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to remove relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Ur(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=f(),o=m(r),n=await zo(o,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to remove role group (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Vr(e){let t=f(),r=m(t),o=await Eo(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to update description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function qr(e){let t=f(),r=m(t),o=await Po(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set case significance (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Jr(e){let t=f(),r=m(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.message}`),process.exitCode=1;return}if(!Array.isArray(s)||s.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await Oo(r,{conceptId:e.id,entries:s,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${s.length} description(s) on concept ${e.id}`),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 o=await Do(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){let s=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${s.join(", ")})`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set acceptability (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Gr(e){let t=f(),r=m(t),o=await $o(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to inactivate concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Hr(e){let t=f(),r=m(t),o=await Ro(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set definition status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Wr(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=f(),o=m(r),n=await Uo(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Yr(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=f(),o=m(r),n=await Vo(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Xr(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=f(),o=m(r),n=await Jo(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function zr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=f(),o=m(r),n=await qo(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Qr(e){if(!e.expression||!e.expression.trim()){console.error("--expression must be a non-empty OWL functional-syntax axiom string."),process.exitCode=1;return}let t=f(),r=m(t),o=await nn(r,{propertyId:e.propertyId,owlExpression:e.expression,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added property axiom to ${e.propertyId}${n.memberId?` (memberId ${n.memberId})`:""}: ${e.expression}`),console.log("Note: this write returns no structured validationResults (no ?validate=true equivalent for this endpoint). Syntactically invalid OWL is still rejected (as an HTTP 500 with a raw parser error, not a 400), but a semantically wrong-but-valid expression would only surface downstream, e.g. on the next classification run.");return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to add property axiom (HTTP ${o.statusCode}): ${i}`),o.statusCode===500&&console.error('WARNING: a 500 here means the expression reached Snowstorm and its OWL parser rejected it \u2014 confirmed live, that can leave this task branch permanently locked server-side (not just this failed write). Try a plain read (e.g. get-property-axioms) or another small write next; if that also fails with "already locked", the branch needs an admin to run the unlock action \u2014 a regular author/project-lead account cannot self-service it.'),process.exitCode=1}async function Zr(e){let t=f(),r=m(t),o=await rn(r,{conceptId:e.id,activeOnly:e.activeOnly,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get property axioms (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function ei(e){let t=f(),r=m(t),o=await sn(r,{conceptId:e.id,memberId:e.memberId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted property axiom ${e.memberId} from ${e.id}${n.owlExpression?`: ${n.owlExpression}`:""}`);return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to delete property axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ti(e){let t=f(),r=m(t),o=await tn(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function oi(e){let t=f(),r=m(t),o=await Fo(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ni(e){let t=f(),r=m(t),o=await Lo(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ri(e){let t=f(),r=m(t),o=await Ko(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to restore description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ii(e){let t=f(),r=m(t),o=await Mo(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to replace FSN (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function si(e){let t=f(),r=m(t),o=await _o(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set description inactivation reason (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ai(e){let t=f(),r=m(t),o=await Go(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ci(e){let t=f(),r=m(t),o=await Ho(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function di(e){let t=f(),r=m(t),o=await Yo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){if(n.alreadyConformed)console.log(`Concept ${e.id}'s axiom${n.axiomId?` ${n.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(n.replacedAxiomId){let s=Array.isArray(n.addResult?.classAxioms)?n.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=s.length>0?s[s.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${n.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to transform axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function li(e){let t=f(),r=m(t),o=await Le(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}if(n.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${n.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${n.axiomId}) \u2014 ${n.message}`)}async function ui(e){let t=f(),r=m(t),o=await Qo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function pi(e){let t=f(),r=m(t),o=await Zo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}function ce(e){let t=e.account?.login;return t?Nn(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 mi(e){let t=f(),r=m(t),o=ce(t),n;try{n=await kn(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.statusCode<300){i.finalStatus!==void 0?(console.log(`Classification ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),i.details&&console.log(JSON.stringify(i.details,null,2)),i.save&&(i.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${i.save.error?`: ${i.save.error}`:""}${i.save.status?` (status: ${i.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${i.jobId} (${i.status})`),i.timedOut&&(process.exitCode=1);return}let s=i.details!==void 0?` \u2014 details: ${JSON.stringify(i.details)}`:"";console.error(`Failed to start classification (HTTP ${n.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function fi(e){let t=f(),r=m(t),o=await hn(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check classification status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function gi(e){let t=f(),r=m(t),o=ce(t),n;try{n=await xn(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.statusCode<300){i.finalStatus!==void 0?console.log(`Validation ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),i.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${n.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function yi(e){let t=f(),r=m(t),o=await Cn(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check validation status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function hi(e){let t=f(),r=m(t),o=ce(t);try{let n=await Dn(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=n.body;if(n.statusCode<200||n.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{o?.stop()}}var Xt=v(require("os")),de=v(require("path"));var T=v(require("fs")),Wt=v(require("os")),w=v(require("path")),j="authoring-cli",M=["claude","codex"];function at(e){let t=[w.resolve(e,"..","skills",j),w.resolve(e,"..","..","skills",j)];for(let r of t)if(T.existsSync(w.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${j}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function ja(e){let t=[];return T.existsSync(w.join(e,".claude"))&&t.push("claude"),T.existsSync(w.join(e,".codex"))&&t.push("codex"),t}function Ae(e,t){if(e==="all")return[...M];if(e){let o=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),n=o.filter(i=>!M.includes(i));if(n.length)throw new Error(`Unknown --agent value(s): ${n.join(", ")}. Supported: ${M.join(", ")}, all.`);return o}let r=ja(t);return r.length?r:["claude"]}var Ci="# authoring-cli \u2014 SNOMED CT authoring guidance";function Na(e){let t=w.join(e,"SKILL.md"),r=w.join(e,"references","batch-authoring.md");return[Ci,"",`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(`
37
- `)}function ct(e){try{return w.resolve(w.dirname(e),T.readlinkSync(e))}catch{return null}}function Re(e){try{return T.lstatSync(e)}catch{return null}}function Yt(e){let t=ct(e);return t?T.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:Re(e)?.isDirectory()?"an existing directory":"an existing file"}function xi(e){let t=ct(e);return t!==null&&w.basename(t)===j&&w.basename(w.dirname(t))==="skills"}function Ii(e){if(!Re(e)?.isFile())return!1;try{return T.readFileSync(e,"utf8").startsWith(Ci)}catch{return!1}}function ki(e){return T.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>w.relative(e,w.join(t.parentPath,t.name))).sort()}function bi(e,t){if(!t||!T.existsSync(t))return!1;try{let r=ki(t);return r.join(`
38
- `)!==ki(e).join(`
39
- `)?!1:r.every(o=>T.readFileSync(w.join(e,o)).equals(T.readFileSync(w.join(t,o))))}catch{return!1}}function Da(e,t,r){let o=e.project?w.join(r,".claude","skills"):w.join(t,".claude","skills"),n=w.join(o,j),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+w.sep)?w.relative(w.dirname(n),i):i,a=Re(n),c=!1;if(a){let d=ct(n);if(d===i&&T.existsSync(d))return{agent:"claude",path:n,status:"already-current",kind:"symlink",detail:i};if(!(xi(n)||bi(n,i))&&!e.force)return{agent:"claude",path:n,status:"blocked",kind:"symlink",detail:Yt(n)};T.rmSync(n,{recursive:!0,force:!0}),c=!0}T.mkdirSync(o,{recursive:!0});try{return T.symlinkSync(s,n,"dir"),{agent:"claude",path:n,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(d){let l=d.code;if(l!=="EPERM"&&l!=="EACCES")throw d;return T.cpSync(i,n,{recursive:!0}),{agent:"claude",path:n,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function Oa(e,t){let r=w.join(t,".codex","prompts"),o=w.join(r,`${j}.md`),n=Na(e.shippedSkillDir),i=Re(o),s=!1;if(i){if((i.isFile()?T.readFileSync(o,"utf8"):null)===n)return{agent:"codex",path:o,status:"already-current",kind:"pointer"};if(!Ii(o)&&!e.force)return{agent:"codex",path:o,status:"blocked",kind:"pointer",detail:Yt(o)};T.rmSync(o,{recursive:!0,force:!0}),s=!0}return T.mkdirSync(r,{recursive:!0}),T.writeFileSync(o,n,"utf8"),{agent:"codex",path:o,status:s?"replaced":"installed",kind:"pointer"}}function vi(e){let t=e.homeDir??Wt.homedir(),r=e.cwd??process.cwd();return(e.agents??Ae(void 0,t)).map(n=>n==="claude"?Da(e,t,r):Oa(e,t))}function Si(e){let t=e.homeDir??Wt.homedir(),r=e.cwd??process.cwd();return e.agents.map(o=>{let n=o==="claude"?w.join(e.project?w.join(r,".claude"):w.join(t,".claude"),"skills",j):w.join(t,".codex","prompts",`${j}.md`);if(!Re(n))return{agent:o,path:n,status:"not-registered"};if(!(o==="claude"?xi(n)||bi(n,e.shippedSkillDir):Ii(n))&&!e.force)return{agent:o,path:n,status:"left-alone",detail:`${Yt(n)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=ct(n)??void 0;return T.rmSync(n,{recursive:!0,force:!0}),{agent:o,path:n,status:"removed",detail:s}})}function wi(e){let t=Xt.homedir();return e===t||e.startsWith(t+de.sep)?de.join("~",de.relative(t,e)):e}function Fa(e){let t=wi(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${wi(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 Ti(e){let t=at(__dirname),r=Ae(e.agent,Xt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let o=vi({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),n=o.filter(a=>a.status==="installed"||a.status==="replaced"),i=o.filter(a=>a.status==="blocked");console.log(n.length?`Installed skill '${j}' for:`:i.length?`Could not install skill '${j}':`:`Skill '${j}' is already registered:`);for(let a of o)console.log(` ${a.agent.padEnd(7)} ${Fa(a)}`);if(e.project&&r.includes("claude")&&console.log(`
40
- Project-scoped install: commit .claude/skills only if authoring-cli is a dependency of this
41
- repo \u2014 a link into a globally installed package resolves on your machine alone.`),i.length){process.exitCode=1;return}n.length&&(console.log(`
42
- Restart your agent, then use /${j}.`),o.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let s=M.filter(a=>!r.includes(a));s.length&&!e.agent&&console.log(`
43
- Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var zt=v(require("os")),le=v(require("path"));function Ai(e){let t=zt.homedir();return e===t||e.startsWith(t+le.sep)?le.join("~",le.relative(t,e)):e}function La(e){let t=Ai(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${Ai(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function Ri(e){let t=e.agent?Ae(e.agent,zt.homedir()):[...M],r;try{r=at(__dirname)}catch{r=void 0}let o=Si({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),n=o.filter(s=>s.status==="removed"),i=o.filter(s=>s.status==="left-alone");console.log(n.length?`Removed skill '${j}' registration for:`:i.length?`Left every registration of '${j}' in place:`:`No '${j}' registration found:`);for(let s of o)console.log(` ${s.agent.padEnd(7)} ${La(s)}`);if(i.length){process.exitCode=1;return}n.length&&console.log(`
44
- Restart your agent to drop /authoring-cli from its command list.`)}function Ka(e){let t={};for(let r=0;r<e.length;r++){let o=e[r];if(o.startsWith("--")){let n=o.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[n]=s}}return t}function Ei(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var Qt=[{name:"login",usage:`login [${Pe.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--cookie-name <name>] [--cookie <value>] (opens Chrome to sign in; automatically captures the session on macOS (Chrome) or Linux (Chromium/Chrome, incl. Termux:X11). Always uses a dedicated "authoring-cli" Chrome profile (created automatically on first use, isolated from your everyday profile, and the only profile this command ever reads/writes cookies for \u2014 no override). Environment defaults to ${ue}; any --*-endpoint overrides that environment's value. --cookie is the manual fallback: paste the session cookie's raw Value from a signed-in browser's own DevTools (Application/Storage tab \u2192 Cookies) to skip Chrome automation entirely \u2014 use it when automatic capture times out because Chrome's own cookie-encryption format isn't one this tool's decryption routine recognizes, not just when sign-in itself fails)`,run:(e,t)=>Cr({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],cookieName:e["cookie-name"],cookie:e.cookie})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>xr()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>Ir()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${M.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=>Ti({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${M.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=>Ri({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=>vr({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=>wr({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=>Tr({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:"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 \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>Ar({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> --context <name> (selects the task for the named context \u2014 a context is mandatory, so one session's selection can never move another's; commands in that context then target it when --project/--task are omitted. A session pinned with AUTHORING_CLI_TASK cannot select a different task)",required:["project","task"],run:e=>Rr({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints this session's task and where it comes from \u2014 pin or context; with --project/--task, notes whether they match)",run:e=>$r({project:e.project,task:e.task})},{name:"contexts",usage:"contexts [--remove <name>] (lists the named contexts in this directory and the task each holds, flagging tasks held by more than one; --remove deletes a stale one)",run:e=>Er({remove:e.remove})},{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=>Pr({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (without --limit, pages through and returns every match rather than stopping at a fixed page size \u2014 Snowstorm still can't page an unsorted search past offset+limit 10,000, so a match count above that comes back with `truncated: true` and a message to narrow the query; --limit N caps the search to exactly N results in one request instead. --check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never \"conforms\"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)",run:e=>jr({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--descriptions] [--description-full] [--axioms] [--inferred] [--gci-axioms-count] [--full] [--project <projectKey> --task <taskKey>] (no flags: a lightweight {conceptId, fsn, pt, active, definitionStatus, moduleId, effectiveTime} summary \u2014 no descriptions array, no relationships/axioms, and no network fetch of the full concept at all. --descriptions: active descriptions only (FSN/PT/synonyms), inactive dropped entirely \u2014 the common case. --description-full: every description, active and inactive, with its full acceptabilityMap. --axioms: classAxioms plus the flat relationships[] list filtered to STATED_RELATIONSHIP \u2014 the stated definition, with no inferred content mixed in. --inferred: the flat relationships[] list filtered to INFERRED_RELATIONSHIP only \u2014 what classification produced, no axioms/stated content. --gci alone: gciAxioms only. --gci-axioms-count: just {conceptId, gciAxiomsCount} \u2014 the count of active gciAxioms, for a plain has-it-got-any-GCIs check that doesn't need the axioms' content at all. --full: the entire raw concept (every description, both axiom types, annotations, both stated and inferred relationships \u2014 this used to be the no-flags default). These are mutually exclusive \u2014 pass only one. --attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type takes precedence over the other flags when combined with them)",required:["id"],run:e=>Nr({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,descriptions:"descriptions"in e,descriptionFull:"description-full"in e,axioms:"axioms"in e,inferred:"inferred"in e,gciAxiomsCount:"gci-axioms-count"in e,full:"full"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes. Without --limit/--offset, pages through and returns every referencing concept rather than stopping at Snowstorm's own default page size (1000); pass --limit/--offset yourself to page through the results manually instead)",required:["id"],run:e=>Dr({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first; run classify --wait then transform-axiom yourself if you want that checked/fixed)",required:["id"],run:e=>Or({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>Fr({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues; does not cover class-axiom authoring-form conformance \u2014 classify --wait then transform-axiom yourself for that)',run:e=>Lr({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:`review-concepts [--project <projectKey> --task <taskKey>] (read-only: fetches each concept's full current representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, the "concepts" list from get-concepts-for-review, so an editorial review has everything it needs in one call without a manual loop. Does not classify the branch or run transform-axiom (run classify --wait then transform-axiom yourself first if you want axiom-authoring-form conformance fixed before reviewing), and does not re-run Snowstorm's own convention check (that already happened on each edit's own save) \u2014 run validate-review-concepts yourself if you want that re-checked in batch. Not gated by Task Author since it never writes anything; usable by any reviewer, not just the task's own assignee. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)`,run:e=>Kr({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=>_r({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=>Vr({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=>qr({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)
45
- 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=>Jr({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=>Mr({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=>Br({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=>Ur({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>Gr({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=>Hr({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":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-axiom)`,required:["id","axiom-id","relationships"],run:e=>Wr({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-axiom",usage:`add-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--definition-status PRIMITIVE|FULLY_DEFINED] [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (appends a genuinely additional class axiom alongside the concept's existing one(s) \u2014 to change an existing axiom's content instead, use update-axiom in place, published or not)`,required:["id","relationships"],run:e=>zr({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.task})},{name:"add-gci-axiom",usage:`add-gci-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new GCI axiom; the relationships are the axiom's sufficient-condition side)`,required:["id","relationships"],run:e=>Xr({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":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-gci-axiom)`,required:["id","axiom-id","relationships"],run:e=>Yr({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-property-axiom",usage:'add-property-axiom --property-id <SCTID> --expression "<OWL functional-syntax axiom>" [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds an OWL axiom whose subject is a property/attribute concept, not a class \u2014 e.g. a property-chain composition axiom such as SubObjectPropertyOf(ObjectPropertyChain(:A :B) :A), or a plain property subsumption SubObjectPropertyOf(:A :B). This is NOT reachable via add-axiom/update-axiom \u2014 those edit classAxioms on a concept, which cannot represent a property-chain axiom at all, confirmed live. Writes the raw OWL expression directly as an OWL Axiom reference set member (733073007); unlike add-axiom this call returns no structured validationResults \u2014 syntactically invalid OWL is still rejected as an HTTP 500 with a raw parser error, but a semantically wrong-but-valid expression is accepted as-is. CAUTION: a malformed expression that reaches Snowstorm can leave the whole branch permanently locked with no self-service unlock, confirmed live \u2014 a shallow client-side syntax check (balanced parens, recognized leading keyword) catches the obvious case before sending anything, but is not a real OWL parser)',required:["property-id","expression"],run:e=>Qr({propertyId:e["property-id"],expression:e.expression,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"get-property-axioms",usage:"get-property-axioms --id <SCTID> [--active-only] [--project <projectKey> --task <taskKey>] (lists every raw OWL Axiom reference set member (733073007) addressed at this concept, read directly off the refset \u2014 including property axioms such as a property-chain composition that get-concept --axioms cannot render at all, confirmed live on 127489000 |Has active ingredient|. Works for a class concept too, returning the same raw owlExpression text get-concept --axioms reformats into relationships. Shows inactive members too unless --active-only is passed)",required:["id"],run:e=>Zr({id:e.id,activeOnly:"active-only"in e,project:e.project,task:e.task})},{name:"delete-property-axiom",usage:"delete-property-axiom --id <SCTID> --member-id <memberId> [--project <projectKey> --task <taskKey>] (deletes an OWL Axiom reference set member from the property concept <SCTID> \u2014 memberId comes from get-property-axioms or add-property-axiom's own output, not an axiomId. Only ever removes a never-released member; a released one is refused by Snowstorm itself (HTTP 400, not 409 like delete-axiom/delete-concept \u2014 confirmed live) with no --force escape hatch exposed here. Also refuses if memberId belongs to a different concept than --id, or is not an OWL Axiom member at all)",required:["id","member-id"],run:e=>ei({id:e.id,memberId:e["member-id"],project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>ti({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>oi({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; --association-target is always a REFERS_TO association \u2014 a description has no other association type; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>ni({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
46
- restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save; --association-target there is always a REFERS_TO association)`,required:["id","description-id"],run:e=>ri({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; --association-target is always a REFERS_TO association; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>ii({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"set-description-inactivation-reason",usage:"set-description-inactivation-reason --id <SCTID> --description-id <descriptionId> --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id <SCTID>] [--project <projectKey> --task <taskKey>] (assigns or retargets the reason on a description that is already inactive, without touching its active state \u2014 --target-id is required for reason NOT_SEMANTICALLY_EQUIVALENT (the concept this description actually belongs under, via a REFERS_TO association) and rejected for the other three reasons, which take no target; 409s if the reason currently assigned has already been published \u2014 only an unpublished reason can be retargeted; for a description that is still active, use inactivate-description instead)",required:["id","description-id","reason"],run:e=>si({id:e.id,descriptionId:e["description-id"],reason:e.reason,targetId:e["target-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>ai({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom; 409s if every other active class axiom is itself unpublished \u2014 that combination is the add-a-replacement-then-inactivate anti-pattern, not a legitimate retirement; use update-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>ci({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"transform-axiom",usage:"transform-axiom --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (rewrites a class axiom into the standard authoring form \u2014 Is-a to the proximal primitive parent(s) plus every currently-inferred attribute, per Snowstorm's own authoring-form computation; updates the axiom in place, published or not \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>di({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>li({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>ui({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional; 409s if every other active GCI axiom is itself unpublished \u2014 use update-gci-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>pi({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=>mi({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=>fi({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=>gi({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=>yi({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=>hi({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function Pi(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 $i(){return["Usage: authoring-cli <command> [options]","","Commands:",...Qt.map(e=>` ${Pi(e)}`),"",'Run "login" first to sign in.',"Every session must say which task it works on, so tasks never get mixed up:",' --context <name> (or AUTHORING_CLI_CONTEXT) \u2014 a named selection; "select-task" in one context never moves another'," AUTHORING_CLI_TASK=<TASK-KEY> \u2014 pins the process to one task; a different --task is refused"," --project/--task on a command \u2014 targets that task for that call only","With none of these, no task is implied and task-targeting commands fail."].join(`
47
- `)}async function ji(e=process.argv){let[,,t,...r]=e,o=Ka(r),n=Ei(r);if(!t){console.log($i());return}let i=Qt.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
35
+ </html>`}async function wa(e){let t=Date.now();try{return await Wn({userDataDir:H(),host:e.host,cookieName:e.cookieName,cookieUrl:`https://${e.host}/`,timeoutMs:e.timeoutMs},{validateCookie:e.validateCookie})}catch(r){if(!(r instanceof W))throw r;let o=Math.max(e.timeoutMs-(Date.now()-t),5e3);return Hn({...e,timeoutMs:o},{validateCookie:e.validateCookie})}}function ur(e,t={}){let r=e.cookieName??Mt(e.host),o=t.platform??process.platform,n=t.openChrome??((d,l)=>va(d,l,o)),i=t.resolveProfile??Ue,s=t.captureCookie??wa,a=e.timeoutMs??12e4,c=i();return new Promise((d,l)=>{let u=!1,p=k=>{u||(u=!0,y.close(),k())},y=ar.createServer((k,h)=>{if((k.url||"/").split("?")[0]==="/callback"){h.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),h.end(Sa());return}h.writeHead(404),h.end()});y.listen(0,"127.0.0.1",()=>{let h=`http://localhost:${y.address().port}/callback`,g=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(h)}`;(async()=>{try{Gn(H()),await n(g,c.directoryName);let I=await s({profileDirectory:c.directoryName,host:e.host,cookieName:r,timeoutMs:a,validateCookie:t.validateCookie});p(()=>d({cookie:`${r}=${I}`}))}catch(I){p(()=>l(I))}})()}),y.on("error",k=>p(()=>l(k)))})}var R=S(require("fs")),J=S(require("path")),pr="AUTHORING_CLI_HOME";function Ta(){return J.join(process.cwd(),".authoring-cli")}function Aa(){let e=process.env[pr];return e&&e.trim()!==""?J.resolve(e):null}function ve(){return Aa()??Ta()}function be(e){return J.join(e,"session.json")}function tt(){let e=be(ve());if(!R.existsSync(e))return null;let t=R.readFileSync(e,"utf8");return{...JSON.parse(t),currentTask:null}}function Se(e){let t=ve(),r={...e,currentTask:null,updatedAt:new Date().toISOString()};try{R.mkdirSync(t,{recursive:!0,mode:448}),R.writeFileSync(be(t),JSON.stringify(r,null,2),{mode:384})}catch(o){let n=o?.code;throw n==="EPERM"||n==="EACCES"?new Error(`Couldn't write the session to ${be(t)} (${n}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${pr} to an explicit, writable location.`):o}}function mr(){let e=be(ve());R.existsSync(e)&&R.unlinkSync(e)}function we(){return be(ve())}var ie="AUTHORING_CLI_CONTEXT",K="AUTHORING_CLI_TASK",Ze="AUTHORING_CLI_PROJECT",Ra=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function et(e){let t=process.env[e];return t&&t.trim()!==""?t.trim():null}function fr(e){if(!Ra.test(e))throw new Error(`Invalid context name "${e}": use letters, digits, ".", "_" or "-" (max 64, starting with a letter or digit), e.g. "ANCRJAN22-1069".`);return e}function Y(){let e=et(ie);return e===null?null:fr(e)}function $a(e){let t=/^(.+)-\d+$/.exec(e);return t?t[1]:null}function Te(){let e=et(K);if(e===null){if(et(Ze)!==null)throw new Error(`${Ze} is set without ${K} \u2014 set both, or neither.`);return null}let t=et(Ze)??$a(e);if(!t)throw new Error(`${K}=${e} doesn't look like "<PROJECT>-<n>"; also set ${Ze}.`);return{projectKey:t,taskKey:e,branchPath:""}}function Bt(){return J.join(ve(),"contexts")}function Ut(e){return J.join(Bt(),`${fr(e)}.json`)}function gr(e,t){let r;try{r=JSON.parse(R.readFileSync(e,"utf8"))}catch(o){throw new Error(`Context "${t}" is unreadable (${e}): ${o instanceof Error?o.message:String(o)}. Re-run select-task, or delete the file.`)}return{name:t,currentTask:r.currentTask??null,updatedAt:r.updatedAt??null}}function Ea(e){let t=Ut(e);return R.existsSync(t)?gr(t,e):null}function Vt(){let e=Bt();return R.existsSync(e)?R.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>gr(J.join(e,t),t.slice(0,-5))).sort((t,r)=>t.name.localeCompare(r.name)):[]}function yr(e){let t=Ut(e);return R.existsSync(t)?(R.unlinkSync(t),!0):!1}function qt(){let e=Y(),t=Te();return t?{task:t,source:"pin",context:e}:e?{task:Ea(e)?.currentTask??null,source:"context",context:e}:{task:null,source:"none",context:null}}function Pa(){return qt().task}var ja=`Name this session's context with "--context <name>" (or ${ie}=<name>) \u2014 e.g. one per task \u2014 or pin it with ${K}=<TASK-KEY>; or pass --project/--task on every command.`;function X(e){let t=Te();if(t){if(e&&e.taskKey!==t.taskKey)throw new Error(`This session is pinned to ${t.projectKey}/${t.taskKey} (${K}) and can't switch to ${e.projectKey}/${e.taskKey}. Use a separate session (or unset the pin) for the other task.`);if(!e)throw new Error(`This session is pinned to ${t.projectKey}/${t.taskKey} (${K}); a newly created task can't become its selection. Pass --no-select.`);return}if(!Y())throw new Error(`No context to store a task selection in. ${ja}`)}function hr(e){let t=Te();if(t&&e&&e!==t.taskKey)throw new Error(`--task ${e} conflicts with this session's pin ${t.projectKey}/${t.taskKey} (${K}). Refusing to act on a different task from a pinned session; use a separate session for it.`)}function se(e){X(e);let t=Y();if(!t)return;let r=Bt(),o=Ut(t),n=JSON.stringify({currentTask:e,updatedAt:new Date().toISOString()},null,2),i=`${o}.${process.pid}.tmp`;try{R.mkdirSync(r,{recursive:!0,mode:448}),R.writeFileSync(i,n,{mode:384}),R.renameSync(i,o)}catch(s){throw R.rmSync(i,{force:!0}),s}}function kr(e,t){return Vt().filter(r=>r.name!==t&&r.currentTask?.taskKey===e).map(r=>r.name)}function Cr(e){return{...e,currentTask:Pa()}}async function Na(e){let t=tt();if(!t||t.imsEndpoint!==e)return null;let r=await oe(e,t.cookie).catch(()=>null);return r?{cookie:t.cookie,account:r,currentTask:t.currentTask}:null}async function Da(e,t,r,o){let n=await Ot(o,t,r).catch(()=>null);if(!n)return null;let i=`${r}=${n}`,s=await oe(e,i).catch(()=>null);return s?{cookie:i,account:s}:null}function ot(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 nt(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:o,explicit:n,source:i}of e)console.log(` ${(o+":").padEnd(t+2)}${r} (${n?"from flag":i})`)}async function xr(e){let t=e.environment?to(e.environment):ue;if(!t){console.error(`Unknown environment: ${e.environment}
36
+ Expected one of: ${Ee.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=z[t],o=e.imsEndpoint||r.imsEndpoint,n=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=new URL(o).hostname}catch{console.error(`Invalid --ims-endpoint: ${o}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||Mt(s),d=t===ue&&!e.environment?`${t}, default`:t,l=[{url:o,label:"IMS",explicit:!!e.imsEndpoint},{url:n,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(g=>({...g,source:d}));if(e.cookie){let g=`${c}=${e.cookie}`,I=await oe(o,g).catch(()=>null);if(!I){console.error(`That cookie value was rejected by IMS (${o}) \u2014 either it's stale/expired, or it's not the right cookie. Re-copy the current "${c}" cookie's Value from the signed-in browser's DevTools (Application/Storage tab \u2192 Cookies) and try again.`),process.exitCode=1;return}Se({cookie:g,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:I,currentTask:null}),console.log(`${ot(I)} (from --cookie \u2014 no browser opened.)`),nt(l),console.log(` Session: ${we()}`);return}let u=await Na(o);if(u){Se({cookie:u.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:u.account,currentTask:null}),console.log(`${ot(u.account)} (reused the already-stored session \u2014 no Chrome involved at all.)`),nt(l),console.log(` Session: ${we()}`);return}let p=Ue(),y=await Da(o,s,c,p.directoryName);if(y){Se({cookie:y.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:y.account,currentTask:null}),console.log(`${ot(y.account)} (reused an existing Chrome session in profile "${p.directoryName}" \u2014 no browser opened.)`),nt(l),console.log(` Session: ${we()}`);return}console.log(`Opening Chrome (profile "${p.directoryName}") to sign in to ${o} ...`),console.log(` This is a separate, dedicated Chrome profile for authoring-cli, isolated from your everyday browsing profile \u2014 it opens its own window and (the first time) starts out NOT signed in, even if another Chrome window/profile already is. Sign in inside THAT new window \u2014 check its profile avatar (top-right) reads "${p.directoryName}" \u2014 not whichever Chrome window happened to already be in front.`);let k;try{k=await ur({imsEndpoint:o,host:s,cookieName:c},{validateCookie:g=>oe(o,`${c}=${g}`).then(I=>I!==null)})}catch(g){console.error(g instanceof Error?g.message:String(g)),process.exitCode=1;return}if(!k){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let h=await oe(o,k.cookie).catch(()=>null);Se({cookie:k.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:h,currentTask:null}),console.log(ot(h)),nt(l),console.log(` Session: ${we()}`)}async function Ir(){mr(),console.log("Signed out.")}var it=S(require("fs")),rt=S(require("path"));async function br(){let e=[rt.join(__dirname,"../../HELP.md"),rt.join(__dirname,"../HELP.md"),rt.join(process.cwd(),"HELP.md")];for(let t of e)try{if(it.existsSync(t)){let r=it.readFileSync(t,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function f(){let e;try{e=tt(),e&&(e=Cr(e))}catch(t){console.error(t instanceof Error?t.message:String(t)),process.exit(1)}return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function Ht(e){let t=e.account;return t?.login??t?.username}function m(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,currentUsername:Ht(e),onLog:t=>console.error(t)}}function vr(e){return e.projectKey??e.key??"?"}async function Sr(e){let t=f(),r=m(t),o=await bn(r);if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log("No projects available.");return}let n=Math.max(...o.map(i=>vr(i).length))+1;for(let i of o){let s=i.title??"";console.log(`${vr(i).padEnd(n)}${s?`"${s}"`:""}`)}}function st(e){return e.taskKey??e.key??"?"}function wr(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Oa(e){return e.projectKey||st(e).split("-")[0]||"?"}function Jt(e,t){let r=new Map;for(let o of e){let n=t(o);r.set(n,(r.get(n)??0)+1)}return[...r].sort((o,n)=>n[1]-o[1]||o[0].localeCompare(n[0]))}function Gt(e,t){let r=Math.max(...t.map(([n])=>n.length)),o=Math.max(...t.map(([,n])=>String(n).length));console.log(""),console.log(`${e}:`);for(let[n,i]of t)console.log(` ${n.padEnd(r)} ${String(i).padStart(o)}`)}async function Tr(e){let t=f(),r=m(t),o=e.mine||!e.project,n=o?await Sn(r):await vn(r,e.project);if(o&&e.project){let l=e.project.toLowerCase();n=n.filter(u=>(u.projectKey??"").toLowerCase()===l||st(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();n=n.filter(u=>(u.status??"").toLowerCase()===l)}let i=Jt(n,Oa),s=Jt(n,wr),a=Jt(n,l=>l.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:n.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),byStatus:Object.fromEntries(a)}:n,null,2));return}let c=[o?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(n.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${n.length} task${n.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),i.length>1&&Gt("By project",i),!o&&s.length>1&&Gt("By assignee",s),a.length>1&&Gt("By status",a);return}let d=Math.max(...n.map(l=>st(l).length))+1;for(let l of n){let u=l.summary??l.title??"",p=l.status?` status=${l.status}`:"",y=o?"":` [${wr(l)}]`;console.log(`${st(l).padEnd(d)}${u?`"${u}"`:""}${p}${y}`)}}async function Ar(e){e.noSelect||X();let t=f(),r=m(t),o=Ht(t),n=e.unassigned?void 0:e.assignee||o,i=await wn(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:n});if(!i.task){console.error(i.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let s=i.task,a=s.key??s.taskKey,c=s.branchPath;if(e.json)console.log(JSON.stringify(s,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${s.summary??e.summary}"${s.status?` status=${s.status}`:""}`),c&&console.log(` branch: ${c}`);let d=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await ee(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}se({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function Rr(e){let t=f(),r=m(t);if(!e.task){let i=await Tn(r,e.project);if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${i.length} deleted task${i.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let s of i){let a=s.assignee?.displayName??s.assignee?.username??"unassigned";console.log(` ${s.key} "${s.summary??""}" [${a}]`)}return}e.noSelect||X({projectKey:e.project,taskKey:e.task});let o=await An(r,{projectKey:e.project,taskKey:e.task});if(o.error){console.error(o.error),process.exitCode=1;return}if(o.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${o.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${o.task?.status??"In Progress"})`);let n=o.task?.branchPath;if(n){let i=await ee(r,n);if(!i.ok){console.error(`Task recovered, but its branch could not be prepared: ${i.error}`),process.exitCode=1;return}console.log(i.created?` created branch ${n}`:` branch ${n} still holds its content`)}e.noSelect||!n||(se({projectKey:e.project,taskKey:e.task,branchPath:n}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function $r(e){X({projectKey:e.project,taskKey:e.task});let t=f(),r=m(t),o=await _(r,e.project,e.task);if(!o||!o.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let n=await ee(r,o.branchPath);if(!n.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${n.error}`),process.exitCode=1;return}se({projectKey:e.project,taskKey:e.task,branchPath:o.branchPath});let i=Y();console.log(`\u2713 Current task set to ${e.project}/${e.task} (${o.branchPath})${i?` in context "${i}"`:""}`);let s=kr(e.task,i);s.length&&console.error(` Warning: context(s) ${s.map(a=>`"${a}"`).join(", ")} also hold ${e.task} \u2014 concurrent writes to one branch contend for its lock.`),n.created&&console.log(` created branch ${o.branchPath}`)}async function Er(e){let t=f(),r=qt();if(!r.task){r.source==="context"?console.log(`Context "${r.context}" has no task selected yet. Run "select-task --context ${r.context} --project <projectKey> --task <taskKey>".`):console.log(`No task context. Name this session with "--context <name>" (or ${ie}), pin it with ${K}, or pass --project/--task explicitly to any command.`);return}let{projectKey:o,taskKey:n}=r.task,i=r.task.branchPath||await ut(m(t),o,n)||"(branch not resolved)",s=r.source==="pin"?`pinned via ${K}`:`context "${r.context}"`;console.log(`Current task: ${o}/${n} (${i}) [${s}]`),(e.project||e.task)&&((!e.project||e.project===o)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function Pr(e){if(e.remove!==void 0){if(!e.remove){console.error("--remove needs a context name."),process.exitCode=1;return}console.log(yr(e.remove)?`\u2713 Removed context "${e.remove}".`:`No context named "${e.remove}".`);return}let t=Vt(),r=Y(),o=Te();t.length===0&&console.log("No contexts yet. Create one with: select-task --context <name> --project <projectKey> --task <taskKey>");let n=new Map;for(let i of t)i.currentTask&&n.set(i.currentTask.taskKey,[...n.get(i.currentTask.taskKey)??[],i.name]);for(let i of t){let s=i.name===r?"*":" ",a=i.currentTask,c=a&&(n.get(a.taskKey)?.length??0)>1?" (same task as another context \u2014 branch-lock contention possible)":"";console.log(`${s} ${i.name}: ${a?`${a.projectKey}/${a.taskKey} (${a.branchPath})`:"no task selected"}${i.updatedAt?` [${i.updatedAt}]`:""}${c}`)}o?console.log(`This session is pinned to ${o.projectKey}/${o.taskKey}.`):r&&console.log("(* = this session's context)")}async function jr(e){let t=f(),r=m(t),o=await uo(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300&&n.conceptId){console.log(`Created concept ${n.conceptId}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to create concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Nr(e){let t=f(),r=m(t),o={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},n=e.checkStatedParentsDefinitionStatus?await tn(r,o,t.currentTask):await Ne(r,o,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 Dr(e){let t=f(),r=m(t),o=await je(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,descriptions:e.descriptions,descriptionFull:e.descriptionFull,axioms:e.axioms,inferred:e.inferred,gciAxiomsCount:e.gciAxiomsCount,full:e.full,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get concept (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Or(e){let t=f(),r=m(t),o=await mo(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to find references (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Fr(e){let t=f(),r=m(t),o=await _e(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let s=n.error?n.error:JSON.stringify(n);console.error(`Failed to validate concept (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}let i=n.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}b(i),n.hasErrors&&(process.exitCode=1)}async function Lr(e){let t=f(),r=m(t),o=e.checkStatedParentsDefinitionStatus?await dn(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await q(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to list concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function _r(e){let t=f(),r=m(t),o=await ln(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${o.statusCode}): ${n.error??JSON.stringify(n)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(o.body,null,2)),n.summary&&(n.summary.withIssues>0||n.summary.failed>0)&&(process.exitCode=1);return}let i=n.results??[],s=n.summary;if(i.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of i){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),b(a.validationResults)}if(s){console.log("");let a=[`${s.validated} validated`,`${s.clean} clean`,`${s.withIssues} with issues`];s.skippedDeleted&&a.push(`${s.skippedDeleted} skipped (deleted on this branch)`),s.failed&&a.push(`${s.failed} failed`),console.log(a.join(", ")+".")}s&&(s.withIssues>0||s.failed>0)&&(process.exitCode=1)}async function Kr(e){let t=f(),r=m(t),o=await un(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to fetch concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function Mr(e){let t=f(),r=m(t),o=await Ao(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Br(e){let t=f(),r=m(t),o=await Ro(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Ur(e){let t=f(),r=m(t),o=await zo(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to remove relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Vr(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=f(),o=m(r),n=await Qo(o,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to remove role group (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function qr(e){let t=f(),r=m(t),o=await Po(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to update description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Hr(e){let t=f(),r=m(t),o=await jo(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set case significance (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Jr(e){let t=f(),r=m(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.message}`),process.exitCode=1;return}if(!Array.isArray(s)||s.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await Fo(r,{conceptId:e.id,entries:s,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${s.length} description(s) on concept ${e.id}`),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 o=await Oo(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){let s=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${s.join(", ")})`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set acceptability (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Gr(e){let t=f(),r=m(t),o=await Eo(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to inactivate concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Wr(e){let t=f(),r=m(t),o=await $o(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set definition status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Yr(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=f(),o=m(r),n=await Vo(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Xr(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=f(),o=m(r),n=await qo(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function zr(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=f(),o=m(r),n=await Jo(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Qr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=f(),o=m(r),n=await Ho(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),b(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Zr(e){if(!e.expression||!e.expression.trim()){console.error("--expression must be a non-empty OWL functional-syntax axiom string."),process.exitCode=1;return}let t=f(),r=m(t),o=await rn(r,{propertyId:e.propertyId,owlExpression:e.expression,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added property axiom to ${e.propertyId}${n.memberId?` (memberId ${n.memberId})`:""}: ${e.expression}`),console.log("Note: this write returns no structured validationResults (no ?validate=true equivalent for this endpoint). Syntactically invalid OWL is still rejected (as an HTTP 500 with a raw parser error, not a 400), but a semantically wrong-but-valid expression would only surface downstream, e.g. on the next classification run.");return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to add property axiom (HTTP ${o.statusCode}): ${i}`),o.statusCode===500&&console.error('WARNING: a 500 here means the expression reached Snowstorm and its OWL parser rejected it \u2014 confirmed live, that can leave this task branch permanently locked server-side (not just this failed write). Try a plain read (e.g. get-property-axioms) or another small write next; if that also fails with "already locked", the branch needs an admin to run the unlock action \u2014 a regular author/project-lead account cannot self-service it.'),process.exitCode=1}async function ei(e){let t=f(),r=m(t),o=await sn(r,{conceptId:e.id,activeOnly:e.activeOnly,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get property axioms (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function ti(e){let t=f(),r=m(t),o=await an(r,{conceptId:e.id,memberId:e.memberId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted property axiom ${e.memberId} from ${e.id}${n.owlExpression?`: ${n.owlExpression}`:""}`);return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to delete property axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function oi(e){let t=f(),r=m(t),o=await on(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ni(e){let t=f(),r=m(t),o=await Lo(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ri(e){let t=f(),r=m(t),o=await _o(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ii(e){let t=f(),r=m(t),o=await Ko(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to restore description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function si(e){let t=f(),r=m(t),o=await Bo(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to replace FSN (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ai(e){let t=f(),r=m(t),o=await Mo(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set description inactivation reason (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ci(e){let t=f(),r=m(t),o=await Go(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function di(e){let t=f(),r=m(t),o=await Wo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function li(e){let t=f(),r=m(t),o=await Xo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){if(n.alreadyConformed)console.log(`Concept ${e.id}'s axiom${n.axiomId?` ${n.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(n.replacedAxiomId){let s=Array.isArray(n.addResult?.classAxioms)?n.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=s.length>0?s[s.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${n.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to transform axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function ui(e){let t=f(),r=m(t),o=await Fe(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}if(n.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${n.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${n.axiomId}) \u2014 ${n.message}`)}async function pi(e){let t=f(),r=m(t),o=await Zo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function mi(e){let t=f(),r=m(t),o=await en(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}function ae(e){let t=e.account?.login;return t?Dn(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 fi(e){let t=f(),r=m(t),o=ae(t),n;try{n=await Cn(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.statusCode<300){i.finalStatus!==void 0?(console.log(`Classification ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),i.details&&console.log(JSON.stringify(i.details,null,2)),i.save&&(i.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${i.save.error?`: ${i.save.error}`:""}${i.save.status?` (status: ${i.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${i.jobId} (${i.status})`),i.timedOut&&(process.exitCode=1);return}let s=i.details!==void 0?` \u2014 details: ${JSON.stringify(i.details)}`:"";console.error(`Failed to start classification (HTTP ${n.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function gi(e){let t=f(),r=m(t),o=await kn(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check classification status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function yi(e){let t=f(),r=m(t),o=ae(t),n;try{n=await In(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.statusCode<300){i.finalStatus!==void 0?console.log(`Validation ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),i.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${n.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function hi(e){let t=f(),r=m(t),o=await xn(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check validation status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function ki(e){let t=f(),r=m(t),o=ae(t);try{let n=await On(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=n.body;if(n.statusCode<200||n.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{o?.stop()}}var zt=S(require("os")),de=S(require("path"));var T=S(require("fs")),Wt=S(require("os")),v=S(require("path")),j="authoring-cli",Yt=".installed-by-authoring-cli.json",xi=new Set([".DS_Store"]),M=["claude","codex","agents","dsh"];function Xt(e,t){let r=process.env.CODEX_HOME;return t!==void 0?v.resolve(t):r!==void 0&&r.trim().length>0?v.resolve(r):v.join(e,".codex")}function Fa(e,t){return t??process.env.DSH_AGENTS_HOME??v.join(e,".agents")}function Ii(e,t){let r=process.env.DSH_HOME,o=t??(r!==void 0&&r.trim().length>0?r:void 0);return o===void 0?v.join(e,".dsh"):o==="~"?e:o.startsWith("~/")||o.startsWith("~\\")?v.join(e,o.slice(2)):v.resolve(o)}function ct(e){let t=[v.resolve(e,"..","skills",j),v.resolve(e,"..","..","skills",j)];for(let r of t)if(T.existsSync(v.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${j}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function bi(e){try{let t=JSON.parse(T.readFileSync(v.resolve(e,"..","..","package.json"),"utf8"));return typeof t.version=="string"?t.version:void 0}catch{return}}function La(e,t={}){let r=[];return T.existsSync(v.join(e,".claude"))&&r.push("claude"),T.existsSync(Xt(e,t.codexHomeDir))&&r.push("codex"),T.existsSync(Ii(e,t.dshHomeDir))&&r.push("dsh"),r}function Ae(e,t,r={}){if(e==="all")return[...M];if(e){let n=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),i=n.filter(s=>!M.includes(s));if(i.length)throw new Error(`Unknown --agent value(s): ${i.join(", ")}. Supported: ${M.join(", ")}, all.`);return n}let o=La(t,r);return o.length?o:["claude"]}var _a="# authoring-cli \u2014 SNOMED CT authoring guidance";function at(e){try{return v.resolve(v.dirname(e),T.readlinkSync(e))}catch{return null}}function ce(e){try{return T.lstatSync(e)}catch{return null}}function vi(e){let t=at(e);return t?T.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:ce(e)?.isDirectory()?"an existing directory":"an existing file"}function Si(e){let t=at(e);return t!==null&&v.basename(t)===j&&v.basename(v.dirname(t))==="skills"}function Ka(e){if(!ce(e)?.isFile())return!1;try{return T.readFileSync(e,"utf8").startsWith(_a)}catch{return!1}}function wi(e){let t=ce(e);return t!==null&&t.isDirectory()&&!t.isSymbolicLink()&&T.existsSync(v.join(e,Yt))}function Ci(e){return T.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()&&t.name!==Yt&&!xi.has(t.name)).map(t=>v.relative(e,v.join(t.parentPath,t.name))).sort()}function Ti(e,t){if(!t||!T.existsSync(t)||!ce(e)?.isDirectory())return!1;try{let r=Ci(t);return r.join(`
37
+ `)!==Ci(e).join(`
38
+ `)?!1:r.every(o=>T.readFileSync(v.join(e,o)).equals(T.readFileSync(v.join(t,o))))}catch{return!1}}function Ma(e,t){T.mkdirSync(v.dirname(t),{recursive:!0}),T.cpSync(e,t,{recursive:!0,filter:o=>!xi.has(v.basename(o))});let r={installer:"authoring-cli",version:bi(e)??null,source:e,installedAt:new Date().toISOString(),note:"This directory is a copy managed by `authoring-cli install-skill`; re-run it to refresh, or `authoring-cli uninstall-skill` to remove."};T.writeFileSync(v.join(t,Yt),JSON.stringify(r,null,2)+`
39
+ `,"utf8")}function Ai(e,t,r,o){switch(e){case"claude":return v.join(t.project?o:r,".claude","skills");case"codex":return v.join(Xt(r,t.codexHomeDir),"skills");case"agents":return v.join(Fa(r,t.agentsHomeDir),"skills");case"dsh":return v.join(Ii(r,t.dshHomeDir),"skills")}}function Ba(e,t){return v.join(Xt(t,e.codexHomeDir),"prompts",`${j}.md`)}function Ri(e,t){let r=Ba(e,t);return Ka(r)?(T.rmSync(r,{force:!0}),`removed legacy pointer prompt ${r}`):null}function Ua(e,t,r){let o=v.join(t,j),n=r.shippedSkillDir,i=bi(n),s=`copied from ${n}${i?` (v${i})`:""}`,a="installed";if(ce(o)){let c=Ti(o,n);if(wi(o)){if(c)return{agent:e,path:o,status:"already-current",kind:"copy",detail:s};a="updated"}else if(Si(o)||c)a="replaced";else if(r.force)a="replaced";else return{agent:e,path:o,status:"blocked",kind:"copy",detail:vi(o)};T.rmSync(o,{recursive:!0,force:!0})}return Ma(n,o),{agent:e,path:o,status:a,kind:"copy",detail:s}}function $i(e){let t=e.homeDir??Wt.homedir(),r=e.cwd??process.cwd();return(e.agents??Ae(void 0,t,e)).map(n=>{let i=Ua(n,Ai(n,e,t,r),e);if(n==="codex"&&i.status!=="blocked"){let s=Ri(e,t);s&&(i.detail=i.detail?`${i.detail}; ${s}`:s)}return i})}function Ei(e){let t=e.homeDir??Wt.homedir(),r=e.cwd??process.cwd();return e.agents.map(o=>{let n=v.join(Ai(o,e,t,r),j),i=o==="codex"?Ri(e,t):null;if(!ce(n))return{agent:o,path:n,status:"not-registered",...i?{detail:i}:{}};if(!(wi(n)||Si(n)||Ti(n,e.shippedSkillDir))&&!e.force)return{agent:o,path:n,status:"left-alone",detail:`${vi(n)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let a=at(n)?`symlink -> ${at(n)}`:"installed copy";return T.rmSync(n,{recursive:!0,force:!0}),{agent:o,path:n,status:"removed",detail:i?`${a}; ${i}`:a}})}function Va(e){let t=zt.homedir();return e===t||e.startsWith(t+de.sep)?de.join("~",de.relative(t,e)):e}function qa(e){let t=Va(e.path);switch(e.status){case"installed":case"updated":case"replaced":return`${t} (${e.status} \u2014 ${e.detail})`;case"already-current":return`${t} (already up to date \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 Pi(e){let t=ct(__dirname),r=Ae(e.agent,zt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; the other targets are always user-level.");let o=$i({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),n=o.filter(a=>a.status==="installed"||a.status==="updated"||a.status==="replaced"),i=o.filter(a=>a.status==="blocked");console.log(n.length?`Installed skill '${j}' for:`:i.length?`Could not install skill '${j}':`:`Skill '${j}' is already registered:`);for(let a of o)console.log(` ${a.agent.padEnd(6)} ${qa(a)}`);if(e.project&&r.includes("claude")&&console.log(`
40
+ Project-scoped install: .claude/skills now holds a copy of the skill \u2014 commit it if you want teammates
41
+ to get the guidance, and re-run install-skill after upgrading authoring-cli to refresh it.`),i.length){process.exitCode=1;return}n.length&&(console.log(`
42
+ Restart your agent, then use /${j}.`),console.log('Each target is a copy: re-run "authoring-cli install-skill" after "npm update -g authoring-cli" to refresh it.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let s=M.filter(a=>!r.includes(a));s.length&&!e.agent&&console.log(`
43
+ Skipped ${s.join(", ")} (no config directory found; "agents" is never auto-selected). Pass --agent ${s.join(",")} to register anyway.`)}var Qt=S(require("os")),le=S(require("path"));function Ha(e){let t=Qt.homedir();return e===t||e.startsWith(t+le.sep)?le.join("~",le.relative(t,e)):e}function Ja(e){let t=Ha(e.path);switch(e.status){case"removed":return`${t} (removed${e.detail?` \u2014 ${e.detail}`:""})`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function ji(e){let t=e.agent?Ae(e.agent,Qt.homedir()):[...M],r;try{r=ct(__dirname)}catch{r=void 0}let o=Ei({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),n=o.filter(s=>s.status==="removed"),i=o.filter(s=>s.status==="left-alone");console.log(n.length?`Removed skill '${j}' registration for:`:i.length?`Left every registration of '${j}' in place:`:`No '${j}' registration found:`);for(let s of o)console.log(` ${s.agent.padEnd(6)} ${Ja(s)}`);if(i.length){process.exitCode=1;return}n.length&&console.log(`
44
+ Restart your agent to drop /authoring-cli from its command list.`)}function Ga(e){let t={};for(let r=0;r<e.length;r++){let o=e[r];if(o.startsWith("--")){let n=o.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[n]=s}}return t}function Di(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var Zt=[{name:"login",usage:`login [${Ee.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--cookie-name <name>] [--cookie <value>] (opens Chrome to sign in; automatically captures the session on macOS (Chrome) or Linux (Chromium/Chrome, incl. Termux:X11). Always uses a dedicated "authoring-cli" Chrome profile (created automatically on first use, isolated from your everyday profile, and the only profile this command ever reads/writes cookies for \u2014 no override). Environment defaults to ${ue}; any --*-endpoint overrides that environment's value. --cookie is the manual fallback: paste the session cookie's raw Value from a signed-in browser's own DevTools (Application/Storage tab \u2192 Cookies) to skip Chrome automation entirely \u2014 use it when automatic capture times out because Chrome's own cookie-encryption format isn't one this tool's decryption routine recognizes, not just when sign-in itself fails)`,run:(e,t)=>xr({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],cookieName:e["cookie-name"],cookie:e.cookie})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>Ir()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>br()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${M.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=>Pi({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${M.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=>ji({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=>Sr({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=>Tr({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 into the active --context \u2014 pass --no-select if there is no context or the session is pinned; assigned to you unless overridden)',required:["project","summary"],run:e=>Ar({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:"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 into the active --context unless --no-select \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>Rr({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> --context <name> (selects the task for the named context \u2014 a context is mandatory, so one session's selection can never move another's; commands in that context then target it when --project/--task are omitted. A session pinned with AUTHORING_CLI_TASK cannot select a different task)",required:["project","task"],run:e=>$r({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints this session's task and where it comes from \u2014 pin or context; with --project/--task, notes whether they match)",run:e=>Er({project:e.project,task:e.task})},{name:"contexts",usage:"contexts [--remove <name>] (lists the named contexts in this directory and the task each holds, flagging tasks held by more than one; --remove deletes a stale one)",run:e=>Pr({remove:e.remove})},{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=>jr({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (without --limit, pages through and returns every match rather than stopping at a fixed page size \u2014 Snowstorm still can't page an unsorted search past offset+limit 10,000, so a match count above that comes back with `truncated: true` and a message to narrow the query; --limit N caps the search to exactly N results in one request instead. --check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never \"conforms\"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)",run:e=>Nr({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--descriptions] [--description-full] [--axioms] [--inferred] [--gci-axioms-count] [--full] [--project <projectKey> --task <taskKey>] (no flags: a lightweight {conceptId, fsn, pt, active, definitionStatus, moduleId, effectiveTime} summary \u2014 no descriptions array, no relationships/axioms, and no network fetch of the full concept at all. --descriptions: active descriptions only (FSN/PT/synonyms), inactive dropped entirely \u2014 the common case. --description-full: every description, active and inactive, with its full acceptabilityMap. --axioms: classAxioms plus the flat relationships[] list filtered to STATED_RELATIONSHIP \u2014 the stated definition, with no inferred content mixed in. --inferred: the flat relationships[] list filtered to INFERRED_RELATIONSHIP only \u2014 what classification produced, no axioms/stated content. --gci alone: gciAxioms only. --gci-axioms-count: just {conceptId, gciAxiomsCount} \u2014 the count of active gciAxioms, for a plain has-it-got-any-GCIs check that doesn't need the axioms' content at all. --full: the entire raw concept (every description, both axiom types, annotations, both stated and inferred relationships \u2014 this used to be the no-flags default). These are mutually exclusive \u2014 pass only one. --attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type takes precedence over the other flags when combined with them)",required:["id"],run:e=>Dr({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,descriptions:"descriptions"in e,descriptionFull:"description-full"in e,axioms:"axioms"in e,inferred:"inferred"in e,gciAxiomsCount:"gci-axioms-count"in e,full:"full"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes. Without --limit/--offset, pages through and returns every referencing concept rather than stopping at Snowstorm's own default page size (1000); pass --limit/--offset yourself to page through the results manually instead)",required:["id"],run:e=>Or({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first; run classify --wait then transform-axiom yourself if you want that checked/fixed)",required:["id"],run:e=>Fr({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>Lr({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues; does not cover class-axiom authoring-form conformance \u2014 classify --wait then transform-axiom yourself for that)',run:e=>_r({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:`review-concepts [--project <projectKey> --task <taskKey>] (read-only: fetches each concept's full current representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, the "concepts" list from get-concepts-for-review, so an editorial review has everything it needs in one call without a manual loop. Does not classify the branch or run transform-axiom (run classify --wait then transform-axiom yourself first if you want axiom-authoring-form conformance fixed before reviewing), and does not re-run Snowstorm's own convention check (that already happened on each edit's own save) \u2014 run validate-review-concepts yourself if you want that re-checked in batch. Not gated by Task Author since it never writes anything; usable by any reviewer, not just the task's own assignee. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)`,run:e=>Kr({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=>Mr({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=>qr({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=>Hr({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)
45
+ 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=>Jr({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=>Br({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=>Ur({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=>Vr({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>Gr({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=>Wr({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":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-axiom)`,required:["id","axiom-id","relationships"],run:e=>Yr({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-axiom",usage:`add-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--definition-status PRIMITIVE|FULLY_DEFINED] [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (appends a genuinely additional class axiom alongside the concept's existing one(s) \u2014 to change an existing axiom's content instead, use update-axiom in place, published or not)`,required:["id","relationships"],run:e=>Qr({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.task})},{name:"add-gci-axiom",usage:`add-gci-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new GCI axiom; the relationships are the axiom's sufficient-condition side)`,required:["id","relationships"],run:e=>zr({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":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-gci-axiom)`,required:["id","axiom-id","relationships"],run:e=>Xr({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-property-axiom",usage:'add-property-axiom --property-id <SCTID> --expression "<OWL functional-syntax axiom>" [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds an OWL axiom whose subject is a property/attribute concept, not a class \u2014 e.g. a property-chain composition axiom such as SubObjectPropertyOf(ObjectPropertyChain(:A :B) :A), or a plain property subsumption SubObjectPropertyOf(:A :B). This is NOT reachable via add-axiom/update-axiom \u2014 those edit classAxioms on a concept, which cannot represent a property-chain axiom at all, confirmed live. Writes the raw OWL expression directly as an OWL Axiom reference set member (733073007); unlike add-axiom this call returns no structured validationResults \u2014 syntactically invalid OWL is still rejected as an HTTP 500 with a raw parser error, but a semantically wrong-but-valid expression is accepted as-is. CAUTION: a malformed expression that reaches Snowstorm can leave the whole branch permanently locked with no self-service unlock, confirmed live \u2014 a shallow client-side syntax check (balanced parens, recognized leading keyword) catches the obvious case before sending anything, but is not a real OWL parser)',required:["property-id","expression"],run:e=>Zr({propertyId:e["property-id"],expression:e.expression,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"get-property-axioms",usage:"get-property-axioms --id <SCTID> [--active-only] [--project <projectKey> --task <taskKey>] (lists every raw OWL Axiom reference set member (733073007) addressed at this concept, read directly off the refset \u2014 including property axioms such as a property-chain composition that get-concept --axioms cannot render at all, confirmed live on 127489000 |Has active ingredient|. Works for a class concept too, returning the same raw owlExpression text get-concept --axioms reformats into relationships. Shows inactive members too unless --active-only is passed)",required:["id"],run:e=>ei({id:e.id,activeOnly:"active-only"in e,project:e.project,task:e.task})},{name:"delete-property-axiom",usage:"delete-property-axiom --id <SCTID> --member-id <memberId> [--project <projectKey> --task <taskKey>] (deletes an OWL Axiom reference set member from the property concept <SCTID> \u2014 memberId comes from get-property-axioms or add-property-axiom's own output, not an axiomId. Only ever removes a never-released member; a released one is refused by Snowstorm itself (HTTP 400, not 409 like delete-axiom/delete-concept \u2014 confirmed live) with no --force escape hatch exposed here. Also refuses if memberId belongs to a different concept than --id, or is not an OWL Axiom member at all)",required:["id","member-id"],run:e=>ti({id:e.id,memberId:e["member-id"],project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>oi({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>ni({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; --association-target is always a REFERS_TO association \u2014 a description has no other association type; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>ri({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
46
+ restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save; --association-target there is always a REFERS_TO association)`,required:["id","description-id"],run:e=>ii({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; --association-target is always a REFERS_TO association; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>si({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"set-description-inactivation-reason",usage:"set-description-inactivation-reason --id <SCTID> --description-id <descriptionId> --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id <SCTID>] [--project <projectKey> --task <taskKey>] (assigns or retargets the reason on a description that is already inactive, without touching its active state \u2014 --target-id is required for reason NOT_SEMANTICALLY_EQUIVALENT (the concept this description actually belongs under, via a REFERS_TO association) and rejected for the other three reasons, which take no target; 409s if the reason currently assigned has already been published \u2014 only an unpublished reason can be retargeted; for a description that is still active, use inactivate-description instead)",required:["id","description-id","reason"],run:e=>ai({id:e.id,descriptionId:e["description-id"],reason:e.reason,targetId:e["target-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>ci({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom; 409s if every other active class axiom is itself unpublished \u2014 that combination is the add-a-replacement-then-inactivate anti-pattern, not a legitimate retirement; use update-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>di({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"transform-axiom",usage:"transform-axiom --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (rewrites a class axiom into the standard authoring form \u2014 Is-a to the proximal primitive parent(s) plus every currently-inferred attribute, per Snowstorm's own authoring-form computation; updates the axiom in place, published or not \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>li({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>ui({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>pi({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional; 409s if every other active GCI axiom is itself unpublished \u2014 use update-gci-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>mi({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=>fi({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=>gi({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=>yi({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=>hi({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=>ki({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function Oi(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 Ni(){return["Usage: authoring-cli <command> [options]","","Commands:",...Zt.map(e=>` ${Oi(e)}`),"",'Run "login" first to sign in.',"Every session must say which task it works on, so tasks never get mixed up:",' --context <name> (or AUTHORING_CLI_CONTEXT) \u2014 a named selection; "select-task" in one context never moves another'," AUTHORING_CLI_TASK=<TASK-KEY> \u2014 pins the process to one task; a different --task is refused"," --project/--task on a command \u2014 targets that task for that call only","With none of these, no task is implied and task-targeting commands fail."].join(`
47
+ `)}async function Fi(e=process.argv){let[,,t,...r]=e,o=Ga(r),n=Di(r);if(!t){console.log(Ni());return}let i=Zt.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
48
48
 
49
- ${$i()}`),process.exitCode=1;return}if("context"in o){if(!o.context){console.error("--context needs a name, e.g. --context ANCRJAN22-1069."),process.exitCode=1;return}process.env[se]=o.context}if(i.name!=="recover-task")try{yr(o.task)}catch(a){console.error(a instanceof Error?a.message:String(a)),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!o[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
49
+ ${Ni()}`),process.exitCode=1;return}if("context"in o){if(!o.context){console.error("--context needs a name, e.g. --context ANCRJAN22-1069."),process.exitCode=1;return}process.env[ie]=o.context}if(i.name!=="recover-task")try{hr(o.task)}catch(a){console.error(a instanceof Error?a.message:String(a)),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!o[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
50
50
 
51
- Usage: ${Pi(i)}`),process.exitCode=1;return}await i.run(o,n)}require.main===module&&ji().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
51
+ Usage: ${Oi(i)}`),process.exitCode=1;return}await i.run(o,n)}require.main===module&&Fi().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "authoring-cli",
3
- "version": "0.1.33",
3
+ "version": "0.1.35",
4
4
  "description": "CLI for SNOMED CT authoring against authoring-services",
5
5
  "license": "Apache-2.0",
6
6
  "bin": {
@@ -49,7 +49,7 @@ in the same directory. Selection therefore lives only in one of these:
49
49
  given a different `--task` is refused, as is `select-task` on another task. Use it for batches.
50
50
 
51
51
  With none of these, task-targeting commands fail and `select-task` refuses, rather than guessing —
52
- an old selection left in `session.json` is ignored. In a batch script, pin the task (or pass
52
+ there is **no default task** — an old selection left in `session.json` is discarded, never used. In a batch script, pin the task (or pass
53
53
  `--project`/`--task` on every call) and don't rely on `select-task`/`current-task` between calls.
54
54
 
55
55
  `authoring-cli current-task` prints the task and whether it came from a pin or a context. Run it to
@@ -137,7 +137,8 @@ authoring-cli recover-task --project <projectKey> [--task <taskKey>]
137
137
  ```
138
138
 
139
139
  Puts a deleted task (however it was deleted) back into In Progress, with its branch content
140
- intact, and selects it. Its status before deletion isn't recorded anywhere reachable, so recovery
140
+ intact, and selects it into the active context (so pass `--context <name>`, or `--no-select`; a
141
+ pinned session needs `--no-select`). Its status before deletion isn't recorded anywhere reachable, so recovery
141
142
  always lands on In Progress regardless of where the task was when it was deleted. Deletion never
142
143
  touches the branch — everything that was on it survives untouched, which is what makes recovery
143
144
  possible at all — except for a task that's already been promoted or completed: its content is
@@ -197,7 +198,7 @@ One line per task, carrying **at least the task key and the title**:
197
198
  ANCRJAN22-959 "Laparoscopic procedure model" status=In Progress
198
199
  ```
199
200
 
200
- The key is what `select-task --project <key> --task <key>` and every `--task` flag take, and the
201
+ The key is what `select-task --context <name> --project <key> --task <key>` and every `--task` flag take, and the
201
202
  title is the only thing saying what the task is *for*; drop either and the user has to ask again.
202
203
  The command already prints exactly `<taskKey> "<title>" status=<status>` (plus `[assignee]` when
203
204
  the scope can contain other people's tasks), so relaying those lines verbatim is both correct and
@@ -119,6 +119,14 @@ delegate the batch itself to a subagent — see `SKILL.md`'s "Concurrency: one m
119
119
  task branch, at a time" for why this holds regardless of which command you're batching. The rest
120
120
  of this section is the concrete driving mechanics for a large multi-session batch specifically.
121
121
 
122
+ - **Pin the task for the whole batch.** `export AUTHORING_CLI_TASK=<TASK-KEY>` before the loop (or
123
+ pass `--project`/`--task` on every call). A pinned process can't be retargeted by anything else
124
+ working in the same directory, and a command given a different `--task` is refused — the failure
125
+ this prevents is real: a second session's `select-task` silently moved a half-finished batch's
126
+ edits onto another task's branch, and nothing in the output said so. Don't rely on
127
+ `select-task` or `current-task` between calls, and keep a mutating command's stderr (don't send it
128
+ to `/dev/null`): the edit commands log `<command> <project>/<task>: OK` there, which is the evidence
129
+ of where each call landed.
122
130
  - **Never run mutating calls in parallel against the same task branch.** Even a single sequential
123
131
  caller can surface "branch locked, retrying" from the server's own internal locking — true
124
132
  concurrent callers (multiple background loops, or an `xargs -P`-style fan-out) compound this and