comet-dsh-plugin 0.0.0-stage → 0.5.4

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.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +176 -0
  3. package/README.md +152 -2
  4. package/client.js +349 -0
  5. package/cordis.patch.yml +4 -0
  6. package/icon.png +0 -0
  7. package/index.js +183 -0
  8. package/locale/en.json +7 -0
  9. package/locale/zh.json +7 -0
  10. package/package.json +58 -4
  11. package/rules/comet-workflow-guard.md +65 -0
  12. package/rules/migration-assets.json +218 -0
  13. package/server/comet-plugin-setup.mjs +192 -0
  14. package/skills/comet/SKILL.md +37 -0
  15. package/skills/comet/agents/openai.yaml +3 -0
  16. package/skills/comet/reference/change-walkthrough.md +77 -0
  17. package/skills/comet/reference/edit-review.md +26 -0
  18. package/skills/comet/reference/host-check.md +11 -0
  19. package/skills/comet/reference/platform-execution.md +34 -0
  20. package/skills/comet/reference/task-learning.md +39 -0
  21. package/skills/comet/runtime/classic/checks.yaml +6 -0
  22. package/skills/comet/runtime/classic/guardrails.yaml +13 -0
  23. package/skills/comet/runtime/classic/skill.yaml +122 -0
  24. package/skills/comet/scripts/comet-archive.mjs +310 -0
  25. package/skills/comet/scripts/comet-check.mjs +179 -0
  26. package/skills/comet/scripts/comet-entry-runtime.mjs +151 -0
  27. package/skills/comet/scripts/comet-env.mjs +15 -0
  28. package/skills/comet/scripts/comet-guard.mjs +335 -0
  29. package/skills/comet/scripts/comet-handoff.mjs +289 -0
  30. package/skills/comet/scripts/comet-hook-guard.mjs +295 -0
  31. package/skills/comet/scripts/comet-hook-router-guard.mjs +629 -0
  32. package/skills/comet/scripts/comet-hook-router.mjs +17 -0
  33. package/skills/comet/scripts/comet-intent.mjs +181 -0
  34. package/skills/comet/scripts/comet-plugin-hook.mjs +213 -0
  35. package/skills/comet/scripts/comet-resume-probe.mjs +205 -0
  36. package/skills/comet/scripts/comet-runtime.mjs +572 -0
  37. package/skills/comet/scripts/comet-state.mjs +381 -0
  38. package/skills/comet/scripts/comet-yaml-validate.mjs +182 -0
  39. package/skills/comet-any/SKILL.md +47 -0
  40. package/skills/comet-any/agents/openai.yaml +5 -0
  41. package/skills/comet-any/reference/sdk-creation.md +100 -0
  42. package/skills/comet-archive/SKILL.md +28 -0
  43. package/skills/comet-archive/agents/openai.yaml +5 -0
  44. package/skills/comet-archive/reference/compat.md +188 -0
  45. package/skills/comet-build/SKILL.md +35 -0
  46. package/skills/comet-build/agents/openai.yaml +5 -0
  47. package/skills/comet-build/reference/compat.md +191 -0
  48. package/skills/comet-classic/SKILL.md +98 -0
  49. package/skills/comet-classic/agents/openai.yaml +3 -0
  50. package/skills/comet-classic/reference/auto-transition.md +34 -0
  51. package/skills/comet-classic/reference/classic-layout.md +36 -0
  52. package/skills/comet-classic/reference/comet-yaml-fields.md +82 -0
  53. package/skills/comet-classic/reference/context-recovery.md +128 -0
  54. package/skills/comet-classic/reference/debug-gate.md +30 -0
  55. package/skills/comet-classic/reference/decision-point.md +109 -0
  56. package/skills/comet-classic/reference/dirty-worktree.md +59 -0
  57. package/skills/comet-classic/reference/file-structure.md +32 -0
  58. package/skills/comet-classic/reference/intent-frame.md +132 -0
  59. package/skills/comet-classic/reference/scripts.md +144 -0
  60. package/skills/comet-classic/reference/sdk-methods.md +136 -0
  61. package/skills/comet-classic/reference/subagent-dispatch.md +75 -0
  62. package/skills/comet-classic/reference/workspace.md +23 -0
  63. package/skills/comet-design/SKILL.md +25 -0
  64. package/skills/comet-design/agents/openai.yaml +5 -0
  65. package/skills/comet-design/reference/compat.md +191 -0
  66. package/skills/comet-hotfix/SKILL.md +46 -0
  67. package/skills/comet-hotfix/agents/openai.yaml +5 -0
  68. package/skills/comet-hotfix/reference/compat.md +240 -0
  69. package/skills/comet-memory/SKILL.md +68 -0
  70. package/skills/comet-memory/agents/openai.yaml +5 -0
  71. package/skills/comet-native/SKILL.md +139 -0
  72. package/skills/comet-native/agents/openai.yaml +3 -0
  73. package/skills/comet-native/reference/artifacts.md +118 -0
  74. package/skills/comet-native/reference/clarification.md +120 -0
  75. package/skills/comet-native/reference/commands.md +321 -0
  76. package/skills/comet-native/reference/edit-review.md +26 -0
  77. package/skills/comet-native/reference/recovery.md +64 -0
  78. package/skills/comet-native/reference/workspace.md +70 -0
  79. package/skills/comet-native/scripts/comet-native-archive.mjs +475 -0
  80. package/skills/comet-native/scripts/comet-native-cancel.mjs +461 -0
  81. package/skills/comet-native/scripts/comet-native-doctor.mjs +475 -0
  82. package/skills/comet-native/scripts/comet-native-hook-guard.mjs +470 -0
  83. package/skills/comet-native/scripts/comet-native-init.mjs +465 -0
  84. package/skills/comet-native/scripts/comet-native-new.mjs +478 -0
  85. package/skills/comet-native/scripts/comet-native-next.mjs +470 -0
  86. package/skills/comet-native/scripts/comet-native-root.mjs +472 -0
  87. package/skills/comet-native/scripts/comet-native-runtime.mjs +525 -0
  88. package/skills/comet-native/scripts/comet-native-select.mjs +468 -0
  89. package/skills/comet-native/scripts/comet-native-show.mjs +462 -0
  90. package/skills/comet-native/scripts/comet-native-spec.mjs +468 -0
  91. package/skills/comet-native/scripts/comet-native-status.mjs +467 -0
  92. package/skills/comet-native/scripts/comet-native-transfer.mjs +466 -0
  93. package/skills/comet-open/SKILL.md +265 -0
  94. package/skills/comet-open/agents/openai.yaml +5 -0
  95. package/skills/comet-open/reference/batch-changes.md +51 -0
  96. package/skills/comet-review/SKILL.md +121 -0
  97. package/skills/comet-review/agents/openai.yaml +5 -0
  98. package/skills/comet-tweak/SKILL.md +49 -0
  99. package/skills/comet-tweak/agents/openai.yaml +5 -0
  100. package/skills/comet-tweak/reference/compat.md +232 -0
  101. package/skills/comet-verify/SKILL.md +30 -0
  102. package/skills/comet-verify/agents/openai.yaml +5 -0
  103. package/skills/comet-verify/reference/compat.md +202 -0
@@ -0,0 +1,475 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __cometCreateRequire } from 'module';
3
+ const require = __cometCreateRequire(import.meta.url);
4
+ var kB=Object.create;var xg=Object.defineProperty;var bB=Object.getOwnPropertyDescriptor;var AB=Object.getOwnPropertyNames;var RB=Object.getPrototypeOf,NB=Object.prototype.hasOwnProperty;var $d=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var D=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Dd=(e,t)=>{for(var r in t)xg(e,r,{get:t[r],enumerable:!0})},SB=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of AB(t))!NB.call(e,i)&&i!==r&&xg(e,i,{get:()=>t[i],enumerable:!(n=bB(t,i))||n.enumerable});return e};var tr=(e,t,r)=>(r=e!=null?kB(RB(e)):{},SB(t||!e||!e.__esModule?xg(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as EN}from"node:async_hooks";import{performance as SN}from"node:perf_hooks";function IB(e=0){EB+=1,CB+=e;for(let t of _B.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}function ds(e){let t=SN.now();try{return e()}finally{IB(SN.now()-t)}}var EB,CB,_B,o6,Bd=x(()=>{"use strict";EB=0,CB=0,_B=new EN,o6=new EN});var CN=x(()=>{"use strict"});import{existsSync as xB,readFileSync as l6}from"node:fs";import Fc from"node:path";function _N(e,t){let r=t.toLowerCase();return Object.entries(e).find(([n,i])=>n.toLowerCase()===r&&i!==void 0)?.[1]}function OB(e){let t=(_N(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function TB(e,t,r){let i=Fc.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(_N(t,"PATH")??"").split(Fc.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),a=Fc.win32.extname(e)?[e]:OB(t).map(s=>`${e}${s}`);return i.flatMap(s=>a.map(c=>s?Fc.join(s,c):Fc.resolve(r,c)))}function Pg(e,t,r){return TB(e,t,r).find(n=>xB(n))??e}function IN(e){if(e.some(t=>PB.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var PB,d6,Og=x(()=>{"use strict";PB=/[&|<>()^%"!\r\n]/u,d6=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{spawn as v6,execFileSync as jB}from"node:child_process";import Tg from"node:path";function BB(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function fs(e,t,r={}){let n=r.timeoutMs??$B,i=r.maxBufferBytes??DB;if(!Number.isSafeInteger(n)||n<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(i)||i<1)throw new Error("External command max buffer must be a positive integer");let o=Tg.resolve(r.cwd??process.cwd()),a=r.env??process.env,s=process.platform==="win32"?Pg(e,a,o):e,c=Tg.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&IN(t);try{let u=()=>jB(s,[...t],{cwd:o,env:a,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:n,killSignal:"SIGKILL",maxBuffer:i,windowsHide:!0,shell:process.platform==="win32"&&l});return/^(?:git|git\.exe)$/iu.test(Tg.win32.basename(e))?ds(u):u()}catch(u){let f=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Hc(e,t,f,{cause:u,timedOut:BB(u)})}}var $B,DB,Hc,Qc=x(()=>{"use strict";CN();Bd();Og();$B=6e4,DB=8*1024*1024,Hc=class extends Error{constructor(r,n,i,o){super(`${r} ${n.join(" ")} failed${i?`: ${i}`:""}`,o);this.command=r;this.args=n;this.stderr=i;this.name="ExternalCommandError",this.timedOut=o?.timedOut===!0}command;args;stderr;timedOut}});var xN=x(()=>{"use strict"});import{execFileSync as LB}from"child_process";import PN from"fs";import Xi from"path";import{AsyncLocalStorage as $g}from"node:async_hooks";function Wd(e){return Uc.getStore()?e():Uc.run(new Map,e)}function VB(e){let t=Uc.getStore();for(let r of e)t?.set(Zi(r.root),e);return e}function Jc(e,t){return ds(()=>LB("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function we(e,t){return Zi(e)===Zi(t)}function Zi(e){let t=Xi.resolve(e);try{let r=PN.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function de(e){let t=qB.getStore()?.get(Zi(e));if(t)return{...t};try{let r=ON.getStore()?.get(Zi(e)),n=Uc.getStore()?.get(r??Zi(e));if(n){let c=jg(r??e,n);if(c)return c;if(n.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=TN(e),o=jg(e,i);if(o&&PN.existsSync(Xi.join(e,".git")))return o;let a=Xi.resolve(Jc(e,["rev-parse","--show-toplevel"])),s=jg(a,i);if(!s)throw new Error("Current worktree is missing from Git worktree list");return s}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Ld(e){try{let t=Uc.getStore()?.get(ON.getStore()?.get(Zi(e))??Zi(e));return t?t.map(r=>({...r})):TN(e)}catch{return[]}}function TN(e){let t=MB(Jc(e,["worktree","list","--porcelain","-z"]));return VB(t),t.map(r=>({...r}))}function MB(e){let t=e.split("\0"),r=[],n=null;for(let i of t)i.startsWith("worktree ")?(n&&r.push(n),n={root:Xi.resolve(i.slice(9)),branch:null,detached:!1}):n&&i.startsWith("branch refs/heads/")?n.branch=i.slice(18):n&&i==="detached"&&(n.detached=!0);return n&&r.push(n),r}function Mt(e){return Ld(e).map(t=>t.root)}function jg(e,t){let r=t.find(o=>we(Xi.resolve(o.root),Xi.resolve(e)));if(!r)return null;let n=Xi.resolve(t[0].root),i=Xi.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!we(n,i),currentWorktreeRoot:i,primaryWorktreeRoot:n,currentBranch:r.branch}}function zc(e,t){try{return Jc(e,["check-ref-format","--branch",t]),Jc(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function ye(e,t){try{let r=Jc(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Uc,ON,qB,Ze=x(()=>{"use strict";Bd();Qc();xN();Og();Uc=new $g,ON=new $g,qB=new $g});import qd from"node:path";function Dg(...e){if(e.length===0)return qd.resolve();if(qd.win32.isAbsolute(e[0])){let t=qd.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return qd.resolve(...e)}var jN=x(()=>{"use strict"});function $N(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>{let r=t.toUpperCase();return!FB.has(r)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(r)}))}var FB,DN=x(()=>{"use strict";FB=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_PREFIX","GIT_IMPLICIT_WORK_TREE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"])});import{execFileSync as HB}from"node:child_process";import{lstatSync as QB,realpathSync as Bg}from"node:fs";import Wg from"node:path";function qg(e,t,r=JB){try{return ds(()=>HB("git",["-C",e,...t],{encoding:"utf8",env:$N(),stdio:["ignore","pipe","pipe"],timeout:UB,killSignal:"SIGKILL",maxBuffer:r,windowsHide:!0}))}catch(n){let i=typeof n.stderr=="string"?n.stderr.trim():Buffer.isBuffer(n.stderr)?n.stderr.toString("utf8").trim():"";throw new Lg(e,t,i)}}function q(e,t){return qg(e,t).trim()}function BN(e,t,r){let n=q(t,["ls-tree","-r","-z",r]),i=q(e,["ls-tree","-r","-z","HEAD"]),o=q(e,["merge-base","HEAD",r]),a=q(e,["ls-tree","-r","-z",o]),s=u=>new Map(u.split("\0").flatMap(f=>{let d=f.match(/^160000 commit ([a-f0-9]{40}(?:[a-f0-9]{24})?)\t(.+)$/su);return d?[[d[2],d[1]]]:[]})),c=s(i),l=s(a);for(let u of n.split("\0")){let f=u.match(/^160000 commit ([a-f0-9]{40}(?:[a-f0-9]{24})?)\t(.+)$/su);if(!f)continue;let[,d,m]=f;if(c.get(m)===d||c.get(m)===l.get(m))continue;if(Wg.isAbsolute(m)||m.split("/").some(v=>v===".."||v===".git"))throw new Error(`Unsafe Git submodule path: ${m}`);let h=v=>{let w=Wg.resolve(v,...m.split("/")),y=Wg.resolve(Bg(v),...m.split("/")),b=QB(w);if(!b.isDirectory()||b.isSymbolicLink()||Bg(w)!==y||Bg(q(w,["rev-parse","--show-toplevel"]))!==y)throw new Error(`Git 子仓 ${m} 未初始化或路径不安全;请先恢复子仓检出再重试合并`);return w},p=h(e);try{q(p,["cat-file","-e",`${d}^{commit}`]);continue}catch{}let g=h(t);try{q(g,["cat-file","-e",`${d}^{commit}`]),q(p,["fetch","--no-tags","--no-write-fetch-head","--",g,d]),q(p,["cat-file","-e",`${d}^{commit}`])}catch(v){throw new Error(`Git 子仓 ${m} 无法从 ${g} 导入合并所需提交 ${d};请先在目标子仓 fetch 该提交后重试原合并`,{cause:v})}}}function WN(e,t){if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(t))throw new Error("Invalid Git blob id");return qg(e,["cat-file","blob",t],Number.MAX_SAFE_INTEGER)}function Zo(e){return q(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Vg(e,t){q(e,["check-ref-format","--branch",t])}function eo(e){return zB(qg(e,["status","--porcelain=v1","-z","--untracked-files=all"]))}function zB(e){return[...new Set(KB(e).flatMap(t=>t.paths.map(r=>r.replaceAll("\\","/"))))].sort()}function KB(e){if(!e)return[];let t=e.split("\0").filter(Boolean),r=[];for(let n=0;n<t.length;n+=1){let i=t[n];if(i.length<4)throw new Error("Git status returned an invalid porcelain record");let o=[i.slice(3)];if(i[0]==="R"||i[0]==="C"||i[1]==="R"||i[1]==="C"){let a=t[n+1];if(!a)throw new Error("Git status returned an incomplete rename record");o.push(a),n+=1}r.push({status:i.slice(0,2),paths:o})}return r}function LN(e,t){try{let n=q(e,["config","--get",`branch.${t}.remote`]);if(n&&n!==".")return n}catch{}let r=q(e,["remote"]).split(/\r?\n/u).map(n=>n.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var UB,JB,Lg,rr=x(()=>{"use strict";Bd();DN();Qc();UB=3e4,JB=8*1024*1024,Lg=class extends Error{constructor(r,n,i){super(`git ${n.join(" ")} failed${i?`: ${i}`:""}`);this.cwd=r;this.args=n;this.stderr=i;this.name="GitCommandError"}cwd;args;stderr}});function ps(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Gn(e){return`<${e.join("|")}>`}var Kc,ea,Gc,Vd,Yc,qN,ta=x(()=>{"use strict";Kc=["passed","failed","not-run"],ea=["pass","fail","blocked"],Gc=["passed","failed","blocked"],Vd=["aligned","conflict","blocked"],Yc=["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"],qN=["final-result"]});function VN(e){return{phase:e.phase,...e.task?{task:e.task}:{},contextMode:"snapshot",commandArgs:["comet","task",e.projectRoot??".","--task",e.task??"<original-task>","--phase",e.phase,"--session",e.sessionId??"<receiving-session-id>","--context-mode","snapshot",...e.workflow&&e.change?["--workflow",e.workflow,"--change",e.change]:[],"--json"],instruction:[e.language==="zh-CN"?"领取响应已有 contextDelivery 时直接读取 context[].text,不重复检索;上下文丢失时使用 contextActions.restore。其他情况下,首次进入本阶段、交接给新 Agent 或上下文恢复后,由接收方用自己的会话标识和原始请求执行一次本命令,将返回的 context[].text 加入上下文;普通连续执行无需重复获取。将适用偏好和项目约束交给执行者与审查者。Skill 由平台按实际可用能力加载;不兼容或不可用时说明原因。已交付偏好不代表已加载或遵循 Skill;偏好不能代替 Runtime 检查或阶段授权。空结果或获取失败时沿用明确指令继续,不循环重试。":"When the claim response includes contextDelivery, read context[].text without another retrieval; use contextActions.restore after context loss. Otherwise, on first entering this phase, handing off to a new Agent, or restoring context, the receiver runs this command once with its own session ID and the original task, then adds context[].text to context. Do not repeat during uninterrupted work. Pass applicable preferences and project constraints to implementers and reviewers. Load Skills using actual host capabilities; explain unavailable or incompatible choices. Delivery does not prove a Skill was loaded or followed; preferences do not replace Runtime checks or authorization. Continue with explicit instructions after empty or unavailable retrieval; do not loop on retries.",e.instruction].filter(Boolean).join(" ")}}var MN=x(()=>{"use strict"});import GB from"node:path";function FN(e,t){let r=t.actions.map(o=>o.stepId==="repair.implementation"&&o.status==="succeeded").lastIndexOf(!0),n=t.actions[r];if(r<0||n?.outcome?.output?.driftKind!=="report-drift"||t.actions.slice(r+1).some(o=>o.stepId==="verify.report"&&o.status==="succeeded"))return null;let i=t.input.artifactRootRef;return typeof i!="string"?null:{ref:GB.posix.join(i.replaceAll("\\","/"),"comet","changes",e.name,"verification.md"),instruction:e.language==="zh-CN"?"读取用户修改的原验证报告,核对其补充并作为待验证输入;不得将旧报告当作新候选已通过的证据。":"Read the user-edited verification report and assess its notes as inputs; do not treat the old report as proof that the new candidate passed."}}function Xc(e,t){let r=e.builder_handoff?.candidate_id??null,n=new Map;for(let o of t.actions){if(!["verify.checks","verify.requested-checks"].includes(o.stepId)||!o.outcome)continue;let a=o.outcome.output;if(a?.candidateId===r)for(let s of a.checks??[])n.set(s.id,{id:s.id,status:s.status,actionId:o.id,logRef:s.logRef,inputScope:s.inputScope?.kind??"project"})}let i=[...t.actions].reverse().find(o=>o.stepId==="verify.verifier"&&o.status==="succeeded");return{schema:"comet.native.repair-context.v1",previousCandidateId:r,unresolvedAcceptanceIds:e.loop.previous_unresolved_ids,previousVerifierActionId:i?.id??null,previousChecks:[...n.values()],...FN(e,t)?{userEditedReport:FN(e,t)}:{},candidateHandling:"review-existing-work-first",instruction:e.language==="zh-CN"?"先核对并保留用户当前修改。若现有工作已满足已确认需求,原样提交后继候选,无需为推进流程重新写入;确有遗漏时只修复遗漏。旧检查由 Runtime 判断复用,新候选仍需独立验收全部验收项。":"Inspect and preserve the user’s current changes first. If the existing work satisfies the approved requirements, submit it unchanged as the successor candidate; do not rewrite files merely to advance. Repair only actual gaps. Runtime decides check reuse and the successor still requires independent verification of every acceptance criterion."}}function ms(e){return VN({...e,workflow:"native",change:e.name,instruction:e.language==="zh-CN"?"原始请求缺失时从当前 brief 恢复目标。向 Builder、Verifier 或子任务交接时不转交 Builder 的自评结论,保留独立只读验收要求。":"Recover a missing task goal from the current brief. Hand off to the Builder, Verifier or child without Builder self-assessment, preserving independent read-only verification."})}var Zc=x(()=>{"use strict";MN()});function ra(e,t,r,n=""){let i=Object.keys(e),o=t.filter(s=>!Object.hasOwn(e,s)),a=i.filter(s=>!t.includes(s));if(o.length||a.length)throw new el({code:"invalid-fields",path:n,context:r,missingFields:o,unknownFields:a,expectedFields:[...t]})}var el,Md=x(()=>{"use strict";el=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function Mg(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Fg(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){Mg(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:hr,executionRef:Mg(t.executionRef,"Native execution ref"),[HN]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:Mg(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[QN]:!0})}})}function Hg(e){return typeof e=="object"&&e!==null&&e[QN]===!0}function UN(e){return typeof e=="object"&&e!==null&&e[HN]===!0}var HN,QN,hr,na=x(()=>{"use strict";HN=Symbol("comet.native.trusted-execution-identity"),QN=Symbol("comet.native.trusted-verifier-envelope"),hr="skill-coordinated"});function Fd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function JN(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hd(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Qd(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,n)=>{let i=Fd(r,`Native Verifier acceptance ${n}`);ra(i,["id","result","reason"],`Native Verifier acceptance ${n}`,`${t}/${n}`);let o=Hd(i.id,`Native Verifier acceptance ${n} ID`),a=ps(i.result,Gc,`Native Verifier acceptance ${o} result`);return{id:o,result:a,reason:Hd(i.reason,`Native Verifier acceptance ${o} reason`)}})}function YB(e,t){let r=Fd(e,"Native Verifier final result");ra(r,["iteration","attempt","verdict","acceptance","risks","summary",...Object.hasOwn(r,"requestReview")?["requestReview"]:[]],"Native Verifier final result",t);let n=ps(r.verdict,ea,"Native Verifier verdict");if(!Array.isArray(r.risks)||!r.risks.every(o=>typeof o=="string"))throw new Error("Native Verifier risks must be text entries");let i;if(r.requestReview!==void 0){let o=Fd(r.requestReview,"Native requestReview");ra(o,["result","reason"],"Native requestReview",`${t}/requestReview`),i={result:ps(o.result,Vd,"Native requestReview result"),reason:Hd(o.reason,"Native requestReview reason")}}return{...i?{requestReview:i}:{},iteration:JN(r.iteration,"Native Verifier iteration"),attempt:JN(r.attempt,"Native Verifier attempt"),verdict:n,acceptance:Qd(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:Hd(r.summary,"Native Verifier summary")}}function zN(e,t=""){let r=Fd(e,"Native Verifier response");if(r.kind==="final-result")return ra(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:YB(r.result,`${t}/result`)};throw new Error(`Native Verifier response kind must be one of: ${qN.join(", ")}`)}function KN(e){if(!Hg(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(r.requireIndependentSession!==!1&&t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let n=zN(t.payload),i=n.result.iteration,o=n.result.attempt;if(i!==r.iteration||o!==r.attempt)throw new Error(`Native Verifier result is stale for the current iteration or attempt: expected iteration=${r.iteration}, attempt=${r.attempt}; received iteration=${i}, attempt=${o}. Inspect the current action and use its outputTemplate before submitting a new outcomeId`);let a=Ud(n.result,r);return{...n,result:{...n.result,acceptance:a}}}function Ud(e,t){Qd(e.acceptance);let r=[...t.acceptanceIds],n=new Set(t.knownAcceptanceIds??r),i=new Set(t.previouslyPassedAcceptanceIds??[]),o=r.filter(p=>!n.has(p)),a=[...i].filter(p=>!n.has(p));if(o.length>0||a.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:p})=>p),l=c.filter((p,g)=>c.indexOf(p)!==g),u=c.filter(p=>!n.has(p)),f=r.filter(p=>!c.includes(p)),d=e.acceptance.filter(({id:p,result:g})=>s.has(p)||!n.has(p)?!1:!i.has(p)||g!=="passed").map(({id:p,result:g})=>`${p}=${g}`);if(l.length>0||u.length>0||f.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${f.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let m=e.acceptance.filter(({id:p})=>s.has(p));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let h=m.map(({result:p})=>p);if(e.verdict==="pass"&&h.some(p=>p!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!h.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!h.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return m}var tl=x(()=>{"use strict";ta();Md();na()});function hs(e,t){if(!XB.test(e))throw new Error(`${t} must be a Git commit`)}function Qg(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function zd(e){hs(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:n})=>n)),r=e.contract.children.map(n=>({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Ai(e.contract,n.name),builderFailureCount:0}));for(let n of r)for(let i of n.dependsOn)if(!t.has(i))throw new Error(`Native Supervisor child ${n.name} depends on unknown child ${i}`);return{schema:rl,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function Ai(e,t){let r=e.children.find(n=>n.name===t);return r.covers.length>0?r.covers.map(n=>({id:n,source:e.acceptance_index?.[n]?.source??"brief.md",text:e.acceptance_index?.[n]?.text??n})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Kd(e){let t=e.children.every(n=>n.acceptanceScope&&n.acceptanceScope.length>0&&(!n.task||n.task.acceptance&&n.task.acceptance.length>0)),r=e.children.map(n=>({name:n.name,summary:n.summary,dependsOn:[...n.dependsOn],covers:n.acceptanceScope?.map(({id:i})=>i)??[],status:(n.status==="ready"||n.status==="active")&&n.blocker&&[...e.history].reverse().find(i=>i.child===n.name)?.kind==="task-blocked"?"blocked":n.status,phase:null,projectRoot:n.projectRoot??n.task?.projectRoot??null,message:t?n.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:n.builderFailureCount??0}));return{contractRef:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:n})=>n==="ready").map(({name:n})=>n):[],allDone:t&&r.every(({status:n})=>n==="integrated"||n==="archived")}}var XB,rl,Jd,Yn=x(()=>{"use strict";ta();Zc();tl();XB=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;rl="comet.native.supervisor.v2",Jd=3});import{promises as Jg}from"node:fs";async function zg(e,t){let r;for(let n=0;n<=Ug.length;n+=1)try{return await e()}catch(i){r=i;let o=i.code;if(n===Ug.length||!ZB.has(o??""))throw i;await new Promise(a=>setTimeout(a,Ug[n]))}throw r}async function ia(e,t){await zg(()=>Jg.rename(e,t),`rename ${t}`)}async function nl(e){await zg(()=>Jg.unlink(e),`unlink ${e}`)}async function gs(e,t){await zg(()=>Jg.link(e,t),`link ${t}`)}var ZB,Ug,Gd=x(()=>{"use strict";ZB=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Ug=[50,100,200]});function to(e){return e!==0&&e!==0n&&e!=="0"}function il(e,t){return to(e.dev)&&to(t.dev)&&to(e.ino)&&to(t.ino)}function ht(e,t){let r=to(e.dev)&&to(t.dev);if(r&&e.dev!==t.dev)return!1;let n=to(e.ino)&&to(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var vs=x(()=>{"use strict"});var ol=x(()=>{"use strict";vs()});import{randomUUID as eW}from"crypto";import{promises as gr}from"fs";import On from"path";function Yd(e,t){let r=On.relative(e,t);return r===""||!On.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${On.sep}`)}function tW(e,t){return ht({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xd(e,t){return ht({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function rW(e,t){return Xd(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function GN(e){let t=await gr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await gr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ws(e){for(let t of e){let r=await gr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tW(t,r)||await gr.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function nW(e,t,r){let[n,i]=await Promise.all([gr.lstat(e),gr.realpath(e),r?ws(r):Promise.resolve()]);if(!n.isFile()||n.isSymbolicLink()||!Xd(n,t)||r&&!Yd(r[0].realPath,i))throw new Error("Native atomic write temporary file changed after close");return n}async function iW(e,t){let r=On.resolve(e),n=On.resolve(t);if(!Yd(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let i=[await GN(r)],o=On.relative(r,n).split(On.sep).filter(Boolean),a=r;for(let s of o){await ws(i),a=On.join(a,s);try{await gr.mkdir(a)}catch(l){if(l.code!=="EEXIST")throw l}let c=await GN(a);if(!Yd(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${a}`);i.push(c)}return await ws(i),i}async function al(e){let t;try{t=await gr.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function oW(e,t,r={}){let n=On.dirname(e),i=r.containedRoot?await iW(r.containedRoot,n):null;i||await gr.mkdir(n,{recursive:!0});let o=On.join(n,`.${On.basename(e)}.${eW()}.tmp`),a,s,c;try{if(await r.beforeTemporaryOpen?.(),a=await gr.open(o,"wx"),s=await a.stat(),i){let[l,u]=await Promise.all([gr.lstat(o),gr.realpath(o)]);if(await ws(i),!l.isFile()||l.isSymbolicLink()||!Xd(s,l)||!Yd(i[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await a.writeFile(t,"utf8"):await a.writeFile(t),await a.sync(),c=await a.stat(),!Xd(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await a.close(),a=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await nW(o,c,i),await r.beforeCommit?.(),i){await ws(i);let l=await gr.lstat(o);if(!l.isFile()||l.isSymbolicLink()||!c||!rW(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await gs(o,e),await nl(o)):await ia(o,e),await al(n)}catch(l){if(await a?.close(),!i)await gr.rm(o,{force:!0});else try{await ws(i),await gr.rm(o,{force:!0})}catch{}throw l}}async function et(e,t,r={}){await oW(e,t,r)}async function Pr(e,t,r={}){await et(e,JSON.stringify(t,null,2)+`
5
+ `,r)}var bt=x(()=>{"use strict";Gd();ol()});var Te=D(Jt=>{"use strict";var Kg=Symbol.for("yaml.alias"),YN=Symbol.for("yaml.document"),Zd=Symbol.for("yaml.map"),XN=Symbol.for("yaml.pair"),Gg=Symbol.for("yaml.scalar"),ef=Symbol.for("yaml.seq"),Ri=Symbol.for("yaml.node.type"),aW=e=>!!e&&typeof e=="object"&&e[Ri]===Kg,sW=e=>!!e&&typeof e=="object"&&e[Ri]===YN,cW=e=>!!e&&typeof e=="object"&&e[Ri]===Zd,lW=e=>!!e&&typeof e=="object"&&e[Ri]===XN,ZN=e=>!!e&&typeof e=="object"&&e[Ri]===Gg,uW=e=>!!e&&typeof e=="object"&&e[Ri]===ef;function eS(e){if(e&&typeof e=="object")switch(e[Ri]){case Zd:case ef:return!0}return!1}function dW(e){if(e&&typeof e=="object")switch(e[Ri]){case Kg:case Zd:case Gg:case ef:return!0}return!1}var fW=e=>(ZN(e)||eS(e))&&!!e.anchor;Jt.ALIAS=Kg;Jt.DOC=YN;Jt.MAP=Zd;Jt.NODE_TYPE=Ri;Jt.PAIR=XN;Jt.SCALAR=Gg;Jt.SEQ=ef;Jt.hasAnchor=fW;Jt.isAlias=aW;Jt.isCollection=eS;Jt.isDocument=sW;Jt.isMap=cW;Jt.isNode=dW;Jt.isPair=lW;Jt.isScalar=ZN;Jt.isSeq=uW});var sl=D(Yg=>{"use strict";var Tt=Te(),Or=Symbol("break visit"),tS=Symbol("skip children"),Xn=Symbol("remove node");function tf(e,t){let r=rS(t);Tt.isDocument(e)?ys(null,e.contents,r,Object.freeze([e]))===Xn&&(e.contents=null):ys(null,e,r,Object.freeze([]))}tf.BREAK=Or;tf.SKIP=tS;tf.REMOVE=Xn;function ys(e,t,r,n){let i=nS(e,t,r,n);if(Tt.isNode(i)||Tt.isPair(i))return iS(e,n,i),ys(e,i,r,n);if(typeof i!="symbol"){if(Tt.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=ys(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===Or)return Or;a===Xn&&(t.items.splice(o,1),o-=1)}}}else if(Tt.isPair(t)){n=Object.freeze(n.concat(t));let o=ys("key",t.key,r,n);if(o===Or)return Or;o===Xn&&(t.key=null);let a=ys("value",t.value,r,n);if(a===Or)return Or;a===Xn&&(t.value=null)}}return i}async function rf(e,t){let r=rS(t);Tt.isDocument(e)?await ks(null,e.contents,r,Object.freeze([e]))===Xn&&(e.contents=null):await ks(null,e,r,Object.freeze([]))}rf.BREAK=Or;rf.SKIP=tS;rf.REMOVE=Xn;async function ks(e,t,r,n){let i=await nS(e,t,r,n);if(Tt.isNode(i)||Tt.isPair(i))return iS(e,n,i),ks(e,i,r,n);if(typeof i!="symbol"){if(Tt.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=await ks(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===Or)return Or;a===Xn&&(t.items.splice(o,1),o-=1)}}}else if(Tt.isPair(t)){n=Object.freeze(n.concat(t));let o=await ks("key",t.key,r,n);if(o===Or)return Or;o===Xn&&(t.key=null);let a=await ks("value",t.value,r,n);if(a===Or)return Or;a===Xn&&(t.value=null)}}return i}function rS(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function nS(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Tt.isMap(t))return r.Map?.(e,t,n);if(Tt.isSeq(t))return r.Seq?.(e,t,n);if(Tt.isPair(t))return r.Pair?.(e,t,n);if(Tt.isScalar(t))return r.Scalar?.(e,t,n);if(Tt.isAlias(t))return r.Alias?.(e,t,n)}function iS(e,t,r){let n=t[t.length-1];if(Tt.isCollection(n))n.items[e]=r;else if(Tt.isPair(n))e==="key"?n.key=r:n.value=r;else if(Tt.isDocument(n))n.contents=r;else{let i=Tt.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Yg.visit=tf;Yg.visitAsync=rf});var Xg=D(aS=>{"use strict";var oS=Te(),pW=sl(),mW={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hW=e=>e.replace(/[!,[\]{}]/g,t=>mW[t]),cl=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[o,a]=n;return this.tags[o]=a,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[o]=n;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let a=/^\d+\.\d+$/.test(o);return r(6,`Unsupported YAML version ${o}`,a),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let a=t.slice(2,-1);return a==="!"||a==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),a)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let o=this.tags[n];if(o)try{return o+decodeURIComponent(i)}catch(a){return r(String(a)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+hW(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&oS.isNode(t.contents)){let o={};pW.visit(t.contents,(a,s)=>{oS.isNode(s)&&s.tag&&(o[s.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,a]of n)o==="!!"&&a==="tag:yaml.org,2002:"||(!t||i.some(s=>s.startsWith(a)))&&r.push(`%TAG ${o} ${a}`);return r.join(`
6
+ `)}};cl.defaultYaml={explicit:!1,version:"1.2"};cl.defaultTags={"!!":"tag:yaml.org,2002:"};aS.Directives=cl});var nf=D(ll=>{"use strict";var sS=Te(),gW=sl();function vW(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function cS(e){let t=new Set;return gW.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function lS(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function wW(e,t){let r=[],n=new Map,i=null;return{onAnchor:o=>{r.push(o),i??(i=cS(e));let a=lS(t,i);return i.add(a),a},setAnchors:()=>{for(let o of r){let a=n.get(o);if(typeof a=="object"&&a.anchor&&(sS.isScalar(a.node)||sS.isCollection(a.node)))a.node.anchor=a.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=o,s}}},sourceObjects:n}}ll.anchorIsValid=vW;ll.anchorNames=cS;ll.createNodeAnchors=wW;ll.findNewAnchor=lS});var Zg=D(uS=>{"use strict";function ul(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,o=n.length;i<o;++i){let a=n[i],s=ul(e,n,String(i),a);s===void 0?delete n[i]:s!==a&&(n[i]=s)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let o=n.get(i),a=ul(e,n,i,o);a===void 0?n.delete(i):a!==o&&n.set(i,a)}else if(n instanceof Set)for(let i of Array.from(n)){let o=ul(e,n,i,i);o===void 0?n.delete(i):o!==i&&(n.delete(i),n.add(o))}else for(let[i,o]of Object.entries(n)){let a=ul(e,n,i,o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}return e.call(t,r,n)}uS.applyReviver=ul});var ro=D(fS=>{"use strict";var yW=Te();function dS(e,t,r){if(Array.isArray(e))return e.map((n,i)=>dS(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!yW.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=o=>{n.res=o,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}fS.toJS=dS});var of=D(mS=>{"use strict";var kW=Zg(),pS=Te(),bW=ro(),ev=class{constructor(t){Object.defineProperty(this,pS.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:o}={}){if(!pS.isDocument(t))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=bW.toJS(this,"",a);if(typeof i=="function")for(let{count:c,res:l}of a.anchors.values())i(l,c);return typeof o=="function"?kW.applyReviver(o,{"":s},"",s):s}};mS.NodeBase=ev});var dl=D(hS=>{"use strict";var AW=nf(),RW=sl(),bs=Te(),NW=of(),SW=ro(),tv=class extends NW.NodeBase{constructor(t){super(bs.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],RW.visit(t,{Node:(o,a)=>{(bs.isAlias(a)||bs.hasAnchor(a))&&n.push(a)}}),r&&(r.aliasResolveCache=n));let i;for(let o of n){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:o}=r,a=this.resolve(i,r);if(!a){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(a);if(s||(SW.toJS(a,null,r),s=n.get(a)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=af(i,a,n)),s.count*s.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(AW.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${i} `}return i}};function af(e,t,r){if(bs.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(bs.isCollection(t)){let n=0;for(let i of t.items){let o=af(e,i,r);o>n&&(n=o)}return n}else if(bs.isPair(t)){let n=af(e,t.key,r),i=af(e,t.value,r);return Math.max(n,i)}return 1}hS.Alias=tv});var Et=D(rv=>{"use strict";var EW=Te(),CW=of(),_W=ro(),IW=e=>!e||typeof e!="function"&&typeof e!="object",no=class extends CW.NodeBase{constructor(t){super(EW.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:_W.toJS(this.value,t,r)}toString(){return String(this.value)}};no.BLOCK_FOLDED="BLOCK_FOLDED";no.BLOCK_LITERAL="BLOCK_LITERAL";no.PLAIN="PLAIN";no.QUOTE_DOUBLE="QUOTE_DOUBLE";no.QUOTE_SINGLE="QUOTE_SINGLE";rv.Scalar=no;rv.isScalarValue=IW});var fl=D(vS=>{"use strict";var xW=dl(),oa=Te(),gS=Et(),PW="tag:yaml.org,2002:";function OW(e,t,r){if(t){let n=r.filter(o=>o.tag===t),i=n.find(o=>!o.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function TW(e,t,r){if(oa.isDocument(e)&&(e=e.contents),oa.isNode(e))return e;if(oa.isPair(e)){let f=r.schema[oa.MAP].createNode?.(r.schema,null,r);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:o,schema:a,sourceObjects:s}=r,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new xW.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=PW+t.slice(2));let l=OW(e,t,a.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new gS.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?a[oa.MAP]:Symbol.iterator in Object(e)?a[oa.SEQ]:a[oa.MAP]}o&&(o(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new gS.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}vS.createNode=TW});var cf=D(sf=>{"use strict";var jW=fl(),Zn=Te(),$W=of();function nv(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let o=t[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let a=[];a[o]=n,n=a}else n=new Map([[o,n]])}return jW.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var wS=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,iv=class extends $W.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>Zn.isNode(n)||Zn.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(wS(t))this.add(r);else{let[n,...i]=t,o=this.get(n,!0);if(Zn.isCollection(o))o.addIn(i,r);else if(o===void 0&&this.schema)this.set(n,nv(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(Zn.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,o=this.get(n,!0);return i.length===0?!r&&Zn.isScalar(o)?o.value:o:Zn.isCollection(o)?o.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Zn.isPair(r))return!1;let n=r.value;return n==null||t&&Zn.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return Zn.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let o=this.get(n,!0);if(Zn.isCollection(o))o.setIn(i,r);else if(o===void 0&&this.schema)this.set(n,nv(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};sf.Collection=iv;sf.collectionFromPath=nv;sf.isEmptyPath=wS});var pl=D(lf=>{"use strict";var DW=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ov(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var BW=(e,t,r)=>e.endsWith(`
7
+ `)?ov(r,t):r.includes(`
8
+ `)?`
9
+ `+ov(r,t):(e.endsWith(" ")?"":" ")+r;lf.indentComment=ov;lf.lineComment=BW;lf.stringifyComment=DW});var kS=D(ml=>{"use strict";var WW="flow",av="block",uf="quoted";function LW(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:o=20,onFold:a,onOverflow:s}={}){if(!i||i<0)return e;i<o&&(o=0);let c=Math.max(1+o,1+i-t.length);if(e.length<=c)return e;let l=[],u={},f=i-t.length;typeof n=="number"&&(n>i-Math.max(2,o)?l.push(0):f=i-n);let d,m,h=!1,p=-1,g=-1,v=-1;r===av&&(p=yS(e,p,t.length),p!==-1&&(f=p+c));for(let y;y=e[p+=1];){if(r===uf&&y==="\\"){switch(g=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}v=p}if(y===`
10
+ `)r===av&&(p=yS(e,p,t.length)),f=p+t.length+c,d=void 0;else{if(y===" "&&m&&m!==" "&&m!==`
11
+ `&&m!==" "){let b=e[p+1];b&&b!==" "&&b!==`
12
+ `&&b!==" "&&(d=p)}if(p>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===uf){for(;m===" "||m===" ";)m=y,y=e[p+=1],h=!0;let b=p>v+1?p-2:g-1;if(u[b])return e;l.push(b),u[b]=!0,f=b+c,d=void 0}else h=!0}m=y}if(h&&s&&s(),l.length===0)return e;a&&a();let w=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let b=l[y],N=l[y+1]||e.length;b===0?w=`
13
+ ${t}${e.slice(0,N)}`:(r===uf&&u[b]&&(w+=`${e[b]}\\`),w+=`
14
+ ${t}${e.slice(b+1,N)}`)}return w}function yS(e,t,r){let n=t,i=t+1,o=e[i];for(;o===" "||o===" ";)if(t<i+r)o=e[++t];else{do o=e[++t];while(o&&o!==`
15
+ `);n=t,i=t+1,o=e[i]}return n}ml.FOLD_BLOCK=av;ml.FOLD_FLOW=WW;ml.FOLD_QUOTED=uf;ml.foldFlowLines=LW});var gl=D(bS=>{"use strict";var Tn=Et(),io=kS(),ff=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),pf=e=>/^(%|---|\.\.\.)/m.test(e);function qW(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let o=0,a=0;o<i;++o)if(e[o]===`
16
+ `){if(o-a>n)return!0;if(a=o+1,i-a<=n)return!1}return!0}function hl(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(pf(e)?" ":""),a="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(a+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{a+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:u.substr(0,2)==="00"?a+="\\x"+u.substr(2):a+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(a+=r.slice(s,c)+`
17
+
18
+ `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)a+=`
19
+ `,c+=2;a+=o,r[c+2]===" "&&(a+="\\"),c+=1,s=c+1}break;default:c+=1}return a=s?a+r.slice(s):r,n?a:io.foldFlowLines(a,o,io.FOLD_QUOTED,ff(t,!1))}function sv(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
20
+ `)||/[ \t]\n|\n[ \t]/.test(e))return hl(e,t);let r=t.indent||(pf(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
21
+ ${r}`)+"'";return t.implicitKey?n:io.foldFlowLines(n,r,io.FOLD_FLOW,ff(t,!1))}function As(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=hl;else{let i=e.includes('"'),o=e.includes("'");i&&!o?n=sv:o&&!i?n=hl:n=r?sv:hl}return n(e,t)}var cv;try{cv=new RegExp(`(^|(?<!
22
+ ))
23
+ +(?!
24
+ |$)`,"g")}catch{cv=/\n+(?!\n|$)/g}function df({comment:e,type:t,value:r},n,i,o){let{blockQuote:a,commentString:s,lineWidth:c}=n.options;if(!a||/\n[\t ]+$/.test(r))return As(r,n);let l=n.indent||(n.forceBlockIndent||pf(r)?" ":""),u=a==="literal"?!0:a==="folded"||t===Tn.Scalar.BLOCK_FOLDED?!1:t===Tn.Scalar.BLOCK_LITERAL?!0:!qW(r,c,l.length);if(!r)return u?`|
25
+ `:`>
26
+ `;let f,d;for(d=r.length;d>0;--d){let N=r[d-1];if(N!==`
27
+ `&&N!==" "&&N!==" ")break}let m=r.substring(d),h=m.indexOf(`
28
+ `);h===-1?f="-":r===m||h!==m.length-1?(f="+",o&&o()):f="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
29
+ `&&(m=m.slice(0,-1)),m=m.replace(cv,`$&${l}`));let p=!1,g,v=-1;for(g=0;g<r.length;++g){let N=r[g];if(N===" ")p=!0;else if(N===`
30
+ `)v=g;else break}let w=r.substring(0,v<g?v+1:g);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let b=(p?l?"2":"1":"")+f;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let N=r.replace(/\n+/g,`
31
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),A=!1,S=ff(n,!0);a!=="folded"&&t!==Tn.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{A=!0});let _=io.foldFlowLines(`${w}${N}${m}`,l,io.FOLD_BLOCK,S);if(!A)return`>${b}
32
+ ${l}${_}`}return r=r.replace(/\n+/g,`$&${l}`),`|${b}
33
+ ${l}${w}${r}${m}`}function VW(e,t,r,n){let{type:i,value:o}=e,{actualString:a,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&o.includes(`
34
+ `)||u&&/[[\]{},]/.test(o))return As(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return s||u||!o.includes(`
35
+ `)?As(o,t):df(e,t,r,n);if(!s&&!u&&i!==Tn.Scalar.PLAIN&&o.includes(`
36
+ `))return df(e,t,r,n);if(pf(o)){if(c==="")return t.forceBlockIndent=!0,df(e,t,r,n);if(s&&c===l)return As(o,t)}let f=o.replace(/\n+/g,`$&
37
+ ${c}`);if(a){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:m,tags:h}=t.doc.schema;if(h.some(d)||m?.some(d))return As(o,t)}return s?f:io.foldFlowLines(f,c,io.FOLD_FLOW,ff(t,!1))}function MW(e,t,r,n){let{implicitKey:i,inFlow:o}=t,a=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Tn.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value)&&(s=Tn.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Tn.Scalar.BLOCK_FOLDED:case Tn.Scalar.BLOCK_LITERAL:return i||o?As(a.value,t):df(a,t,r,n);case Tn.Scalar.QUOTE_DOUBLE:return hl(a.value,t);case Tn.Scalar.QUOTE_SINGLE:return sv(a.value,t);case Tn.Scalar.PLAIN:return VW(a,t,r,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=t.options,d=i&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}bS.stringifyString=MW});var vl=D(lv=>{"use strict";var FW=nf(),oo=Te(),HW=pl(),QW=gl();function UW(e,t){let r=Object.assign({blockQuote:!0,commentString:HW.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function JW(e,t){if(t.tag){let i=e.filter(o=>o.tag===t.tag);if(i.length>0)return i.find(o=>o.format===t.format)??i[0]}let r,n;if(oo.isScalar(t)){n=t.value;let i=e.filter(o=>o.identify?.(n));if(i.length>1){let o=i.filter(a=>a.test);o.length>0&&(i=o)}r=i.find(o=>o.format===t.format)??i.find(o=>!o.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function zW(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],o=(oo.isScalar(e)||oo.isCollection(e))&&e.anchor;o&&FW.anchorIsValid(o)&&(r.add(o),i.push(`&${o}`));let a=e.tag??(t.default?null:t.tag);return a&&i.push(n.directives.tagString(a)),i.join(" ")}function KW(e,t,r,n){if(oo.isPair(e))return e.toString(t,r,n);if(oo.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,o=oo.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=JW(t.doc.schema.tags,o));let a=zW(o,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart??0)+a.length+1);let s=typeof i.stringify=="function"?i.stringify(o,t,r,n):oo.isScalar(o)?QW.stringifyString(o,t,r,n):o.toString(t,r,n);return a?oo.isScalar(o)||s[0]==="{"||s[0]==="["?`${a} ${s}`:`${a}
38
+ ${t.indent}${s}`:s}lv.createStringifyContext=UW;lv.stringify=KW});var SS=D(NS=>{"use strict";var Ni=Te(),AS=Et(),RS=vl(),wl=pl();function GW({key:e,value:t},r,n,i){let{allNullValues:o,doc:a,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=r,d=Ni.isNode(e)&&e.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Ni.isCollection(e)||!Ni.isNode(e)&&typeof e=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let m=!f&&(!e||d&&t==null&&!r.inFlow||Ni.isCollection(e)||(Ni.isScalar(e)?e.type===AS.Scalar.BLOCK_FOLDED||e.type===AS.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(f||!o),indent:s+c});let h=!1,p=!1,g=RS.stringify(e,r,()=>h=!0,()=>p=!0);if(!m&&!r.inFlow&&g.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(o||t==null)return h&&n&&n(),g===""?"?":m?`? ${g}`:g}else if(o&&!f||t==null&&m)return g=`? ${g}`,d&&!h?g+=wl.lineComment(g,r.indent,l(d)):p&&i&&i(),g;h&&(d=null),m?(d&&(g+=wl.lineComment(g,r.indent,l(d))),g=`? ${g}
39
+ ${s}:`):(g=`${g}:`,d&&(g+=wl.lineComment(g,r.indent,l(d))));let v,w,y;Ni.isNode(t)?(v=!!t.spaceBefore,w=t.commentBefore,y=t.comment):(v=!1,w=null,y=null,t&&typeof t=="object"&&(t=a.createNode(t))),r.implicitKey=!1,!m&&!d&&Ni.isScalar(t)&&(r.indentAtStart=g.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!m&&Ni.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let b=!1,N=RS.stringify(t,r,()=>b=!0,()=>p=!0),A=" ";if(d||v||w){if(A=v?`
40
+ `:"",w){let S=l(w);A+=`
41
+ ${wl.indentComment(S,r.indent)}`}N===""&&!r.inFlow?A===`
42
+ `&&y&&(A=`
43
+
44
+ `):A+=`
45
+ ${r.indent}`}else if(!m&&Ni.isCollection(t)){let S=N[0],_=N.indexOf(`
46
+ `),Q=_!==-1,F=r.inFlow??t.flow??t.items.length===0;if(Q||!F){let K=!1;if(Q&&(S==="&"||S==="!")){let Z=N.indexOf(" ");S==="&"&&Z!==-1&&Z<_&&N[Z+1]==="!"&&(Z=N.indexOf(" ",Z+1)),(Z===-1||_<Z)&&(K=!0)}K||(A=`
47
+ ${r.indent}`)}}else(N===""||N[0]===`
48
+ `)&&(A="");return g+=A+N,r.inFlow?b&&n&&n():y&&!b?g+=wl.lineComment(g,r.indent,l(y)):p&&i&&i(),g}NS.stringifyPair=GW});var dv=D(uv=>{"use strict";var ES=$d("process");function YW(e,...t){e==="debug"&&console.log(...t)}function XW(e,t){(e==="debug"||e==="warn")&&(typeof ES.emitWarning=="function"?ES.emitWarning(t):console.warn(t))}uv.debug=YW;uv.warn=XW});var wf=D(vf=>{"use strict";var gf=Te(),CS=Et(),mf="<<",hf={identify:e=>e===mf||typeof e=="symbol"&&e.description===mf,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new CS.Scalar(Symbol(mf)),{addToJSMap:_S}),stringify:()=>mf},ZW=(e,t)=>(hf.identify(t)||gf.isScalar(t)&&(!t.type||t.type===CS.Scalar.PLAIN)&&hf.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===hf.tag&&r.default);function _S(e,t,r){let n=IS(e,r);if(gf.isSeq(n))for(let i of n.items)fv(e,t,i);else if(Array.isArray(n))for(let i of n)fv(e,t,i);else fv(e,t,n)}function fv(e,t,r){let n=IS(e,r);if(!gf.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[o,a]of i)t instanceof Map?t.has(o)||t.set(o,a):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0});return t}function IS(e,t){return e&&gf.isAlias(t)?t.resolve(e.doc,e):t}vf.addMergeToJSMap=_S;vf.isMergeKey=ZW;vf.merge=hf});var mv=D(OS=>{"use strict";var eL=dv(),xS=wf(),tL=vl(),PS=Te(),pv=ro();function rL(e,t,{key:r,value:n}){if(PS.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(xS.isMergeKey(e,r))xS.addMergeToJSMap(e,t,n);else{let i=pv.toJS(r,"",e);if(t instanceof Map)t.set(i,pv.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let o=nL(r,i,e),a=pv.toJS(n,o,e);o in t?Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0}):t[o]=a}}return t}function nL(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(PS.isNode(e)&&r?.doc){let n=tL.createStringifyContext(r.doc,{});n.anchors=new Set;for(let o of r.anchors.keys())n.anchors.add(o.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),eL.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}OS.addPairToJSMap=rL});var ao=D(hv=>{"use strict";var TS=fl(),iL=SS(),oL=mv(),yf=Te();function aL(e,t,r){let n=TS.createNode(e,void 0,r),i=TS.createNode(t,void 0,r);return new kf(n,i)}var kf=class e{constructor(t,r=null){Object.defineProperty(this,yf.NODE_TYPE,{value:yf.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return yf.isNode(r)&&(r=r.clone(t)),yf.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return oL.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?iL.stringifyPair(this,t,r,n):JSON.stringify(this)}};hv.Pair=kf;hv.createPair=aL});var gv=D($S=>{"use strict";var aa=Te(),jS=vl(),bf=pl();function sL(e,t,r){return(t.inFlow??e.flow?lL:cL)(e,t,r)}function cL({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:o,onChompKeep:a,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:o,type:null}),f=!1,d=[];for(let h=0;h<t.length;++h){let p=t[h],g=null;if(aa.isNode(p))!f&&p.spaceBefore&&d.push(""),Af(r,d,p.commentBefore,f),p.comment&&(g=p.comment);else if(aa.isPair(p)){let w=aa.isNode(p.key)?p.key:null;w&&(!f&&w.spaceBefore&&d.push(""),Af(r,d,w.commentBefore,f))}f=!1;let v=jS.stringify(p,u,()=>g=null,()=>f=!0);g&&(v+=bf.lineComment(v,o,l(g))),f&&g&&(f=!1),d.push(n+v)}let m;if(d.length===0)m=i.start+i.end;else{m=d[0];for(let h=1;h<d.length;++h){let p=d[h];m+=p?`
49
+ ${c}${p}`:`
50
+ `}}return e?(m+=`
51
+ `+bf.indentComment(l(e),c),s&&s()):f&&a&&a(),m}function lL({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:o,flowCollectionPadding:a,options:{commentString:s}}=t;n+=o;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let h=0;h<e.length;++h){let p=e[h],g=null;if(aa.isNode(p))p.spaceBefore&&f.push(""),Af(t,f,p.commentBefore,!1),p.comment&&(g=p.comment);else if(aa.isPair(p)){let w=aa.isNode(p.key)?p.key:null;w&&(w.spaceBefore&&f.push(""),Af(t,f,w.commentBefore,!1),w.comment&&(l=!0));let y=aa.isNode(p.value)?p.value:null;y?(y.comment&&(g=y.comment),y.commentBefore&&(l=!0)):p.value==null&&w?.comment&&(g=w.comment)}g&&(l=!0);let v=jS.stringify(p,c,()=>g=null);l||(l=f.length>u||v.includes(`
52
+ `)),h<e.length-1?v+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((w,y)=>w+y.length+2,2)+(v.length+2)>t.options.lineWidth)),l&&(v+=",")),g&&(v+=bf.lineComment(v,n,s(g))),f.push(v),u=f.length}let{start:d,end:m}=r;if(f.length===0)return d+m;if(!l){let h=f.reduce((p,g)=>p+g.length+2,2);l=t.options.lineWidth>0&&h>t.options.lineWidth}if(l){let h=d;for(let p of f)h+=p?`
53
+ ${o}${i}${p}`:`
54
+ `;return`${h}
55
+ ${i}${m}`}else return`${d}${a}${f.join(" ")}${a}${m}`}function Af({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let o=bf.indentComment(t(n),e);r.push(o.trimStart())}}$S.stringifyCollection=sL});var co=D(wv=>{"use strict";var uL=gv(),dL=mv(),fL=cf(),so=Te(),Rf=ao(),pL=Et();function yl(e,t){let r=so.isScalar(t)?t.value:t;for(let n of e)if(so.isPair(n)&&(n.key===t||n.key===r||so.isScalar(n.key)&&n.key.value===r))return n}var vv=class extends fL.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(so.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:o}=n,a=new this(t),s=(c,l)=>{if(typeof o=="function")l=o.call(r,c,l);else if(Array.isArray(o)&&!o.includes(c))return;(l!==void 0||i)&&a.items.push(Rf.createPair(c,l,n))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&a.items.sort(t.sortMapEntries),a}add(t,r){let n;so.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Rf.Pair(t,t?.value):n=new Rf.Pair(t.key,t.value);let i=yl(this.items,n.key),o=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);so.isScalar(i.value)&&pL.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(o){let a=this.items.findIndex(s=>o(n,s)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(t){let r=yl(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=yl(this.items,t)?.value;return(!r&&so.isScalar(i)?i.value:i)??void 0}has(t){return!!yl(this.items,t)}set(t,r){this.add(new Rf.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let o of this.items)dL.addPairToJSMap(r,i,o);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!so.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),uL.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};wv.YAMLMap=vv;wv.findPair=yl});var Rs=D(BS=>{"use strict";var mL=Te(),DS=co(),hL={collection:"map",default:!0,nodeClass:DS.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return mL.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>DS.YAMLMap.from(e,t,r)};BS.map=hL});var lo=D(WS=>{"use strict";var gL=fl(),vL=gv(),wL=cf(),Sf=Te(),yL=Et(),kL=ro(),yv=class extends wL.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Sf.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Nf(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=Nf(t);if(typeof n!="number")return;let i=this.items[n];return!r&&Sf.isScalar(i)?i.value:i}has(t){let r=Nf(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=Nf(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];Sf.isScalar(i)&&yL.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let o of this.items)n.push(kL.toJS(o,String(i++),r));return n}toString(t,r,n){return t?vL.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,o=new this(t);if(r&&Symbol.iterator in Object(r)){let a=0;for(let s of r){if(typeof i=="function"){let c=r instanceof Set?s:String(a++);s=i.call(r,c,s)}o.items.push(gL.createNode(s,void 0,n))}}return o}};function Nf(e){let t=Sf.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}WS.YAMLSeq=yv});var Ns=D(qS=>{"use strict";var bL=Te(),LS=lo(),AL={collection:"seq",default:!0,nodeClass:LS.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return bL.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>LS.YAMLSeq.from(e,t,r)};qS.seq=AL});var kl=D(VS=>{"use strict";var RL=gl(),NL={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),RL.stringifyString(e,t,r,n)}};VS.string=NL});var Ef=D(HS=>{"use strict";var MS=Et(),FS={identify:e=>e==null,createNode:()=>new MS.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new MS.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&FS.test.test(e)?e:t.options.nullStr};HS.nullTag=FS});var kv=D(US=>{"use strict";var SL=Et(),QS={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new SL.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&QS.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};US.boolTag=QS});var Ss=D(JS=>{"use strict";function EL({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let o=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let a=o.indexOf(".");a<0&&(a=o.length,o+=".");let s=t-(o.length-a-1);for(;s-- >0;)o+="0"}return o}JS.stringifyNumber=EL});var Av=D(Cf=>{"use strict";var CL=Et(),bv=Ss(),_L={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:bv.stringifyNumber},IL={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():bv.stringifyNumber(e)}},xL={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new CL.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:bv.stringifyNumber};Cf.float=xL;Cf.floatExp=IL;Cf.floatNaN=_L});var Nv=D(If=>{"use strict";var zS=Ss(),_f=e=>typeof e=="bigint"||Number.isInteger(e),Rv=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function KS(e,t,r){let{value:n}=e;return _f(n)&&n>=0?r+n.toString(t):zS.stringifyNumber(e)}var PL={identify:e=>_f(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Rv(e,2,8,r),stringify:e=>KS(e,8,"0o")},OL={identify:_f,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Rv(e,0,10,r),stringify:zS.stringifyNumber},TL={identify:e=>_f(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Rv(e,2,16,r),stringify:e=>KS(e,16,"0x")};If.int=OL;If.intHex=TL;If.intOct=PL});var YS=D(GS=>{"use strict";var jL=Rs(),$L=Ef(),DL=Ns(),BL=kl(),WL=kv(),Sv=Av(),Ev=Nv(),LL=[jL.map,DL.seq,BL.string,$L.nullTag,WL.boolTag,Ev.intOct,Ev.int,Ev.intHex,Sv.floatNaN,Sv.floatExp,Sv.float];GS.schema=LL});var eE=D(ZS=>{"use strict";var qL=Et(),VL=Rs(),ML=Ns();function XS(e){return typeof e=="bigint"||Number.isInteger(e)}var xf=({value:e})=>JSON.stringify(e),FL=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:xf},{identify:e=>e==null,createNode:()=>new qL.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:xf},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:xf},{identify:XS,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>XS(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:xf}],HL={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},QL=[VL.map,ML.seq].concat(FL,HL);ZS.schema=QL});var _v=D(tE=>{"use strict";var bl=$d("buffer"),Cv=Et(),UL=gl(),JL={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof bl.Buffer=="function")return bl.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},n,i,o){if(!r)return"";let a=r,s;if(typeof bl.Buffer=="function")s=a instanceof bl.Buffer?a.toString("base64"):bl.Buffer.from(a.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<a.length;++l)c+=String.fromCharCode(a[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Cv.Scalar.BLOCK_LITERAL),t!==Cv.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(t===Cv.Scalar.BLOCK_LITERAL?`
56
+ `:" ")}return UL.stringifyString({comment:e,type:t,value:s},n,i,o)}};tE.binary=JL});var Tf=D(Of=>{"use strict";var Pf=Te(),Iv=ao(),zL=Et(),KL=lo();function rE(e,t){if(Pf.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!Pf.isPair(n)){if(Pf.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new Iv.Pair(new zL.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
57
+ ${i.key.commentBefore}`:n.commentBefore),n.comment){let o=i.value??i.key;o.comment=o.comment?`${n.comment}
58
+ ${o.comment}`:n.comment}n=i}e.items[r]=Pf.isPair(n)?n:new Iv.Pair(n)}}else t("Expected a sequence for this tag");return e}function nE(e,t,r){let{replacer:n}=r,i=new KL.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let a of t){typeof n=="function"&&(a=n.call(t,String(o++),a));let s,c;if(Array.isArray(a))if(a.length===2)s=a[0],c=a[1];else throw new TypeError(`Expected [key, value] tuple: ${a}`);else if(a&&a instanceof Object){let l=Object.keys(a);if(l.length===1)s=l[0],c=a[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=a;i.items.push(Iv.createPair(s,c,r))}return i}var GL={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:rE,createNode:nE};Of.createPairs=nE;Of.pairs=GL;Of.resolvePairs=rE});var Ov=D(Pv=>{"use strict";var iE=Te(),xv=ro(),Al=co(),YL=lo(),oE=Tf(),sa=class e extends YL.YAMLSeq{constructor(){super(),this.add=Al.YAMLMap.prototype.add.bind(this),this.delete=Al.YAMLMap.prototype.delete.bind(this),this.get=Al.YAMLMap.prototype.get.bind(this),this.has=Al.YAMLMap.prototype.has.bind(this),this.set=Al.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let o,a;if(iE.isPair(i)?(o=xv.toJS(i.key,"",r),a=xv.toJS(i.value,o,r)):o=xv.toJS(i,"",r),n.has(o))throw new Error("Ordered maps must not include duplicate keys");n.set(o,a)}return n}static from(t,r,n){let i=oE.createPairs(t,r,n),o=new this;return o.items=i.items,o}};sa.tag="tag:yaml.org,2002:omap";var XL={collection:"seq",identify:e=>e instanceof Map,nodeClass:sa,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=oE.resolvePairs(e,t),n=[];for(let{key:i}of r.items)iE.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new sa,r)},createNode:(e,t,r)=>sa.from(e,t,r)};Pv.YAMLOMap=sa;Pv.omap=XL});var uE=D(Tv=>{"use strict";var aE=Et();function sE({value:e,source:t},r){return t&&(e?cE:lE).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var cE={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new aE.Scalar(!0),stringify:sE},lE={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new aE.Scalar(!1),stringify:sE};Tv.falseTag=lE;Tv.trueTag=cE});var dE=D(jf=>{"use strict";var ZL=Et(),jv=Ss(),eq={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:jv.stringifyNumber},tq={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():jv.stringifyNumber(e)}},rq={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new ZL.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:jv.stringifyNumber};jf.float=rq;jf.floatExp=tq;jf.floatNaN=eq});var pE=D(Nl=>{"use strict";var fE=Ss(),Rl=e=>typeof e=="bigint"||Number.isInteger(e);function $f(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let a=BigInt(e);return i==="-"?BigInt(-1)*a:a}let o=parseInt(e,r);return i==="-"?-1*o:o}function $v(e,t,r){let{value:n}=e;if(Rl(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return fE.stringifyNumber(e)}var nq={identify:Rl,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>$f(e,2,2,r),stringify:e=>$v(e,2,"0b")},iq={identify:Rl,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>$f(e,1,8,r),stringify:e=>$v(e,8,"0")},oq={identify:Rl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>$f(e,0,10,r),stringify:fE.stringifyNumber},aq={identify:Rl,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>$f(e,2,16,r),stringify:e=>$v(e,16,"0x")};Nl.int=oq;Nl.intBin=nq;Nl.intHex=aq;Nl.intOct=iq});var Bv=D(Dv=>{"use strict";var Wf=Te(),Df=ao(),Bf=co(),ca=class e extends Bf.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Wf.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Df.Pair(t.key,null):r=new Df.Pair(t,null),Bf.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=Bf.findPair(this.items,t);return!r&&Wf.isPair(n)?Wf.isScalar(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=Bf.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new Df.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,o=new this(t);if(r&&Symbol.iterator in Object(r))for(let a of r)typeof i=="function"&&(a=i.call(r,a,a)),o.items.push(Df.createPair(a,null,n));return o}};ca.tag="tag:yaml.org,2002:set";var sq={collection:"map",identify:e=>e instanceof Set,nodeClass:ca,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>ca.from(e,t,r),resolve(e,t){if(Wf.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ca,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Dv.YAMLSet=ca;Dv.set=sq});var Lv=D(Lf=>{"use strict";var cq=Ss();function Wv(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=a=>t?BigInt(a):Number(a),o=n.replace(/_/g,"").split(":").reduce((a,s)=>a*i(60)+i(s),i(0));return r==="-"?i(-1)*o:o}function mE(e){let{value:t}=e,r=a=>a;if(typeof t=="bigint")r=a=>BigInt(a);else if(isNaN(t)||!isFinite(t))return cq.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),o=[t%i];return t<60?o.unshift(0):(t=(t-o[0])/i,o.unshift(t%i),t>=60&&(t=(t-o[0])/i,o.unshift(t))),n+o.map(a=>String(a).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var lq={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Wv(e,r),stringify:mE},uq={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Wv(e,!1),stringify:mE},hE={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(hE.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,o,a,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,o||0,a||0,s||0,c),u=t[8];if(u&&u!=="Z"){let f=Wv(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Lf.floatTime=uq;Lf.intTime=lq;Lf.timestamp=hE});var wE=D(vE=>{"use strict";var dq=Rs(),fq=Ef(),pq=Ns(),mq=kl(),hq=_v(),gE=uE(),qv=dE(),qf=pE(),gq=wf(),vq=Ov(),wq=Tf(),yq=Bv(),Vv=Lv(),kq=[dq.map,pq.seq,mq.string,fq.nullTag,gE.trueTag,gE.falseTag,qf.intBin,qf.intOct,qf.int,qf.intHex,qv.floatNaN,qv.floatExp,qv.float,hq.binary,gq.merge,vq.omap,wq.pairs,yq.set,Vv.intTime,Vv.floatTime,Vv.timestamp];vE.schema=kq});var _E=D(Hv=>{"use strict";var AE=Rs(),bq=Ef(),RE=Ns(),Aq=kl(),Rq=kv(),Mv=Av(),Fv=Nv(),Nq=YS(),Sq=eE(),NE=_v(),Sl=wf(),SE=Ov(),EE=Tf(),yE=wE(),CE=Bv(),Vf=Lv(),kE=new Map([["core",Nq.schema],["failsafe",[AE.map,RE.seq,Aq.string]],["json",Sq.schema],["yaml11",yE.schema],["yaml-1.1",yE.schema]]),bE={binary:NE.binary,bool:Rq.boolTag,float:Mv.float,floatExp:Mv.floatExp,floatNaN:Mv.floatNaN,floatTime:Vf.floatTime,int:Fv.int,intHex:Fv.intHex,intOct:Fv.intOct,intTime:Vf.intTime,map:AE.map,merge:Sl.merge,null:bq.nullTag,omap:SE.omap,pairs:EE.pairs,seq:RE.seq,set:CE.set,timestamp:Vf.timestamp},Eq={"tag:yaml.org,2002:binary":NE.binary,"tag:yaml.org,2002:merge":Sl.merge,"tag:yaml.org,2002:omap":SE.omap,"tag:yaml.org,2002:pairs":EE.pairs,"tag:yaml.org,2002:set":CE.set,"tag:yaml.org,2002:timestamp":Vf.timestamp};function Cq(e,t,r){let n=kE.get(t);if(n&&!e)return r&&!n.includes(Sl.merge)?n.concat(Sl.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let o=Array.from(kE.keys()).filter(a=>a!=="yaml11").map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)i=i.concat(o);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(Sl.merge)),i.reduce((o,a)=>{let s=typeof a=="string"?bE[a]:a;if(!s){let c=JSON.stringify(a),l=Object.keys(bE).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return o.includes(s)||o.push(s),o},[])}Hv.coreKnownTags=Eq;Hv.getTags=Cq});var Jv=D(IE=>{"use strict";var Qv=Te(),_q=Rs(),Iq=Ns(),xq=kl(),Mf=_E(),Pq=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Uv=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:o,sortMapEntries:a,toStringDefaults:s}){this.compat=Array.isArray(t)?Mf.getTags(t,"compat"):t?Mf.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?Mf.coreKnownTags:{},this.tags=Mf.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Qv.MAP,{value:_q.map}),Object.defineProperty(this,Qv.SCALAR,{value:xq.string}),Object.defineProperty(this,Qv.SEQ,{value:Iq.seq}),this.sortMapEntries=typeof a=="function"?a:a===!0?Pq:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};IE.Schema=Uv});var PE=D(xE=>{"use strict";var Oq=Te(),zv=vl(),El=pl();function Tq(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=zv.createStringifyContext(e,t),{commentString:o}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=o(e.commentBefore);r.unshift(El.indentComment(c,""))}let a=!1,s=null;if(e.contents){if(Oq.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let u=o(e.contents.commentBefore);r.push(El.indentComment(u,""))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>a=!0,l=zv.stringify(e.contents,i,()=>s=null,c);s&&(l+=El.lineComment(l,"",o(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(zv.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=o(e.comment);c.includes(`
59
+ `)?(r.push("..."),r.push(El.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&a&&(c=c.replace(/^\n+/,"")),c&&((!a||s)&&r[r.length-1]!==""&&r.push(""),r.push(El.indentComment(o(c),"")))}return r.join(`
60
+ `)+`
61
+ `}xE.stringifyDocument=Tq});var Cl=D(OE=>{"use strict";var jq=dl(),Es=cf(),ln=Te(),$q=ao(),Dq=ro(),Bq=Jv(),Wq=PE(),Kv=nf(),Lq=Zg(),qq=fl(),Gv=Xg(),Yv=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ln.NODE_TYPE,{value:ln.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=o;let{version:a}=o;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new Gv.Directives({version:a}),this.setSchema(a,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[ln.NODE_TYPE]:{value:ln.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=ln.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Cs(this.contents)&&this.contents.add(t)}addIn(t,r){Cs(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=Kv.anchorNames(this);t.anchor=!r||n.has(r)?Kv.findNewAnchor(r||"a",n):r}return new jq.Alias(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let g=w=>typeof w=="number"||w instanceof String||w instanceof Number,v=r.filter(g).map(String);v.length>0&&(r=r.concat(v)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:o,anchorPrefix:a,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:f,setAnchors:d,sourceObjects:m}=Kv.createNodeAnchors(this,a||"a"),h={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:m},p=qq.createNode(t,u,h);return s&&ln.isCollection(p)&&(p.flow=!0),d(),p}createPair(t,r,n={}){let i=this.createNode(t,null,n),o=this.createNode(r,null,n);return new $q.Pair(i,o)}delete(t){return Cs(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Es.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Cs(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return ln.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Es.isEmptyPath(t)?!r&&ln.isScalar(this.contents)?this.contents.value:this.contents:ln.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return ln.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Es.isEmptyPath(t)?this.contents!==void 0:ln.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Es.collectionFromPath(this.schema,[t],r):Cs(this.contents)&&this.contents.set(t,r)}setIn(t,r){Es.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Es.collectionFromPath(this.schema,Array.from(t),r):Cs(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Gv.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Gv.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new Bq.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:o,reviver:a}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Dq.toJS(this.contents,r??"",s);if(typeof o=="function")for(let{count:l,res:u}of s.anchors.values())o(u,l);return typeof a=="function"?Lq.applyReviver(a,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Wq.stringifyDocument(this,t)}};function Cs(e){if(ln.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}OE.Document=Yv});var xl=D(Il=>{"use strict";var _l=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},Xv=class extends _l{constructor(t,r,n){super("YAMLParseError",t,r,n)}},Zv=class extends _l{constructor(t,r,n){super("YAMLWarning",t,r,n)}},Vq=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let o=i-1,a=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(o>=60&&a.length>80){let s=Math.min(o-39,a.length-79);a="…"+a.substring(s),o-=s-1}if(a.length>80&&(a=a.substring(0,79)+"…"),n>1&&/^ *$/.test(a.substring(0,o))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
62
+ `),a=s+a}if(/[^ ]/.test(a)){let s=1,c=r.linePos[1];c?.line===n&&c.col>i&&(s=Math.max(1,Math.min(c.col-i,80-o)));let l=" ".repeat(o)+"^".repeat(s);r.message+=`:
63
+
64
+ ${a}
65
+ ${l}
66
+ `}};Il.YAMLError=_l;Il.YAMLParseError=Xv;Il.YAMLWarning=Zv;Il.prettifyError=Vq});var Pl=D(TE=>{"use strict";function Mq(e,{flow:t,indicator:r,next:n,offset:i,onError:o,parentIndent:a,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",m=!1,h=!1,p=null,g=null,v=null,w=null,y=null,b=null,N=null;for(let _ of e)switch(h&&(_.type!=="space"&&_.type!=="newline"&&_.type!=="comma"&&o(_.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),p&&(l&&_.type!=="comment"&&_.type!=="newline"&&o(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),_.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&_.source.includes(" ")&&(p=_),u=!0;break;case"comment":{u||o(_,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let Q=_.source.substring(1)||" ";f?f+=d+Q:f=Q,d="",l=!1;break}case"newline":l?f?f+=_.source:(!b||r!=="seq-item-ind")&&(c=!0):d+=_.source,l=!0,m=!0,(g||v)&&(w=_),u=!0;break;case"anchor":g&&o(_,"MULTIPLE_ANCHORS","A node can have at most one anchor"),_.source.endsWith(":")&&o(_.offset+_.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=_,N??(N=_.offset),l=!1,u=!1,h=!0;break;case"tag":{v&&o(_,"MULTIPLE_TAGS","A node can have at most one tag"),v=_,N??(N=_.offset),l=!1,u=!1,h=!0;break}case r:(g||v)&&o(_,"BAD_PROP_ORDER",`Anchors and tags must be after the ${_.source} indicator`),b&&o(_,"UNEXPECTED_TOKEN",`Unexpected ${_.source} in ${t??"collection"}`),b=_,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){y&&o(_,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=_,l=!1,u=!1;break}default:o(_,"UNEXPECTED_TOKEN",`Unexpected ${_.type} token`),l=!1,u=!1}let A=e[e.length-1],S=A?A.offset+A.source.length:i;return h&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&o(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=a||n?.type==="block-map"||n?.type==="block-seq")&&o(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:b,spaceBefore:c,comment:f,hasNewline:m,anchor:g,tag:v,newlineAfterProp:w,end:S,start:N??S}}TE.resolveProps=Mq});var Ff=D(jE=>{"use strict";function ew(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
67
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(ew(t.key)||ew(t.value))return!0}return!1;default:return!0}}jE.containsNewline=ew});var tw=D($E=>{"use strict";var Fq=Ff();function Hq(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&Fq.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}$E.flowIndentCheck=Hq});var rw=D(BE=>{"use strict";var DE=Te();function Qq(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(o,a)=>o===a||DE.isScalar(o)&&DE.isScalar(a)&&o.value===a.value;return t.some(o=>i(o.key,r))}BE.mapIncludes=Qq});var FE=D(ME=>{"use strict";var WE=ao(),Uq=co(),LE=Pl(),Jq=Ff(),qE=tw(),zq=rw(),VE="All mapping items must start at the same column";function Kq({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??Uq.YAMLMap,s=new a(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:f,key:d,sep:m,value:h}=u,p=LE.resolveProps(f,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!p.found;if(g){if(d&&(d.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&i(c,"BAD_INDENT",VE)),!p.anchor&&!p.tag&&!m){l=p.end,p.comment&&(s.comment?s.comment+=`
68
+ `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||Jq.containsNewline(d))&&i(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&i(c,"BAD_INDENT",VE);r.atKey=!0;let v=p.end,w=d?e(r,d,p,i):t(r,v,f,null,p,i);r.schema.compat&&qE.flowIndentCheck(n.indent,d,i),r.atKey=!1,zq.mapIncludes(r,s.items,w)&&i(v,"DUPLICATE_KEY","Map keys must be unique");let y=LE.resolveProps(m??[],{indicator:"map-value-ind",next:h,offset:w.range[2],onError:i,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){g&&(h?.type==="block-map"&&!y.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<y.found.offset-1024&&i(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=h?e(r,h,y,i):t(r,c,m,null,y,i);r.schema.compat&&qE.flowIndentCheck(n.indent,h,i),c=b.range[2];let N=new WE.Pair(w,b);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}else{g&&i(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(w.comment?w.comment+=`
69
+ `+y.comment:w.comment=y.comment);let b=new WE.Pair(w);r.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}ME.resolveBlockMap=Kq});var QE=D(HE=>{"use strict";var Gq=lo(),Yq=Pl(),Xq=tw();function Zq({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??Gq.YAMLSeq,s=new a(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:f}of n.items){let d=Yq.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?i(d.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let m=f?e(r,f,d,i):t(r,d.end,u,null,d,i);r.schema.compat&&Xq.flowIndentCheck(n.indent,f,i),c=m.range[2],s.items.push(m)}return s.range=[n.offset,c,l??c],s}HE.resolveBlockSeq=Zq});var _s=D(UE=>{"use strict";function eV(e,t,r,n){let i="";if(e){let o=!1,a="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":o=!0;break;case"comment":{r&&!o&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";i?i+=a+u:i=u,a="";break}case"newline":i&&(a+=c),o=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:i,offset:t}}UE.resolveEnd=eV});var GE=D(KE=>{"use strict";var tV=Te(),rV=ao(),JE=co(),nV=lo(),iV=_s(),zE=Pl(),oV=Ff(),aV=rw(),nw="Block collections are not allowed within flow collections",iw=e=>e&&(e.type==="block-map"||e.type==="block-seq");function sV({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=n.start.source==="{",s=a?"flow map":"flow sequence",c=o?.nodeClass??(a?JE.YAMLMap:nV.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let f=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let v=n.items[g],{start:w,key:y,sep:b,value:N}=v,A=zE.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:y??b?.[0],offset:f,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!b&&!N){g===0&&A.comma?i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<n.items.length-1&&i(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),A.comment&&(l.comment?l.comment+=`
70
+ `+A.comment:l.comment=A.comment),f=A.end;continue}!a&&r.options.strict&&oV.containsNewline(y)&&i(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)A.comma&&i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(A.comma||i(A.start,"MISSING_CHAR",`Missing , between ${s} items`),A.comment){let S="";e:for(let _ of w)switch(_.type){case"comma":case"space":break;case"comment":S=_.source.substring(1);break e;default:break e}if(S){let _=l.items[l.items.length-1];tV.isPair(_)&&(_=_.value??_.key),_.comment?_.comment+=`
71
+ `+S:_.comment=S,A.comment=A.comment.substring(S.length+1)}}if(!a&&!b&&!A.found){let S=N?e(r,N,A,i):t(r,A.end,b,null,A,i);l.items.push(S),f=S.range[2],iw(N)&&i(S.range,"BLOCK_IN_FLOW",nw)}else{r.atKey=!0;let S=A.end,_=y?e(r,y,A,i):t(r,S,w,null,A,i);iw(y)&&i(_.range,"BLOCK_IN_FLOW",nw),r.atKey=!1;let Q=zE.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:N,offset:_.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(Q.found){if(!a&&!A.found&&r.options.strict){if(b)for(let Z of b){if(Z===Q.found)break;if(Z.type==="newline"){i(Z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}A.start<Q.found.offset-1024&&i(Q.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?i(N,"MISSING_CHAR",`Missing space after : in ${s}`):i(Q.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let F=N?e(r,N,Q,i):Q.found?t(r,Q.end,b,null,Q,i):null;F?iw(N)&&i(F.range,"BLOCK_IN_FLOW",nw):Q.comment&&(_.comment?_.comment+=`
72
+ `+Q.comment:_.comment=Q.comment);let K=new rV.Pair(_,F);if(r.options.keepSourceTokens&&(K.srcToken=v),a){let Z=l;aV.mapIncludes(r,Z.items,_)&&i(S,"DUPLICATE_KEY","Map keys must be unique"),Z.items.push(K)}else{let Z=new JE.YAMLMap(r.schema);Z.flow=!0,Z.items.push(K);let re=(F??_).range;Z.range=[_.range[0],re[1],re[2]],l.items.push(Z)}f=F?F.range[2]:Q.end}}let d=a?"}":"]",[m,...h]=n.end,p=f;if(m?.source===d)p=m.offset+m.source.length;else{let g=s[0].toUpperCase()+s.substring(1),v=u?`${g} must end with a ${d}`:`${g} in block collection must be sufficiently indented and end with a ${d}`;i(f,u?"MISSING_CHAR":"BAD_INDENT",v),m&&m.source.length!==1&&h.unshift(m)}if(h.length>0){let g=iV.resolveEnd(h,p,r.options.strict,i);g.comment&&(l.comment?l.comment+=`
73
+ `+g.comment:l.comment=g.comment),l.range=[n.offset,p,g.offset]}else l.range=[n.offset,p,p];return l}KE.resolveFlowCollection=sV});var XE=D(YE=>{"use strict";var cV=Te(),lV=Et(),uV=co(),dV=lo(),fV=FE(),pV=QE(),mV=GE();function ow(e,t,r,n,i,o){let a=r.type==="block-map"?fV.resolveBlockMap(e,t,r,n,o):r.type==="block-seq"?pV.resolveBlockSeq(e,t,r,n,o):mV.resolveFlowCollection(e,t,r,n,o),s=a.constructor;return i==="!"||i===s.tagName?(a.tag=s.tagName,a):(i&&(a.tag=i),a)}function hV(e,t,r,n,i){let o=n.tag,a=o?t.directives.tagName(o.source,d=>i(o,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=n,h=d&&o?d.offset>o.offset?d:o:d??o;h&&(!m||m.offset<h.offset)&&i(h,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!o||!a||a==="!"||a===uV.YAMLMap.tagName&&s==="map"||a===dV.YAMLSeq.tagName&&s==="seq")return ow(e,t,r,i,a);let c=t.schema.tags.find(d=>d.tag===a&&d.collection===s);if(!c){let d=t.schema.knownTags[a];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?i(o,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):i(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${a}`,!0),ow(e,t,r,i,a)}let l=ow(e,t,r,i,a,c),u=c.resolve?.(l,d=>i(o,"TAG_RESOLVE_FAILED",d),t.options)??l,f=cV.isNode(u)?u:new lV.Scalar(u);return f.range=l.range,f.tag=a,c?.format&&(f.format=c.format),f}YE.composeCollection=hV});var sw=D(ZE=>{"use strict";var aw=Et();function gV(e,t,r){let n=t.offset,i=vV(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let o=i.mode===">"?aw.Scalar.BLOCK_FOLDED:aw.Scalar.BLOCK_LITERAL,a=t.source?wV(t.source):[],s=a.length;for(let p=a.length-1;p>=0;--p){let g=a[p][1];if(g===""||g==="\r")s=p;else break}if(s===0){let p=i.chomp==="+"&&a.length>0?`
74
+ `.repeat(Math.max(1,a.length-1)):"",g=n+i.length;return t.source&&(g+=t.source.length),{value:p,type:o,comment:i.comment,range:[n,g,g]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let p=0;p<s;++p){let[g,v]=a[p];if(v===""||v==="\r")i.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&r(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=g.length),u=p,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+v.length+1}for(let p=a.length-1;p>=s;--p)a[p][0].length>c&&(s=p+1);let f="",d="",m=!1;for(let p=0;p<u;++p)f+=a[p][0].slice(c)+`
75
+ `;for(let p=u;p<s;++p){let[g,v]=a[p];l+=g.length+v.length+1;let w=v[v.length-1]==="\r";if(w&&(v=v.slice(0,-1)),v&&g.length<c){let b=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-v.length-(w?2:1),"BAD_INDENT",b),g=""}o===aw.Scalar.BLOCK_LITERAL?(f+=d+g.slice(c)+v,d=`
76
+ `):g.length>c||v[0]===" "?(d===" "?d=`
77
+ `:!m&&d===`
78
+ `&&(d=`
79
+
80
+ `),f+=d+g.slice(c)+v,d=`
81
+ `,m=!0):v===""?d===`
82
+ `?f+=`
83
+ `:d=`
84
+ `:(f+=d+v,d=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let p=s;p<a.length;++p)f+=`
85
+ `+a[p][0].slice(c);f[f.length-1]!==`
86
+ `&&(f+=`
87
+ `);break;default:f+=`
88
+ `}let h=n+i.length+t.source.length;return{value:f,type:o,comment:i.comment,range:[n,h,h]}}function vV({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],o=i[0],a=0,s="",c=-1;for(let d=1;d<i.length;++d){let m=i[d];if(!s&&(m==="-"||m==="+"))s=m;else{let h=Number(m);!a&&h?a=h:c===-1&&(c=e+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",f=i.length;for(let d=1;d<t.length;++d){let m=t[d];switch(m.type){case"space":l=!0;case"newline":f+=m.source.length;break;case"comment":r&&!l&&n(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,u=m.source.substring(1);break;case"error":n(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{let h=`Unexpected token in block scalar header: ${m.type}`;n(m,"UNEXPECTED_TOKEN",h);let p=m.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:o,indent:a,chomp:s,comment:u,length:f}}function wV(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),o=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let a=1;a<t.length;a+=2)o.push([t[a],t[a+1]]);return o}ZE.resolveBlockScalar=gV});var lw=D(tC=>{"use strict";var cw=Et(),yV=_s();function kV(e,t,r){let{offset:n,type:i,source:o,end:a}=e,s,c,l=(d,m,h)=>r(n+d,m,h);switch(i){case"scalar":s=cw.Scalar.PLAIN,c=bV(o,l);break;case"single-quoted-scalar":s=cw.Scalar.QUOTE_SINGLE,c=AV(o,l);break;case"double-quoted-scalar":s=cw.Scalar.QUOTE_DOUBLE,c=RV(o,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+o.length,n+o.length]}}let u=n+o.length,f=yV.resolveEnd(a,u,t,r);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function bV(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),eC(e)}function AV(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),eC(e.slice(1,-1)).replace(/''/g,"'")}function eC(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
+ `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
90
+ `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],o=" ",a=t.lastIndex;for(r.lastIndex=a;n=r.exec(e);)n[1]===""?o===`
91
+ `?i+=o:o=`
92
+ `:(i+=o+n[1],o=" "),a=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=a,n=s.exec(e),i+o+(n?.[1]??"")}function RV(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
93
+ `))if(i===`
94
+ `){let{fold:o,offset:a}=NV(e,n);r+=o,n=a}else if(i==="\\"){let o=e[++n],a=SV[o];if(a)r+=a;else if(o===`
95
+ `)for(o=e[n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="\r"&&e[n+1]===`
96
+ `)for(o=e[++n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="x"||o==="u"||o==="U"){let s=o==="x"?2:o==="u"?4:8;r+=EV(e,n+1,s,t),n+=s}else{let s=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(i===" "||i===" "){let o=n,a=e[n+1];for(;a===" "||a===" ";)a=e[++n+1];a!==`
97
+ `&&!(a==="\r"&&e[n+2]===`
98
+ `)&&(r+=n>o?e.slice(o,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function NV(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
99
+ `||n==="\r")&&!(n==="\r"&&e[t+2]!==`
100
+ `);)n===`
101
+ `&&(r+=`
102
+ `),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var SV={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function EV(e,t,r,n){let i=e.substr(t,r),a=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let s=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}tC.resolveFlowScalar=kV});var iC=D(nC=>{"use strict";var la=Te(),rC=Et(),CV=sw(),_V=lw();function IV(e,t,r,n){let{value:i,type:o,comment:a,range:s}=t.type==="block-scalar"?CV.resolveBlockScalar(e,t,n):_V.resolveFlowScalar(t,e.options.strict,n),c=r?e.directives.tagName(r.source,f=>n(r,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[la.SCALAR]:c?l=xV(e.schema,i,c,r,n):t.type==="scalar"?l=PV(e,i,t,n):l=e.schema[la.SCALAR];let u;try{let f=l.resolve(i,d=>n(r??t,"TAG_RESOLVE_FAILED",d),e.options);u=la.isScalar(f)?f:new rC.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(r??t,"TAG_RESOLVE_FAILED",d),u=new rC.Scalar(i)}return u.range=s,u.source=i,o&&(u.type=o),c&&(u.tag=c),l.format&&(u.format=l.format),a&&(u.comment=a),u}function xV(e,t,r,n,i){if(r==="!")return e[la.SCALAR];let o=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)o.push(s);else return s;for(let s of o)if(s.test?.test(t))return s;let a=e.knownTags[r];return a&&!a.collection?(e.tags.push(Object.assign({},a,{default:!1,test:void 0})),a):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[la.SCALAR])}function PV({atKey:e,directives:t,schema:r},n,i,o){let a=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||r[la.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[la.SCALAR];if(a.tag!==s.tag){let c=t.tagString(a.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;o(i,"TAG_RESOLVE_FAILED",u,!0)}}return a}nC.composeScalar=IV});var aC=D(oC=>{"use strict";function OV(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}oC.emptyScalarPosition=OV});var lC=D(dw=>{"use strict";var TV=dl(),jV=Te(),$V=XE(),sC=iC(),DV=_s(),BV=aC(),WV={composeNode:cC,composeEmptyNode:uw};function cC(e,t,r,n){let i=e.atKey,{spaceBefore:o,comment:a,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=LV(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=sC.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=$V.composeCollection(WV,e,t,r,n),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);n(t,"RESOURCE_EXHAUSTION",d)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=uw(e,t.offset,void 0,null,r,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!jV.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),a&&(t.type==="scalar"&&t.source===""?l.comment=a:l.commentBefore=a),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function uw(e,t,r,n,{spaceBefore:i,comment:o,anchor:a,tag:s,end:c},l){let u={type:"scalar",offset:BV.emptyScalarPosition(t,r,n),indent:-1,source:""},f=sC.composeScalar(e,u,s,l);return a&&(f.anchor=a.source.substring(1),f.anchor===""&&l(a,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(f.spaceBefore=!0),o&&(f.comment=o,f.range[2]=c),f}function LV({options:e},{offset:t,source:r,end:n},i){let o=new TV.Alias(r.substring(1));o.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let a=t+r.length,s=DV.resolveEnd(n,a,e.strict,i);return o.range=[t,a,s.offset],s.comment&&(o.comment=s.comment),o}dw.composeEmptyNode=uw;dw.composeNode=cC});var fC=D(dC=>{"use strict";var qV=Cl(),uC=lC(),VV=_s(),MV=Pl();function FV(e,t,{offset:r,start:n,value:i,end:o},a){let s=Object.assign({_directives:t},e),c=new qV.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=MV.resolveProps(n,{indicator:"doc-start",next:i??o?.[0],offset:r,onError:a,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&a(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?uC.composeNode(l,i,u,a):uC.composeEmptyNode(l,u.end,n,null,u,a);let f=c.contents.range[2],d=VV.resolveEnd(o,f,!1,a);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}dC.composeDoc=FV});var pw=D(hC=>{"use strict";var HV=$d("process"),QV=Xg(),UV=Cl(),Ol=xl(),pC=Te(),JV=fC(),zV=_s();function Tl(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function mC(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let o=e[i];switch(o[0]){case"#":t+=(t===""?"":n?`
104
+
105
+ `:`
106
+ `)+(o.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var fw=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,o)=>{let a=Tl(r);o?this.warnings.push(new Ol.YAMLWarning(a,n,i)):this.errors.push(new Ol.YAMLParseError(a,n,i))},this.directives=new QV.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=mC(this.prelude);if(n){let o=t.contents;if(r)t.comment=t.comment?`${t.comment}
107
+ ${n}`:n;else if(i||t.directives.docStart||!o)t.commentBefore=n;else if(pC.isCollection(o)&&!o.flow&&o.items.length>0){let a=o.items[0];pC.isPair(a)&&(a=a.key);let s=a.commentBefore;a.commentBefore=s?`${n}
108
+ ${s}`:n}else{let a=o.commentBefore;o.commentBefore=a?`${n}
109
+ ${a}`:n}}if(r){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:mC(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(HV.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let o=Tl(t);o[0]+=r,this.onError(o,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=JV.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new Ol.YAMLParseError(Tl(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Ol.YAMLParseError(Tl(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=zV.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
110
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Ol.YAMLParseError(Tl(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),i=new UV.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};hC.Composer=fw});var wC=D(Hf=>{"use strict";var KV=sw(),GV=lw(),YV=xl(),gC=gl();function XV(e,t=!0,r){if(e){let n=(i,o,a)=>{let s=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(s,o,a);else throw new YV.YAMLParseError([s,s+1],o,a)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return GV.resolveFlowScalar(e,t,n);case"block-scalar":return KV.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function ZV(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:o=-1,type:a="PLAIN"}=t,s=gC.stringifyString({type:a,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
111
+ `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
112
+ `),u=s.substring(0,l),f=s.substring(l+1)+`
113
+ `,d=[{type:"block-scalar-header",offset:o,indent:n,source:u}];return vC(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
114
+ `}),{type:"block-scalar",offset:o,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:o,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:n,source:s,end:c};default:return{type:"scalar",offset:o,indent:n,source:s,end:c}}}function eM(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:o=!1,type:a}=r,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!a)switch(e.type){case"single-quoted-scalar":a="QUOTE_SINGLE";break;case"double-quoted-scalar":a="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}let c=gC.stringifyString({type:a,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":tM(e,c);break;case'"':mw(e,c,"double-quoted-scalar");break;case"'":mw(e,c,"single-quoted-scalar");break;default:mw(e,c,"scalar")}}function tM(e,t){let r=t.indexOf(`
115
+ `),n=t.substring(0,r),i=t.substring(r+1)+`
116
+ `;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=n,e.source=i}else{let{offset:o}=e,a="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:o,indent:a,source:n}];vC(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:a,source:`
117
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:a,props:s,source:i})}}function vC(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function mw(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let o of n)o.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
118
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}Hf.createScalarToken=ZV;Hf.resolveAsScalar=XV;Hf.setScalarValue=eM});var kC=D(yC=>{"use strict";var rM=e=>"type"in e?Uf(e):Qf(e);function Uf(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Uf(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Qf(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Qf(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Qf(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Qf({start:e,key:t,sep:r,value:n}){let i="";for(let o of e)i+=o.source;if(t&&(i+=Uf(t)),r)for(let o of r)i+=o.source;return n&&(i+=Uf(n)),i}yC.stringify=rM});var NC=D(RC=>{"use strict";var hw=Symbol("break visit"),nM=Symbol("skip children"),bC=Symbol("remove item");function ua(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),AC(Object.freeze([]),e,t)}ua.BREAK=hw;ua.SKIP=nM;ua.REMOVE=bC;ua.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let o=r?.[n];if(o&&"items"in o)r=o.items[i];else return}return r};ua.parentCollection=(e,t)=>{let r=ua.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function AC(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let o=t[i];if(o&&"items"in o){for(let a=0;a<o.items.length;++a){let s=AC(Object.freeze(e.concat([[i,a]])),o.items[a],r);if(typeof s=="number")a=s-1;else{if(s===hw)return hw;s===bC&&(o.items.splice(a,1),a-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}RC.visit=ua});var Jf=D(Tr=>{"use strict";var gw=wC(),iM=kC(),oM=NC(),vw="\uFEFF",ww="",yw="",kw="",aM=e=>!!e&&"items"in e,sM=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function cM(e){switch(e){case vw:return"<BOM>";case ww:return"<DOC>";case yw:return"<FLOW_END>";case kw:return"<SCALAR>";default:return JSON.stringify(e)}}function lM(e){switch(e){case vw:return"byte-order-mark";case ww:return"doc-mode";case yw:return"flow-error-end";case kw:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
119
+ `:case`\r
120
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Tr.createScalarToken=gw.createScalarToken;Tr.resolveAsScalar=gw.resolveAsScalar;Tr.setScalarValue=gw.setScalarValue;Tr.stringify=iM.stringify;Tr.visit=oM.visit;Tr.BOM=vw;Tr.DOCUMENT=ww;Tr.FLOW_END=yw;Tr.SCALAR=kw;Tr.isCollection=aM;Tr.isScalar=sM;Tr.prettyToken=cM;Tr.tokenType=lM});var Rw=D(EC=>{"use strict";var jl=Jf();function jn(e){switch(e){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var SC=new Set("0123456789ABCDEFabcdef"),uM=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),zf=new Set(",[]{}"),dM=new Set(` ,[]{}
122
+ \r `),bw=e=>!e||dM.has(e),Aw=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
123
+ `?!0:r==="\r"?this.buffer[t+1]===`
124
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
125
+ `||!i&&!this.atEnd)return t+n+1}return r===`
126
+ `||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&jn(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===jl.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let o=t[n-1];if(o===" "||o===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let o=t[r-1];if(o===" "||o===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield jl.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&jn(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!jn(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&jn(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(bw),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&jn(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield jl.FLOW_END,yield*this.parseLineStart();let o=0;for(;i[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),i[o]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(bw),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let a=this.charAt(1);if(this.flowKey||jn(a)||a===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let o=0;for(;this.buffer[r-1-o]==="\\";)o+=1;if(o%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
128
+ `,this.pos);if(i!==-1){for(;i!==-1;){let o=this.continueScalar(i+1);if(o===-1)break;i=n.indexOf(`
129
+ `,o)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>jn(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let o=this.pos;n=this.buffer[o];++o)switch(n){case" ":r+=1;break;case`
130
+ `:t=o,r=0;break;case"\r":{let a=this.buffer[o+1];if(!a&&!this.atEnd)return this.setNext("block-scalar");if(a===`
131
+ `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
132
+ `,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
133
+ `;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let o=t-1,a=this.buffer[o];a==="\r"&&(a=this.buffer[--o]);let s=o;for(;a===" ";)a=this.buffer[--o];if(a===`
134
+ `&&o>=this.pos&&o+1+r>s)t=o;else break}while(!0);return yield jl.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let o=this.buffer[n+1];if(jn(o)||t&&zf.has(o))break;r=n}else if(jn(i)){let o=this.buffer[n+1];if(i==="\r"&&(o===`
135
+ `?(n+=1,i=`
136
+ `,o=this.buffer[n+1]):r=n),o==="#"||t&&zf.has(o))break;if(i===`
137
+ `){let a=this.continueScalar(n+1);if(a===-1)break;n=Math.max(n,a-2)}}else{if(t&&zf.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield jl.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(bw),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(jn(n)||r&&zf.has(n)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!jn(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(uM.has(r))r=this.buffer[++t];else if(r==="%"&&SC.has(this.buffer[t+1])&&SC.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
138
+ `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
139
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};EC.Lexer=Aw});var Sw=D(CC=>{"use strict";var Nw=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let o=r+n>>1;this.lineStarts[o]<t?r=o+1:n=o}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};CC.LineCounter=Nw});var Cw=D(OC=>{"use strict";var fM=$d("process"),_C=Jf(),pM=Rw();function uo(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function IC(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function PC(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Kf(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Is(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Gf(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function xC(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!uo(t.start,"explicit-key-ind")&&!uo(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,PC(t.value)?t.value.end?Gf(t.value.end,t.sep):t.value.end=t.sep:Gf(t.start,t.sep),delete t.sep)}var Ew=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new pM.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,fM.env.LOG_TOKENS&&console.log("|",_C.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=_C.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&xC(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&IC(i.start)===-1&&(r.indent===0||i.start.every(o=>o.type!=="comment"||o.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{IC(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Kf(this.peek(2)),n=Is(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
140
+ `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
141
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Gf(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&r.sep&&!r.value){let a=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":a.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=r.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(o.push(this.sourceToken),t.items.push({start:o}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.value?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(uo(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(PC(r.key)&&!uo(r.sep,"newline")){let a=Is(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:s,sep:c}]})}else o.length>0?r.sep=r.sep.concat(o,this.sourceToken):r.sep.push(this.sourceToken);else if(uo(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let a=Is(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:o,key:null,sep:[this.sourceToken]}):uo(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);i||r.value?(t.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(a):(Object.assign(r,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(t);if(a){if(a.type==="block-seq"){if(!r.explicitKey&&r.sep&&!uo(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Gf(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||uo(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=Kf(n),o=Is(i);xC(t);let a=t.end.splice(1,t.end.length);a.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:a}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
142
+ `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
143
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Kf(t),n=Is(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Kf(t),n=Is(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};OC.Parser=Ew});var BC=D(Dl=>{"use strict";var TC=pw(),mM=Cl(),$l=xl(),hM=dv(),gM=Te(),vM=Sw(),jC=Cw();function $C(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new vM.LineCounter||null,prettyErrors:t}}function wM(e,t={}){let{lineCounter:r,prettyErrors:n}=$C(t),i=new jC.Parser(r?.addNewLine),o=new TC.Composer(t),a=Array.from(o.compose(i.parse(e)));if(n&&r)for(let s of a)s.errors.forEach($l.prettifyError(e,r)),s.warnings.forEach($l.prettifyError(e,r));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function DC(e,t={}){let{lineCounter:r,prettyErrors:n}=$C(t),i=new jC.Parser(r?.addNewLine),o=new TC.Composer(t),a=null;for(let s of o.compose(i.parse(e),!0,e.length))if(!a)a=s;else if(a.options.logLevel!=="silent"){a.errors.push(new $l.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(a.errors.forEach($l.prettifyError(e,r)),a.warnings.forEach($l.prettifyError(e,r))),a}function yM(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=DC(e,r);if(!i)return null;if(i.warnings.forEach(o=>hM.warn(i.options.logLevel,o)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function kM(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=r??t??{};if(!i)return}return gM.isDocument(e)&&!n?e.toString(r):new mM.Document(e,n,r).toString(r)}Dl.parse=yM;Dl.parseAllDocuments=wM;Dl.parseDocument=DC;Dl.stringify=kM});var jr=D(He=>{"use strict";var bM=pw(),AM=Cl(),RM=Jv(),_w=xl(),NM=dl(),fo=Te(),SM=ao(),EM=Et(),CM=co(),_M=lo(),IM=Jf(),xM=Rw(),PM=Sw(),OM=Cw(),Yf=BC(),WC=sl();He.Composer=bM.Composer;He.Document=AM.Document;He.Schema=RM.Schema;He.YAMLError=_w.YAMLError;He.YAMLParseError=_w.YAMLParseError;He.YAMLWarning=_w.YAMLWarning;He.Alias=NM.Alias;He.isAlias=fo.isAlias;He.isCollection=fo.isCollection;He.isDocument=fo.isDocument;He.isMap=fo.isMap;He.isNode=fo.isNode;He.isPair=fo.isPair;He.isScalar=fo.isScalar;He.isSeq=fo.isSeq;He.Pair=SM.Pair;He.Scalar=EM.Scalar;He.YAMLMap=CM.YAMLMap;He.YAMLSeq=_M.YAMLSeq;He.CST=IM;He.Lexer=xM.Lexer;He.LineCounter=PM.LineCounter;He.Parser=OM.Parser;He.parse=Yf.parse;He.parseAllDocuments=Yf.parseAllDocuments;He.parseDocument=Yf.parseDocument;He.stringify=Yf.stringify;He.visit=WC.visit;He.visitAsync=WC.visitAsync});function $M(e){return e.toLowerCase().startsWith(".env")}function LC(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>$M(n))?"environment-file":r.some(n=>jM.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>TM.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var TM,jM,qC=x(()=>{"use strict";TM=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),jM=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as DM}from"node:crypto";import{promises as Ft}from"node:fs";import $r from"node:path";import{TextDecoder as MC}from"node:util";function Xf(e,t){let r=$r.relative(e,t);return r===""||!$r.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${$r.sep}`)}function HC(e){let t=$r.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let o=i.codePointAt(0)??0;return o<=31||o===127})||$r.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),n=LC(e);if(n||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function QC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function BM(e,t){return ht({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function po(e,t){let r={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ht(r,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function VC(e){let t=await Ft.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ft.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function UC(e,t){let r=$r.resolve(e),n=$r.resolve(t);if(!Xf(r,n))throw new Error("Native artifact path is outside its root");let i=[await VC(r)],o=r;for(let a of $r.relative(r,n).split($r.sep).filter(Boolean)){o=$r.join(o,a);let s=await VC(o);if(!Xf(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${o}`);i.push(s)}return i}async function Zf(e){for(let t of e){let r=await Ft.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!BM(t,r)||await Ft.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Qe(e){let t=HC(e.ref),r=e.maxBytes===null?null:QC(e.maxBytes??FC),n=$r.resolve(e.root,...t.split("/")),i=await UC(e.root,$r.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Ft.lstat(n);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&o.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let a=await Ft.realpath(n);if(!Xf(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ft.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Zf(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!po(o,c)||!po(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?m.length:r+1-d,b=await s.read(m,0,Math.min(m.length,y),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);f.push(Buffer.from(m.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[h,p,g]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Zf(i),!p.isFile()||p.isSymbolicLink()||g!==a||!po(c,h)||!po(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(f,d),w;try{w=new MC("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:DM("sha256").update(v).digest("hex"),text:w}}finally{await s.close()}}async function JC(e){let t=HC(e.ref),r=QC(e.maxBytes),n=$r.resolve(e.root,...t.split("/")),i=await UC(e.root,$r.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Ft.lstat(n);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);let a=await Ft.realpath(n);if(!Xf(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ft.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Zf(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!po(o,c)||!po(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=Math.min(c.size,r),d=[],m=0,h=Buffer.allocUnsafe(Math.min(64*1024,r));for(;m<f;){let N=await s.read(h,0,Math.min(h.length,f-m),null);if(N.bytesRead===0)break;m+=N.bytesRead,d.push(Buffer.from(h.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[p,g,v]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Zf(i),!g.isFile()||g.isSymbolicLink()||v!==a||!po(c,p)||!po(c,g)||m!==f)throw new Error(`Native artifact changed while reading: ${t}`);let w=c.size>r,y=Buffer.concat(d,m),b;try{b=new MC("utf-8",{fatal:!0}).decode(y,{stream:w})}catch(N){throw new Error(`Native artifact prefix is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:c.size,text:b,truncated:w}}finally{await s.close()}}var FC,Xr=x(()=>{"use strict";qC();ol();FC=Number.MAX_SAFE_INTEGER});import{promises as WM}from"node:fs";import LM from"node:path";function tp(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function ep(e,t,r){let n=Object.keys(e).filter(o=>!t.has(o)),i=[...t].filter(o=>!(o in e));if(n.length>0||i.length>0){let o=[...i.length>0?[`missing ${i.join(", ")}`]:[],...n.length>0?[`unexpected ${n.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${o.join("; ")}`)}}function KC(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,n)=>r.localeCompare(n,"en"))}function QM(e){let t=new Map(e.map(o=>[o.name,o])),r=new Set,n=new Set,i=o=>{if(!n.has(o)){if(r.has(o))throw new Error(`Native children dependency cycle includes ${o}`);r.add(o);for(let a of t.get(o).depends_on)i(a);r.delete(o),n.add(o)}};for(let o of e)i(o.name)}function GC(e,t,r=[]){let n=new Set(t);for(let a of e){let s=a.covers.filter(c=>!n.has(c));if(s.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${s.join(", ")}`)}let i=new Set(e.flatMap(a=>a.covers)),o=r.filter(a=>!i.has(a));if(o.length>0)throw new Error(`Native children do not cover parent acceptance: ${o.join(", ")}`)}function e_(e,t,r){let n={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===xw&&e.acceptance_index){let i=r.requiredAcceptanceIds??[],o=r.allowedAcceptanceIds??t??i,a=Object.keys(e.acceptance_index);n.missing=i.filter(l=>!(l in e.acceptance_index)),n.extra=a.filter(l=>!o.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=s.get(l),f=e.acceptance_index[l];u&&f&&(f.source!==u.source||f.text!==u.text)&&n.mismatched.push(l)}let c=new Set(a);for(let l of e.children)n.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return n.uncovered=i.filter(l=>!YC(e.children,l)),XC(n)?n:null}if(e.schema===mo&&t){let i=new Set(t);for(let o of e.children)n.unknownCovers.push(...o.covers.filter(a=>!i.has(a)));return n.uncovered=(r.requiredAcceptanceIds??[]).filter(o=>!YC(e.children,o)),XC(n)?n:null}return null}function YC(e,t){return e.some(r=>r.covers.includes(t))}function XC(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function un(e){return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[],allowedAcceptanceIds:e.acceptance.map(({id:t})=>t)}}function UM(e){let t=tp(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[n,i]of Object.entries(t)){let o=tp(i,`Native children acceptance_index.${n}`);if(ep(o,new Set(["source","text"]),`Native children acceptance_index.${n}`),typeof o.source!="string"||o.source.length===0)throw new Error(`Native children acceptance_index.${n}.source must be a non-empty string`);if(typeof o.text!="string"||o.text.length===0)throw new Error(`Native children acceptance_index.${n}.text must be a non-empty string`);r[n]={source:o.source,text:o.text}}return r}function JM(e,t,r){let n=r.requiredAcceptanceIds??[],i=r.allowedAcceptanceIds??t??n,o=Object.keys(e),a=n.filter(c=>!(c in e)),s=o.filter(c=>!i.includes(c));if(a.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${s.join(", ")||"none"}`)}function rp(e,t,r={}){let n=(0,ZC.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${n.errors[0].message}`);let i=tp(n.toJS({mapAsMap:!1}),"Native children contract"),o=i.schema;if(o!==mo&&o!==ho)throw ep(i,zC,"Native children contract"),new Error(`Native children schema must be ${mo} or ${ho}`);let a=o===mo?"v1":"acceptance_index"in i?"indexed-v2":Array.isArray(i.children)&&i.children.every(d=>!d||typeof d!="object"||!("summary"in d))&&i.children.some(d=>d&&typeof d=="object"&&"covers"in d)?"referenced-v2":"summary-v2";if(a==="referenced-v2"&&!r.acceptanceCatalog)throw new Error("Native referenced children require the current acceptance catalog");let s=a.replace("-"," ");if(ep(i,a==="indexed-v2"?VM:zC,"Native children contract"),!Array.isArray(i.children)||i.children.length===0)throw new Error("Native children must be a non-empty array");let c=i.children.map((d,m)=>{let h=tp(d,`Native child ${m}`);if(ep(h,a==="indexed-v2"||a==="referenced-v2"?HM:a==="summary-v2"?FM:MM,`Native ${s} child fields (child ${m})`),typeof h.name!="string"||!qM.test(h.name))throw new Error(`Native child ${m} name is invalid`);let p=a==="summary-v2";if(p){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:p?h.summary:null,depends_on:KC(h.depends_on,`Native child ${h.name} depends_on`),covers:a==="indexed-v2"||a==="referenced-v2"||a==="v1"?KC(h.covers,`Native child ${h.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let m=d.depends_on.filter(h=>!u.has(h));if(m.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${m.join(", ")}`)}QM(c);let f=r.policy==="advisory";if(o===xw){if(a==="indexed-v2"||a==="referenced-v2"){let d=a==="indexed-v2"?UM(i.acceptance_index):{},m=[...new Set([...Object.keys(d),...r.requiredAcceptanceIds??[],...c.flatMap(v=>v.covers)])],h=new Map(r.acceptanceCatalog?.map(v=>[v.id,v])),p=Object.fromEntries(m.map(v=>{let w=h.get(v)??d[v];if(!w)throw new Error(`Native acceptance catalog is missing ${v}`);return[v,{source:w.source,text:w.text}]}));f||JM(p,t,r);let g=Object.keys(p);return f||GC(c,g,r.requiredAcceptanceIds??[]),{schema:ho,acceptance_index:p,children:c}}return{schema:ho,children:c}}return t&&!f&&GC(c,t),{schema:mo,children:c}}async function dn(e){let t=LM.join(e.changeDir,Iw);try{await WM.lstat(t)}catch(a){if(a.code==="ENOENT")return null;throw a}let r=await Qe({root:e.changeDir,ref:Iw,includeHash:!1}),n=e.policy==="advisory",i=n?{...e.validation,policy:"advisory"}:e.validation??{},o=rp(r.text,e.acceptanceIds,i);return{contract:o,size:r.size,drift:n?e_(o,e.acceptanceIds,e.validation??{}):null}}function ze(e,t,r){let n=e?.contractRef??e?.contractHash;if(t&&typeof n=="string"){let i=t.state;if(r?.stepId==="supervisor.prepare"&&r.executionOrigin&&n===i.children_contract_hash){let s=t.actionContexts[r.id].results["shape.prepare"],c=s&&t.actions.find(l=>l.stepId==="shape.prepare"&&l.status==="succeeded"&&t.actionContexts[l.id].sequence===s.sequence);if(c&&c.id===i.children_contract_ref)return c.id}if(n===i.children_contract_ref)return n;let o=t.outputs["supervisor.prepare"];if(o?.value?.contractHash===n){let s=t.actions.find(u=>u.stepId==="supervisor.prepare"&&u.status==="succeeded"&&t.actionContexts[u.id].sequence===o.sequence),c=s&&t.actionContexts[s.id].results["shape.prepare"],l=c&&t.actions.find(u=>u.stepId==="shape.prepare"&&u.status==="succeeded"&&t.actionContexts[u.id].sequence===c.sequence);if(l&&l.id===i.children_contract_ref)return l.id}}return typeof n=="string"?n:void 0}var ZC,Iw,mo,ho,xw,qM,zC,VM,MM,FM,HM,vr=x(()=>{"use strict";ZC=tr(jr(),1);Xr();Iw="children.yaml",mo="comet.native.children.v1",ho="comet.native.children.v2",xw=ho,qM=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zC=new Set(["schema","children"]),VM=new Set(["schema","acceptance_index","children"]),MM=new Set(["name","depends_on","covers"]),FM=new Set(["name","summary","depends_on"]),HM=new Set(["name","depends_on","covers"])});import{AsyncLocalStorage as zM}from"node:async_hooks";function np(){let e=Pw.getStore();return e?.active?e:null}function t_(){np()?.entries.clear()}async function ip(e){if(np()!==null)return e();let t={entries:new Map,active:!0};return Pw.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function ei(e){return Pw.run({entries:new Map,active:!1},e)}function r_(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function fn(e,t){return(...r)=>{let n=np();if(n===null)return t(...r);let i=r_(`async:${e}`,r),o=n.entries.get(i);if(o)return o.value;let a=t(...r).catch(s=>{throw n.entries.get(i)?.value===a&&n.entries.delete(i),s});return n.entries.set(i,{value:a}),a}}function Si(e,t){return(...r)=>{let n=np();if(n===null)return t(...r);let i=r_(`sync:${e}`,r),o=n.entries.get(i);if(o)return o.value;let a=t(...r);return n.entries.set(i,{value:a}),a}}var Pw,ti=x(()=>{"use strict";Pw=new zM});import{createHash as KM}from"node:crypto";import{lstatSync as Bl,readFileSync as GM,realpathSync as n_}from"node:fs";import YM from"node:os";import wr from"node:path";function Ow(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function op(e){return process.platform==="win32"?n_.native(e):n_(e)}function ZM(e){return XM(e)}function e1(e){let t=op(wr.resolve(e)),r=Bl(t,{bigint:!0});if(!r.isDirectory())throw new Error(`工作区必须是目录:${e}`);let n=Ow(r),i=(c,l)=>({projectRoot:t,workspaceId:KM("sha256").update(JSON.stringify(["comet.workspace.v2",t,n,c,l])).digest("hex")}),o=wr.join(t,".git"),a,s;try{let c=Bl(o);if(c.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${o}`);if(c.isDirectory())a=op(o),s=Ow(Bl(a,{bigint:!0}));else if(c.isFile()){let l=/^gitdir: (.+)\r?\n?$/u.exec(GM(o,"utf8"));if(!l)throw new Error(`工作区 .git 文件格式无效:${o}`);a=op(wr.resolve(t,l[1].trim()));let u=Bl(a,{bigint:!0});if(!u.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${a}`);s=Ow(u)}else throw new Error(`工作区 .git 类型无效:${o}`)}catch(c){if(c.code!=="ENOENT")throw c;try{Bl(o)}catch(l){if(l.code==="ENOENT")return i(o,null);throw l}throw c}return i(a,s)}function i_(e){let t=wr.dirname(e);if(t===e)return e;try{return wr.join(op(t),wr.basename(e))}catch(r){if(r.code!=="ENOENT")throw r;return wr.join(i_(t),wr.basename(e))}}function Tw(e){let t=ZM(e),r=process.env.COMET_DATA_DIR;if(r!==void 0&&(!r.trim()||!wr.isAbsolute(r)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let n=t1(r??wr.join(YM.homedir(),".comet")),i=wr.relative(t.projectRoot,n);if(i===""||!wr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${wr.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${n};工作区:${t.projectRoot}`);let o=wr.join(n,"workspaces",t.workspaceId);return{...t,dataRoot:n,workspaceRoot:o,runtimeRoot:wr.join(o,"runtime")}}function Ue(e){return Tw(e).runtimeRoot}var XM,t1,jw=x(()=>{"use strict";ti();XM=Si("workspaceIdentity",e1);t1=Si("workspaceRuntimeParent",i_)});import{constants as go,promises as Dr}from"fs";import{createHash as r1}from"node:crypto";function $w(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ap(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function wo(e){return{dev:e.dev,ino:e.ino,birthtime:$w(e)}}function n1(e,t){let r=wo(e),n=wo(t);return il(r,n)?ht(r,n):ht(r,n)&&$w(e)===$w(t)&&ap(e)===ap(t)&&e.size===t.size}function vo(e,t){let r=n=>"mtimeNs"in n?n.mtimeNs:n.mtimeMs;return n1(e,t)&&e.size===t.size&&e.mode===t.mode&&r(e)===r(t)&&ap(e)===ap(t)}async function da(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,o=await Dr.lstat(e,{bigint:i});if(!o.isFile()||o.isSymbolicLink())throw new jt("not-regular-file",`${n} must be a regular file`);if(BigInt(o.size)>BigInt(t))throw new jt("too-large",`${n} exceeds ${t} bytes`);let a=await Dr.realpath(e);await r.verify?.("pre-open",{realPath:a,identity:wo(o)});let s=process.platform==="win32"?go.O_RDONLY:go.O_RDONLY|go.O_NOFOLLOW|go.O_NONBLOCK,c;try{c=await Dr.open(e,s)}catch(l){throw l.code==="ELOOP"?new jt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:i}),Dr.lstat(e,{bigint:i}),Dr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==a||!vo(o,l)||!vo(o,u))throw new jt("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:wo(l)}),await r.hooks?.afterOpen?.();let d=[],m=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-m,{bytesRead:b}=await c.read(h,0,Math.min(h.length,y),null);if(b===0)break;if(m+=b,m>t)throw new jt("too-large",`${n} exceeds ${t} bytes`);d.push(Buffer.from(h.subarray(0,b)))}let p=Buffer.concat(d,m);if(await r.hooks?.beforeFinalCheck?.(),process.platform==="win32"){let y=0;for(;;){let{bytesRead:b}=await c.read(h,0,Math.min(h.length,m+1-y),y);if(b===0&&y===m)break;if(b===0||y+b>m||!h.subarray(0,b).equals(p.subarray(y,y+b)))throw new jt("changed",`${n} changed while reading`);y+=b}}let[g,v,w]=await Promise.all([c.stat({bigint:i}),Dr.lstat(e,{bigint:i}),Dr.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||w!==a||!vo(o,g)||!vo(o,v))throw new jt("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:wo(g)}),{bytes:p,stat:g,realPath:w}}finally{await c.close()}}async function a_(e,t={}){let r=t.label??"file",n=t.bigint===!0,i=await Dr.lstat(e,{bigint:n});if(!i.isFile()||i.isSymbolicLink())throw new jt("not-regular-file",`${r} must be a regular file`);let o=await Dr.realpath(e);await t.verify?.("pre-open",{realPath:o,identity:wo(i)});let a=process.platform==="win32"?go.O_RDONLY:go.O_RDONLY|go.O_NOFOLLOW|go.O_NONBLOCK,s;try{s=await Dr.open(e,a)}catch(c){throw c.code==="ELOOP"?new jt("not-regular-file",`${r} must be a regular file`,{cause:c}):c}try{let[c,l,u]=await Promise.all([s.stat({bigint:n}),Dr.lstat(e,{bigint:n}),Dr.realpath(e)]);if(!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!vo(i,c)||!vo(i,l))throw new jt("changed",`${r} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:wo(c)}),await t.hooks?.afterOpen?.();let f=t.algorithm??"sha256",d=await o_(s,f);if(await t.hooks?.beforeFinalCheck?.(),process.platform==="win32"&&await o_(s,f)!==d)throw new jt("changed",`${r} changed while reading`);let[m,h,p]=await Promise.all([s.stat({bigint:n}),Dr.lstat(e,{bigint:n}),Dr.realpath(e)]);if(!h.isFile()||h.isSymbolicLink()||p!==o||!vo(i,m)||!vo(i,h))throw new jt("changed",`${r} changed while reading`);return await t.verify?.("post-read",{realPath:p,identity:wo(m)}),{digest:d,stat:m,realPath:p}}finally{await s.close()}}async function o_(e,t){let r=r1(t),n=Buffer.allocUnsafe(64*1024),i=0;for(;;){let{bytesRead:o}=await e.read(n,0,n.length,i);if(o===0)break;r.update(n.subarray(0,o)),i+=o}return r.digest("hex")}var jt,yo=x(()=>{"use strict";vs();jt=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});import{promises as s_}from"node:fs";import i1 from"node:path";async function $n(e){return Ue(e)}async function Dw(e){return[Ue(e)]}async function c_(e){let t=i1.dirname(e);if(t!==e){await c_(t);try{await s_.mkdir(e,{mode:448})}catch(n){if(n.code!=="EEXIST")throw n}}let r=await s_.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function Ei(e){let t=Ue(e);return await c_(t),t}var yr=x(()=>{"use strict";jw();yo()});import ko from"path";import{isDeepStrictEqual as l_}from"node:util";function h_(e,t){return fa[t][e]}function a1(e,t,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let i=n[1].length,o=n[2];if(i===0&&o in fa.en)return o;if(i===2&&t){let a=`${t}.${o}`;if(a in fa.en)return a}if(i===4&&t==="knowledge"&&r==="remote"){let a=`knowledge.remote.${o}`;if(a in fa.en)return a}if(i===4&&t==="knowledge"&&r==="local"){let a=`knowledge.local.${o}`;if(a in fa.en)return a}return i===2&&t===null&&o==="hook"?"hook":i===2&&t==="hook"&&o==="allow_paths"?"hook.allow_paths":null}function Vl(e,t,r){let n=[],i=null,o=null;for(let g of(0,ke.stringify)(e).trimEnd().split(`
144
+ `)){let v=a1(g,i,o);if(v){let w=g.match(/^\s*/u)?.[0]??"";for(let y of h_(v,t).split(`
145
+ `))n.push(`${w}${y}`)}n.push(g),/^[a-z_]+:/u.test(g)?(g.startsWith("native:")?i="native":g.startsWith("classic:")?i="classic":g.startsWith("hook:")?i="hook":g.startsWith("memory:")?i="memory":g.startsWith("knowledge:")?i="knowledge":i=null,o=null):/^ {2}[a-z_]+:/u.test(g)&&i==="knowledge"&&(o=g.startsWith(" local:")?"local":g.startsWith(" remote:")?"remote":null)}n.push("");let a=n.join(`
146
+ `);if(!r)return a;let s=(0,ke.parseDocument)(r,{uniqueKeys:!0});if(s.errors.length>0)throw new Error(s.errors[0].message);let c=(0,ke.parseDocument)(a);if(!(0,ke.isMap)(s.contents)||!(0,ke.isMap)(c.contents))return a;let l=g=>{if(!(0,ke.isMap)(g))return;let v=g.items[0];g.commentBefore&&v&&(0,ke.isScalar)(v.key)&&(v.key.commentBefore=[g.commentBefore,v.key.commentBefore].filter(Boolean).join(`
147
+ `),g.commentBefore=void 0);for(let w of g.items)l(w.value)};l(s.contents),l(c.contents);let u=s.toJS(),f=c.get("classic",!0);if((0,ke.isMap)(f))for(let g of[...s.contents.items]){if(!(0,ke.isScalar)(g.key)||c.has(g.key))continue;let v=String(g.key.value);if(!Object.hasOwn(fa.en,`classic.${v}`)||!f.has(v))continue;let w=s.get("classic",!0);if(!(0,ke.isMap)(w)){let b=s.createPair("classic",{});s.contents.items.push(b),w=b.value}if(!(0,ke.isMap)(w))continue;let y=w.items.find(b=>(0,ke.isScalar)(b.key)&&b.key.value===v);y?((0,ke.isScalar)(y.key)&&(y.key.commentBefore=[g.key.commentBefore,y.key.commentBefore].filter(Boolean).join(`
148
+ `)||void 0),(0,ke.isNode)(y.value)&&(0,ke.isNode)(g.value)&&(y.value.comment=[g.value.comment,y.value.comment].filter(Boolean).join(`
149
+ `)||void 0)):(w.items.push(g),u.classic={...u.classic,[v]:u[v]})}let d=new Set(Object.values(fa).flatMap(g=>Object.values(g).flatMap(v=>v.split(`
150
+ `).map(w=>w.replace(/^#\s?/u,"").trim())))),m=(g,v,w,y)=>{for(let b of[...g.items])v.has(b.key)||g.delete(b.key);for(let b of v.items){let N=String((0,ke.isScalar)(b.key)?b.key.value:b.key),A=g.items.find(S=>(0,ke.isScalar)(S.key)&&(0,ke.isScalar)(b.key)?S.key.value===b.key.value:!1);if(!A){let S=s.createPair(N,y[N]);(0,ke.isScalar)(S.key)&&(0,ke.isScalar)(b.key)&&(S.key.commentBefore=b.key.commentBefore),g.items.push(S),(0,ke.isMap)(S.value)&&(0,ke.isMap)(b.value)&&m(S.value,b.value,y[N],y[N]);continue}if((0,ke.isScalar)(A.key)&&(0,ke.isScalar)(b.key)){let S=A.key.commentBefore?.split(`
151
+ `).filter(_=>!d.has(_.trim())).join(`
152
+ `);A.key.commentBefore=[b.key.commentBefore,S].filter(Boolean).join(`
153
+ `)||void 0}if((0,ke.isMap)(A.value)&&(0,ke.isMap)(b.value))m(A.value,b.value,w[N]??{},y[N]);else if(!l_(w[N],y[N])){let S=A.value;A.value=s.createNode(y[N]),(0,ke.isNode)(S)&&(0,ke.isNode)(A.value)&&(A.value.comment=S.comment,A.value.commentBefore=S.commentBefore,A.value.spaceBefore=S.spaceBefore)}}};m(s.contents,c.contents,u,e);let h=(g,v)=>{if((0,ke.isAlias)(g)){let w=!1;try{w=l_(g.toJS(s),v)}catch{}if(w)return g;let y=s.createNode(v);return y.comment=g.comment,y.commentBefore=g.commentBefore,y.spaceBefore=g.spaceBefore,y}if((0,ke.isMap)(g))for(let w of g.items){let y=String((0,ke.isScalar)(w.key)?w.key.value:w.key);w.value=h(w.value,v[y])}else(0,ke.isSeq)(g)&&Array.isArray(v)&&(g.items=g.items.map((w,y)=>h(w,v[y])));return g};h(s.contents,e);let p=s.toString();return r.includes(`\r
154
+ `)?p.replaceAll(`
155
+ `,`\r
156
+ `):p}function s1(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||ko.posix.isAbsolute(r)||ko.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function pa(e){let t=s1(e,"native.artifact_root");return t.length===0?".":t.join("/")}function g_(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Ao(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||ko.posix.isAbsolute(n)||ko.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let i=n.split("/");if(i.some(o=>o===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(o=>o===""||o==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function bo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function v_(e,t,r){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function c1(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function m_(e,t,r){let n=c1(e,t,r);if(n>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return n}function l1(e){if(e===void 0)return;let t=bo(e,"native.pending_root_move"),r=t.id,n=t.from_artifact_root,i=t.to_artifact_root,o=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(o!=="copying"&&o!=="ready"&&o!=="switched")throw new Error("native.pending_root_move.stage is invalid");let a;if(t.cleanup!==void 0){let s=bo(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");a={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:pa(n),toArtifactRoot:pa(i),stage:o,...a?{cleanup:a}:{}}}function u1(e){if(e===void 0)return;let t=bo(e,"native.finish");if(t.pull_request===void 0)return{};let r=bo(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let n=r.command.map((o,a)=>{if(typeof o!="string"||o.trim().length===0||o.length>4096||/[\0\r\n]/u.test(o))throw new Error(`native.finish.pull_request.command[${a}] must be a non-empty single-line string of at most 4096 characters`);return o});if(ko.posix.isAbsolute(n[0])||ko.win32.isAbsolute(n[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=r.timeout_ms??o1;if(!Number.isSafeInteger(i)||i<1||i>p_)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${p_}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function d1(e,t={}){let r=bo(e,"native"),n=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let o=r.archive_confirmation??"automatic";if(o!=="automatic"&&o!=="required")throw new Error("native.archive_confirmation must be automatic or required");let a=r.max_verify_failures??xs;if(!Number.isSafeInteger(a)||a<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.max_parallel_children===void 0?ql:r.max_parallel_children;if(!Number.isSafeInteger(s)||s<1)throw new Error("native.max_parallel_children must be a positive integer");let c=r.document_writes??"allow";if(c!=="allow"&&c!=="revert")throw new Error("native.document_writes must be allow or revert");let l=l1(r.pending_root_move),u=u1(r.finish);return{artifact_root:pa(n),language:v_(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:o,max_verify_failures:a,max_parallel_children:s,...c==="revert"?{document_writes:c}:{},...u?{finish:u}:{},...l?{pending_root_move:l}:{}}}function f1(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>f_)throw new Error(`${t} must be an integer between 1 and ${f_} milliseconds`);return e}function p1(e){let t=bo(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=t.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");t.check_timeout_ms!==void 0&&f1(t.check_timeout_ms,"classic.check_timeout_ms");let o=t.document_evidence??"neutral";if(o!=="neutral"&&o!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:g_(t.artifact_layout),language:v_(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i,...o==="strict"?{document_evidence:o}:{},...t.check_timeout_ms!==void 0?{check_timeout_ms:t.check_timeout_ms}:{}}}function m1(e){let r=bo(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((n,i)=>Ao(n,`hook.allow_paths[${i}]`)))]}}function h1(e){if(e===void 0)return{...Wl};let t=bo(e,"memory"),r=t.learning??Wl.learning,n=t.retrieval??Wl.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof n!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:n}}function Ww(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function g1(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||ko.posix.isAbsolute(r)||ko.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>u_)throw new Error(`${t} exceeds ${u_} characters`);let n=0;for(let i=0;i<r.length;i+=1)r[i]==="?"?n+=1:r[i]==="*"&&(n+=1,r[i+1]==="*"&&(i+=1));if(n>d_)throw new Error(`${t} contains more than ${d_} wildcard tokens`);return r}function v1(e){let t=Ww(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let n={include:[...new Set(r.map((i,o)=>g1(i,`knowledge.local.include[${o}]`)))],max_file_mb:m_(t.max_file_mb,sp.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:m_(t.max_total_mb,sp.max_total_mb,"knowledge.local.max_total_mb")};if(n.max_file_mb>n.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return n}function w1(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),n=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function y1(e){let t=Ww(e,"knowledge.remote"),r=w1(t.endpoint),n=t.token_env;if(n!==void 0&&(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(n)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=t.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let o=t.timeout_ms??5e3;if(typeof o!="number"||!Number.isSafeInteger(o)||o<100||o>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...n===void 0?{}:{token_env:n},...i===void 0?{}:{scope:i},timeout_ms:o}}function k1(e){if(e===void 0)return{...Bw};let t=Ww(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let n=t.local===void 0?void 0:v1(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:y1(t.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...n?{local:n}:{},remote:i}}function Lw(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function b1(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function A1(e,t,r,n,i,o,a,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let f=[...new Set(u)];if(!f.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(f.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:f,ambient_resume:a,change_walkthrough:Lw(e.change_walkthrough),...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...o?{classic:o}:{}}}function Ps(e,t={}){let r=(0,ke.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0,change_walkthrough:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=n,o=b1(i.ambient_resume),a=Lw(i.change_walkthrough),s=i.hook===void 0?void 0:m1(i.hook),c=h1(i.memory),l=k1(i.knowledge),u=i.native===void 0?void 0:d1(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=i.classic===void 0?void 0:p1(i.classic),d=A1(i,s,c,l,u,f,o,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:d,ambient_resume:o,change_walkthrough:a,memory:c,knowledge:l,...s?{hook:s}:{},...u?{native:u}:{},...f?{classic:f}:{}}}function w_(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function y_(e){let t=e.knowledge??{...Bw};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,change_walkthrough:e.change_walkthrough??!0,memory:e.memory??{...Wl},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??sp.max_file_mb,max_total_mb:t.local.max_total_mb??sp.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,max_parallel_children:e.native.max_parallel_children??ql,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:w_(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.check_timeout_ms!==void 0?{check_timeout_ms:e.classic.check_timeout_ms}:{},...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function Zr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ml(e,t){let r=y_({...t,change_walkthrough:t.change_walkthrough??Lw(e.change_walkthrough)}),n=Ps((0,ke.stringify)(r)).config;if(!n)throw new Error("Unsupported Comet project schema");let i={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume,change_walkthrough:n.change_walkthrough??!0};if(n.hook&&(i.hook={...Zr(e.hook),allow_paths:[...n.hook.allow_paths]}),n.memory){let o=Zr(e.memory);i.memory={...o,learning:n.memory.learning,retrieval:n.memory.retrieval}}if(n.knowledge){let o=Zr(e.knowledge),a={...o,provider:n.knowledge.provider};if(n.knowledge.local?a.local={...Zr(o.local),include:[...n.knowledge.local.include],max_file_mb:n.knowledge.local.max_file_mb,max_total_mb:n.knowledge.local.max_total_mb}:delete a.local,n.knowledge.remote){let c={...Zr(o.remote),endpoint:n.knowledge.remote.endpoint,timeout_ms:n.knowledge.remote.timeout_ms,...n.knowledge.remote.token_env===void 0?{}:{token_env:n.knowledge.remote.token_env},...n.knowledge.remote.scope===void 0?{}:{scope:n.knowledge.remote.scope}};n.knowledge.remote.token_env===void 0&&delete c.token_env,n.knowledge.remote.scope===void 0&&delete c.scope,a.remote=c}else delete a.remote;i.knowledge=a}if(n.native){let o=Zr(e.native),a={...o,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,max_parallel_children:n.native.max_parallel_children,...n.native.document_writes?{document_writes:n.native.document_writes}:{}};if(t.native?.document_writes==="allow"&&delete a.document_writes,n.native.finish?.pull_request){let s=Zr(o.finish);a.finish={...s,pull_request:{...Zr(s.pull_request),provider:n.native.finish.pull_request.provider,command:[...n.native.finish.pull_request.command],timeout_ms:n.native.finish.pull_request.timeout_ms}}}else{let s={...Zr(o.finish)};delete s.pull_request,Object.keys(s).length>0?a.finish=s:delete a.finish}if(delete a.snapshot,n.native.pending_root_move){let s=Zr(o.pending_root_move),c=w_(n.native.pending_root_move),l=Zr(s.cleanup),u=Zr(c.cleanup);a.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete a.pending_root_move;i.native=a}return n.classic&&(i.classic={...Zr(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition,...n.classic.check_timeout_ms!==void 0?{check_timeout_ms:n.classic.check_timeout_ms}:{},...n.classic.document_evidence?{document_evidence:n.classic.document_evidence}:{}}),i}function cp(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,change_walkthrough:!0,memory:{...Wl},knowledge:{...Bw},native:{artifact_root:pa(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:xs,max_parallel_children:ql}}}var ke,Ll,u_,d_,xs,ql,Wl,sp,Bw,f_,o1,p_,fa,Ci=x(()=>{"use strict";ke=tr(jr(),1),Ll=Number.MAX_SAFE_INTEGER,u_=1024,d_=64,xs=5,ql=2,Wl={learning:!0,retrieval:!0},sp={include:[],max_file_mb:1,max_total_mb:32},Bw={provider:"local"},f_=36e5,o1=12e4,p_=6e5,fa={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",change_walkthrough:`# Generate a standalone HTML change walkthrough for Native and Classic. Enabling it uses extra explanation tokens.
157
+ # change_walkthrough: true | false (default: true)`,ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
158
+ # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
159
+ # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
160
+ # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
161
+ # provider: local | remote`,"knowledge.local":"# Additional project-relative Markdown globs used by the local provider.","knowledge.local.include":"# One project-relative Markdown glob per list item; appended to the built-in corpus.","knowledge.local.max_file_mb":"# Maximum size in MB for one local Markdown document. Increase it for long specifications or verification reports.","knowledge.local.max_total_mb":"# Maximum total size in MB of the local Markdown retrieval corpus.","knowledge.remote":"# Fixed Comet Retrieval API v1 settings used when provider is remote.","knowledge.remote.endpoint":"# HTTPS endpoint; loopback HTTP is allowed.","knowledge.remote.token_env":"# Optional environment variable containing the bearer token.","knowledge.remote.scope":"# Optional opaque remote knowledge scope.","knowledge.remote.timeout_ms":"# Remote request timeout in milliseconds (100-30000).",hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
162
+ # language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time.
163
+ # clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
164
+ # archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.max_parallel_children":"# Maximum dispatched Supervisor children awaiting integration and archive. Defaults to 2; single-session always uses 1. Changes apply at the next dispatch.","native.document_writes":`# Controls documentation file writes during Shape, Verify, and Archive: allow treats them as neutral instead of returning the change to Build, revert restores the strict behavior.
165
+ # document_writes: allow | revert`,"native.finish":"# Optional repository-owned finish providers. Native keeps commit, push, generic remote verification, and recovery ownership.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
166
+ # artifact_layout: legacy | docs`,"classic.language":`# Artifact language used by Classic workflow documents.
167
+ # language: en | zh-CN`,"classic.context_compression":`# Controls beta context compression for new Classic changes.
168
+ # context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
169
+ # review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
170
+ # auto_transition: true | false`,"classic.check_timeout_ms":"# Default check timeout in milliseconds (1-3600000); --timeout-ms overrides it. Default: 300000.","classic.document_evidence":`# Controls how documentation edits affect recorded check evidence: neutral keeps build and verify evidence valid when only documentation files changed, strict binds every working-tree file again.
171
+ # document_evidence: neutral | strict`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",change_walkthrough:`# 是否生成可直接打开的 HTML 变更说明,同时作用于 Native 和 Classic;开启会增加讲解内容的 token 消耗。
172
+ # change_walkthrough: true | false(默认 true)`,ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
173
+ # ambient_resume: true | false`,memory:"# 当前项目的个人记忆自动学习与注入策略。","memory.learning":`# 是否允许当前项目通过工作流事件自动沉淀新的个人记忆。
174
+ # 可选值:true | false`,"memory.retrieval":`# 是否允许当前项目把个人记忆自动注入 Agent 上下文。
175
+ # 可选值:true | false`,knowledge:"# 普通 Comet 任务使用的项目知识检索 Provider。","knowledge.provider":`# 项目知识 Provider。
176
+ # 可选值:local | remote`,"knowledge.local":"# Local Provider 额外加载的项目相对 Markdown 路径。","knowledge.local.include":"# 每项填写一个项目相对 Markdown glob;会追加到内置语料。","knowledge.local.max_file_mb":"# 单个本地 Markdown 文档允许参与检索的最大 MB 数;较长的规格或验证报告可按需提高。","knowledge.local.max_total_mb":"# 本地 Markdown 检索语料允许读取的总 MB 数。","knowledge.remote":"# provider 为 remote 时使用的固定 Comet Retrieval API v1 配置。","knowledge.remote.endpoint":"# HTTPS 地址;loopback 地址允许使用 HTTP。","knowledge.remote.token_env":"# 可选的 Bearer Token 环境变量名。","knowledge.remote.scope":"# 可选的不透明远端知识库范围。","knowledge.remote.timeout_ms":"# 远端请求超时时间(毫秒,100-30000)。",hook:"# Native 和 Classic 共享的 Hook 写入策略;路径必须是项目相对路径。","hook.allow_paths":"# 在受保护阶段允许写入的项目相对目录;每项填写一个目录,默认为空。",native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
177
+ # 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
178
+ # 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
179
+ # 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.max_parallel_children":"# Supervisor 已派发且尚未完成集成归档的子任务上限;默认 2,single-session 固定为 1;调整从下一轮派发生效。","native.document_writes":`# Shape、Verify 和 Archive 阶段的文档类写入处理方式:allow 视为中性写入、不再把 change 打回 Build,revert 恢复严格行为。
180
+ # 可选值:allow | revert`,"native.finish":"# 可选的仓库自有收尾 provider;提交、推送、通用远端核验和恢复仍由 Native 负责。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
181
+ # 可选值:legacy | docs`,"classic.language":`# Classic 工作流文档使用的产物语言。
182
+ # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
183
+ # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
184
+ # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
185
+ # 可选值:true | false`,"classic.check_timeout_ms":"# 检查命令默认超时,单位毫秒,范围 1-3600000,缺省为 300000;命令行 --timeout-ms 优先。","classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
186
+ # 可选值:neutral | strict`}}});import{promises as Os}from"fs";import tt from"path";import R1 from"os";async function qw(e){try{return await Os.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function S1(e){try{let t=await Os.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Fl(e,t){let r=tt.relative(e,t);return r===""||!tt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${tt.sep}`)}async function Hl(e){let t=[],r=e;for(;!await qw(r);){let i=tt.dirname(r);if(i===r)break;t.push(tt.basename(r)),r=i}let n=await Os.realpath(r);return tt.resolve(n,...t.reverse())}async function Vw(e){try{return(await Os.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function lp(e){let t=tt.resolve(e);try{(await Os.stat(t)).isDirectory()||(t=tt.dirname(t))}catch(i){if(i.code!=="ENOENT")throw i}let r=t,n=tt.resolve(R1.homedir());for(;;){if(!(t===n&&r!==n)){let a=tt.join(t,...Ql.split("/")),s=t===r||await S1(a);if(await qw(a)&&s)return t}if(await qw(tt.join(t,".git")))return t;let o=tt.dirname(t);if(o===t)return r;t=o}}function up(e){return pa(e)}async function E1(e,t){let r=up(t),n=tt.resolve(e,...r.split("/")),i=await Os.realpath(e),o=await Hl(n);if(!Fl(i,o))throw new Error("native.artifact_root resolves outside the project root");return n}async function he(e,t,r={}){let n=up(t),i=await E1(e,n),o=tt.join(i,"comet");if(await Vw(o))throw new Error("The configured Native comet root must not be a symbolic link");let[a,s]=await Promise.all([Hl(i),Hl(o)]);if(!Fl(a,s))throw new Error("The configured Native comet root resolves outside its artifact root");let c=tt.resolve(e),l=Ue(c),u=tt.join(l,"native");if(await Vw(u))throw new Error("The Native Runtime root must not be a symbolic link");return await _i(l,u),{projectRoot:c,configFile:tt.join(e,...Ql.split("/")),artifactRoot:i,artifactRootRef:n,nativeRoot:o,specsDir:tt.join(o,"specs"),changesDir:tt.join(o,"changes"),archiveDir:tt.join(o,"archive"),workspaceRuntimeRoot:l,runtimeDir:u,changesRuntimeDir:tt.join(u,"changes"),transactionsDir:tt.join(u,"transactions")}}function C1(e){if(!N1.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Mw(e,t){C1(t);let r=tt.join(e.changesRuntimeDir,t);if(!Br(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Br(e,t){return Fl(tt.resolve(e),tt.resolve(t))}async function _i(e,t){let r=tt.resolve(e),n=tt.resolve(t);if(!Fl(r,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Vw(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[i,o]=await Promise.all([Hl(r),Hl(n)]);if(!Fl(i,o))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Ql,N1,Ke=x(()=>{"use strict";yr();Ci();Ql=".comet/config.yaml",N1=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function _1(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Ct(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(_1(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",n=0;for(let i of e){let o=Buffer.byteLength(i,"utf8");if(n+o>t)break;r+=i,n+=o}return{text:r,truncated:!0}}var Ii=x(()=>{"use strict"});function Fw(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function dp(e,t,r="acceptance_review"){if(!Array.isArray(e))throw new Error(`Native Builder ${r} must be an array`);let n=[],i=l=>{try{return l()}catch(u){n.push(u instanceof Error?u.message:String(u))}},o=t&&new Set(t.map(({id:l})=>l)),a=[],s=[],c=e.flatMap((l,u)=>{let f=`Native Builder ${r}[${u}]`;if(!l||typeof l!="object"||Array.isArray(l))return n.push(`${f} must be an object`),[];let d=l;i(()=>ra(d,["id","status","evidence","note"],f,`/${r}/${u}`));let m=i(()=>Fw(d.id,`${f}.id`));m&&(a.includes(m)&&n.push(`${f}.id contains duplicate ID: ${m}`),a.push(m),o&&!o.has(m)&&s.push({index:u,id:m}));let h=m&&o?.has(m)?f+" ("+m+")":f,p=i(()=>ps(d.status,Yc,`${f}.status`)),g;Array.isArray(d.evidence)?g=d.evidence.map((w,y)=>i(()=>Fw(w,`${f}.evidence[${y}]`))).filter(w=>w!==void 0):n.push(`${h}.evidence must be an array of concrete strings of at most 4000 characters; received ${typeof d.evidence}`);let v=i(()=>Fw(d.note,`${h}.note`));return m&&p&&g&&v?[{id:m,status:p,evidence:g,note:v}]:[]});if(t&&!n.length)return Ul(t,c),c;if(t){for(let{index:u,id:f}of s)n.push(`Native Builder ${r}[${u}].id contains unknown ID: ${f}`);let l=t.filter(({id:u})=>!a.includes(u)).map(({id:u})=>u);l.length&&n.push(`Native Builder ${r} missing: ${l.join(", ")}`)}if(n.length)throw new Error(n.join(`
187
+ `));return c}function Ul(e,t){if(!t)throw new Ro(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),n=t.map(({id:c})=>c),i=new Set(n);if(i.size!==n.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let o=n.filter(c=>!r.has(c));if(o.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${o.join(", ")}`);let a=e.filter(({id:c})=>!i.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(a.length||s.length)throw new Ro(a,s)}var Ro,fp=x(()=>{"use strict";Md();ta();Ro=class extends Error{constructor(r,n){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${n.length?`; not ready: ${n.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=n}missingIds;incompleteIds}});var k_,R,pn=x(()=>{"use strict";k_=Object.freeze({STORE_WRITER_FENCED:"inspect-run",STORE_INDEX_CORRUPT:"repair-storage",STORE_INDEX_EPOCH_CHANGED:"inspect-run",STORE_BUSY:"inspect-run",SCOPE_HELD:"inspect-run",INVALID_VALIDATION:"restore-definition",ACTION_ACTIVE:"reconcile-execution",ACTION_ALREADY_ADVANCED:"inspect-run",ACTION_ALREADY_CLAIMED:"inspect-run",ACTION_IN_FLIGHT:"reconcile-execution",ACTION_NOT_FOUND:"inspect-run",ACTION_NOT_PENDING:"inspect-run",ACTION_NOT_RUNNING:"inspect-run",ACTION_TERMINAL:"inspect-run",CAPABILITY_REQUIRED:"correct-input",CHILD_DEPTH_LIMIT:"restore-definition",CHILD_MANAGED:"inspect-run",COMMAND_CONFLICT:"correct-input",COMMAND_DISPATCH_FAILED:"manual-review",COMMAND_NOT_FOUND:"inspect-run",COMMAND_REJECTED:"correct-input",COMMAND_VALIDATION_ERROR:"manual-review",COMMAND_VALIDATOR_UNAVAILABLE:"restore-definition",DECISION_CONFLICT:"inspect-run",DUPLICATE_COMMAND_VALIDATOR:"restore-definition",DUPLICATE_EVIDENCE_VALIDATOR:"restore-definition",DUPLICATE_EXECUTOR:"restore-definition",DUPLICATE_STATE_VALIDATOR:"restore-definition",DUPLICATE_TRANSITION_HANDLER:"restore-definition",DUPLICATE_VALIDATOR:"restore-definition",DUPLICATE_WORKFLOW:"restore-definition",EVIDENCE_INVALIDATION_UNAVAILABLE:"restore-definition",EVIDENCE_KIND_MISMATCH:"correct-input",EVIDENCE_REJECTED:"correct-input",EVIDENCE_STEP_CHANGED:"restore-definition",EVIDENCE_STILL_VALID:"inspect-run",EVIDENCE_VALIDATOR_UNAVAILABLE:"restore-definition",EVIDENCE_WAIT_NOT_FOUND:"inspect-run",EVIDENCE_WAIT_RESOLVED:"inspect-run",EXECUTION_UNKNOWN:"reconcile-execution",EXECUTOR_UNAVAILABLE:"restore-definition",EXECUTOR_UNSUPPORTED:"correct-input",INITIAL_STATE_CONFLICT:"correct-input",INITIAL_STATE_INVALID:"correct-input",INITIAL_STATE_REQUIRED:"correct-input",INVALID_ACTION:"correct-input",INVALID_COMMAND:"correct-input",INVALID_DECISION:"correct-input",INVALID_EVIDENCE:"correct-input",INVALID_JOIN:"correct-input",INVALID_JSON:"correct-input",INVALID_OUTCOME:"correct-input",INVALID_REQUEST:"correct-input",INVALID_RUN:"correct-input",INVALID_WORKFLOW:"correct-input",OUTCOME_ALREADY_RECORDED:"inspect-run",OUTCOME_CONFLICT:"inspect-outcome",OUTCOME_PROCESSING_ERROR:"inspect-outcome",OUTCOME_REJECTED:"inspect-outcome",OUTPUT_INVALID:"inspect-outcome",PROPOSAL_INPUT_MISSING:"correct-input",RECONCILIATION_REQUIRED:"reconcile-execution",REQUEST_ABORTED:"inspect-run",REVISION_CONFLICT:"inspect-run",RUN_CANCELLED:"inspect-run",RUN_CONFLICT:"correct-input",RUN_FAILED:"inspect-run",RUN_NOT_FOUND:"inspect-run",RUN_STATE_INVALID:"restore-definition",RUN_TERMINAL:"inspect-run",STALE_ACTION:"inspect-run",STALE_PROPOSAL:"review-proposal",STATE_VALIDATOR_UNAVAILABLE:"restore-definition",STORE_ATOMIC_PUBLICATION_UNSUPPORTED:"repair-storage",STORE_CHANGED_DIRECTORY:"repair-storage",STORE_CORRUPT_RECORD:"repair-storage",STORE_INVALID_ENTRY:"repair-storage",STORE_INVALID_REVISION:"repair-storage",STORE_INVALID_ROOT:"repair-storage",STORE_INVALID_RUN_ID:"repair-storage",STORE_MISSING_REVISION:"repair-storage",TRANSITION_HANDLER_UNAVAILABLE:"restore-definition",TRANSITION_STATE_INVALID:"restore-definition",TRANSITION_TARGET_INVALID:"restore-definition",TRANSITION_UNAVAILABLE:"restore-definition",UNSUPPORTED_PROTOCOL:"restore-definition",VALIDATOR_UNAVAILABLE:"restore-definition",WAIT_NOT_FOUND:"inspect-run",WORKFLOW_CHANGED:"restore-definition",WORKFLOW_UNAVAILABLE:"restore-definition"}),R=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.name="RuntimeProtocolError",this.recovery=Object.hasOwn(k_,r)?k_[r]:"manual-review"}code;recovery}});import{createHash as I1}from"node:crypto";import{types as x1}from"node:util";function mn(e){return Hw.has(e)}function pp(e,t=!0,r=!1,n=!1){let i=new Set,o=new WeakMap;function a(s,c){if(c>64)throw new R("INVALID_JSON","数据嵌套超过 64 层");if(s===null||typeof s=="string"||typeof s=="boolean")return r?JSON.stringify(s):s;if(typeof s=="number"&&Number.isFinite(s))return r?JSON.stringify(s):s===0?0:s;if(typeof s!="object"||s===null)throw new R("INVALID_JSON","数据必须能无损保存为 JSON");if(i.has(s))throw new R("INVALID_JSON","数据包含循环引用");if(x1.isProxy(s))throw new R("INVALID_JSON","仅接受无执行行为的 JSON 数据");let l=Hw.get(s);if(!t&&!r&&l!==void 0){if(c+l>64)throw new R("INVALID_JSON","数据嵌套超过 64 层");return o.set(s,{value:s,height:l}),s}let u=o.get(s);if(u){if(c+u.height>64)throw new R("INVALID_JSON","数据嵌套超过 64 层");return t?Ge(u.value):r?u.value:s}i.add(s);let f=0,d=h=>h&&typeof h=="object"?o.get(h)?.height??0:0,m=h=>(o.set(s,{value:h,height:f}),n&&(Object.freeze(s),Hw.set(s,f)),h);try{if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw new R("INVALID_JSON","数组不能包含空洞或额外属性");let v=[];for(let w=0;w<s.length;w+=1){let y=Object.getOwnPropertyDescriptor(s,String(w));if(!y||!("value"in y))throw new R("INVALID_JSON","数组元素必须是普通数据");let b=a(y.value,c+1);f=Math.max(f,1+d(y.value)),(t||r)&&v.push(b)}return m(r?`[${v.join(",")}]`:t?v:s)}let h=Object.getPrototypeOf(s);if(h!==Object.prototype&&h!==null)throw new R("INVALID_JSON","仅接受普通 JSON 对象");let p=[],g=Reflect.ownKeys(s);(t||r)&&g.sort((v,w)=>{let y=String(v),b=String(w),N=String(Number(y))===y&&Number.isInteger(Number(y))&&Number(y)>=0&&Number(y)<4294967295,A=String(Number(b))===b&&Number.isInteger(Number(b))&&Number(b)>=0&&Number(b)<4294967295;return N||A?N&&A?Number(y)-Number(b):N?-1:1:y<b?-1:y>b?1:0});for(let v of g){let w=Object.getOwnPropertyDescriptor(s,v);if(typeof v!="string"||!w.enumerable||!("value"in w))throw new R("INVALID_JSON","对象属性必须是可枚举的字符串数据属性");let y=a(w.value,c+1);f=Math.max(f,1+d(w.value)),(t||r)&&p.push([v,y])}return m(r?`{${p.map(([v,w])=>`${JSON.stringify(v)}:${w}`).join(",")}}`:t?Object.fromEntries(p):s)}finally{i.delete(s)}}return a(e,0)}function ri(e){return pp(e,!1,!0)}function ct(e){return pp(e)}function Ge(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(Ge(e[n]));return r}let t={};for(let r of Object.keys(e)){let n=Ge(e[r]);r==="__proto__"?Object.defineProperty(t,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):t[r]=n}return t}function hn(e){pp(e,!1)}function j(e){let t=e!==null&&typeof e=="object"&&mn(e),r=t?b_.get(e):void 0;if(r!==void 0)return r;let n=I1("sha256").update(ri(e)).digest("hex");return t&&b_.set(e,n),n}function ma(e){return pp(e,!1,!1,!0),e}var Hw,b_,kr=x(()=>{"use strict";pn();Hw=new WeakMap,b_=new WeakMap});function $t(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new R("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function ni(e){return mn(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function Qw(e,t,r){if(t!==e.attempt||r!==e.inputHash)throw new R("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Uw(e){return["succeeded","failed","cancelled"].includes(e.status)}function A_(e){return R_(e,e.input)}function R_(e,t,r){for(let a of["id","runId","stepId","type"])$t(e[a],a);e.ref!==void 0&&$t(e.ref,"ref");let n=e.attempt??1;if(!Number.isSafeInteger(n)||n<1)throw new R("INVALID_ACTION","attempt 必须是正安全整数");let i=e.retry??"manual";if(!["idempotent","reconcile","manual"].includes(i))throw new R("INVALID_ACTION","retry 策略无效");let o=e.requiredCapabilities??[];for(let a of o)$t(a,"requiredCapabilities");return{protocolVersion:1,id:e.id,runId:e.runId,stepId:e.stepId,type:e.type,...e.ref===void 0?{}:{ref:e.ref},attempt:n,input:t,inputHash:r??j(t),status:"pending",retry:i,requiredCapabilities:[...new Set(o)],receipts:[],reconciliations:[]}}function Jw(e,t){Qw(e,t.attempt,t.inputHash),$t(t.executorId,"executorId"),$t(t.token,"token"),t.sessionId!==void 0&&$t(t.sessionId,"sessionId");let r={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if(j(e.claim)===j(r)&&e.status==="running")return ni(e);throw new R("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new R("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...ni(e),claim:r,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function mp(e,t){if(t=hp(t),$t(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new R("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&$t(t.event,"event");let r=j(t),n=e.rejectedOutcomes?.find(o=>o.outcome.outcomeId===t.outcomeId);if(n)throw j(n.outcome)!==r?new R("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken"):new R(n.code,n.reason);let i=e.receipts.find(o=>o.outcomeId===t.outcomeId);if(i){if(i.hash!==r)throw new R("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken");return{action:ni(e),duplicate:!0}}if(Qw(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new R("STALE_ACTION","结果不属于当前 Action");if(Uw(e))throw new R("ACTION_TERMINAL","Action 已终止,不能接受新结果");if(!e.claim||!["running","unknown"].includes(e.status))throw new R("ACTION_NOT_RUNNING","Action 尚未交给执行者");if(t.claimToken!==e.claim.token)throw new R("STALE_ACTION","结果不属于当前执行者的领取记录");for(let o of t.artifacts??[])if($t(o.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(o.sha256))throw new R("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...ni(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:r}]},duplicate:!1}}function N_(e,t){if($t(t,"reason"),!["running","unknown"].includes(e.status))throw new R("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...ni(e),status:"unknown",reason:t}}function S_(e,t){if(e.rejectedOutcomes?.some(n=>n.outcome.attempt===e.attempt))throw new R("OUTCOME_ALREADY_RECORDED","当前执行尝试已记录结果,不能声明未执行并重试;请核对并修正同一次结果");if(!["failed","unknown"].includes(e.status))throw new R("ACTION_ACTIVE","仅失败或待核对的 Action 可以重试");if((e.retry!=="idempotent"||e.status==="unknown")&&!t)throw new R("RECONCILIATION_REQUIRED","先核对外部执行结果;不能把断连当作未执行");let r=ni(e);if(t){if(t.resolution!=="not-executed"||t.evidence===null)throw new R("RECONCILIATION_REQUIRED","需要明确的未执行结论与核对证据");r.reconciliations.push({attempt:e.attempt,resolution:"not-executed",evidence:ct(t.evidence)})}if(!Number.isSafeInteger(e.attempt+1))throw new R("INVALID_ACTION","执行尝试次数溢出");return r.attempt+=1,r.status="pending",delete r.claim,delete r.executionOrigin,delete r.executionStop,delete r.cancellation,delete r.outcome,delete r.reason,r}function Jl(e,t){return $t(t,"reason"),Uw(e)?ni(e):{...ni(e),status:"cancelled",reason:t}}function E_(e,t){Dn(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let r of["actionId","inputHash","claimToken","evidence"])$t(t[r],r);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new R("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(Qw(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new R("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function zw(e,t){if(E_(e,t),e.status!=="cancelled")throw new R("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&j(e.cancellation)!==j(t))throw new R("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...ni(e),cancellation:structuredClone(t)}}function Kw(e,t){if(E_(e,t),!Uw(e))throw new R("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&j(e.executionStop)!==j(t))throw new R("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...ni(e),executionStop:structuredClone(t)}}function Dn(e,t,r="INVALID_ACTION"){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(n=>!t.includes(n)))throw new R(r,"执行记录包含无效结构或未知字段")}function hp(e){let t=ct(e),r=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(Dn(t,[...r,"artifacts","summary","event"],"INVALID_OUTCOME"),r.some(n=>!Object.hasOwn(t,n)))throw new R("INVALID_OUTCOME","执行结果缺少身份、绑定或 output 字段");for(let n of["actionId","inputHash","claimToken","outcomeId"])if(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096)throw new R("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(typeof t.attempt!="number"||!Number.isSafeInteger(t.attempt)||t.attempt<1)throw new R("INVALID_OUTCOME","attempt 必须是正安全整数");if(t.status!=="succeeded"&&t.status!=="failed")throw new R("INVALID_OUTCOME","status 必须是 succeeded 或 failed");for(let n of["summary","event"])if(t[n]!==void 0&&(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096))throw new R("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(t.artifacts!==void 0){if(!Array.isArray(t.artifacts))throw new R("INVALID_OUTCOME","产物引用必须是数组");for(let n of t.artifacts)if(Dn(n,["uri","sha256"],"INVALID_OUTCOME"),typeof n.uri!="string"||!n.uri.trim()||typeof n.sha256!="string"||!/^[a-f0-9]{64}$/.test(n.sha256))throw new R("INVALID_OUTCOME","产物引用必须包含 URI 与 SHA-256")}return t}function C_(e){return Gw(ct(e))}function Gw(e,t){if(Dn(e,["protocolVersion","id","runId","stepId","type","ref","attempt","input","inputHash","status","retry","requiredCapabilities","claim","outcome","receipts","rejectedOutcomes","reconciliations","reason","cancellation","executionOrigin","executionStop"]),e.protocolVersion!==1)throw new R("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Action 协议版本");if(!Array.isArray(e.requiredCapabilities)||!Array.isArray(e.receipts)||!Array.isArray(e.reconciliations))throw new R("INVALID_ACTION","Action 缺少能力、结果或核对记录");let r=e,n=R_(r,r.input,t);if(r.inputHash!==n.inputHash||r.retry!==n.retry||r.attempt!==n.attempt)throw new R("INVALID_ACTION","Action 输入绑定或执行参数不完整");if(!["pending","running","unknown","succeeded","failed","cancelled"].includes(r.status))throw new R("INVALID_ACTION","Action 状态无效");if(r.reason!==void 0&&$t(r.reason,"reason"),r.claim!==void 0&&(Dn(r.claim,["executorId","sessionId","token"]),$t(r.claim.executorId,"executorId"),$t(r.claim.token,"token"),r.claim.sessionId!==void 0&&$t(r.claim.sessionId,"sessionId")),r.status==="pending"&&r.claim||["running","unknown","succeeded","failed"].includes(r.status)&&!r.claim)throw new R("INVALID_ACTION","Action 状态与执行归属不一致");if(r.executionOrigin!==void 0&&(Dn(r.executionOrigin,["workflow"]),Dn(r.executionOrigin.workflow,["id","version","hash"]),$t(r.executionOrigin.workflow.id,"executionOrigin.workflow.id"),$t(r.executionOrigin.workflow.version,"executionOrigin.workflow.version"),!r.claim||!/^[a-f0-9]{64}$/u.test(r.executionOrigin.workflow.hash)))throw new R("INVALID_ACTION","执行来源必须包含领取记录和有效工作流摘要");r.cancellation!==void 0&&zw({...r,input:null},r.cancellation),r.executionStop!==void 0&&Kw({...r,input:null},r.executionStop);let i=new Set;for(let a of r.receipts){if(Dn(a,["outcomeId","hash"]),$t(a.outcomeId,"outcomeId"),!/^[a-f0-9]{64}$/.test(a.hash)||i.has(a.outcomeId))throw new R("INVALID_ACTION","结果记录的标识或摘要无效");i.add(a.outcomeId)}if(r.rejectedOutcomes!==void 0){if(!Array.isArray(r.rejectedOutcomes))throw new R("INVALID_ACTION","Action 的拒绝结果记录必须是数组");let a=new Set;for(let s of r.rejectedOutcomes){if(Dn(s,["outcome","code","reason"]),!["OUTPUT_INVALID","OUTCOME_REJECTED","OUTCOME_PROCESSING_ERROR"].includes(s.code))throw new R("INVALID_ACTION","Action 的拒绝结果代码无效");if(typeof s.reason!="string"||!s.reason.trim())throw new R("INVALID_ACTION","Action 的拒绝结果缺少原因");let c=hp(s.outcome),l=r.receipts.find(u=>u.outcomeId===c.outcomeId);if(a.has(c.outcomeId)||!l||l.hash!==j(c)||c.actionId!==r.id||c.inputHash!==r.inputHash||c.attempt>r.attempt||c.attempt===r.attempt&&r.claim?.token!==c.claimToken)throw new R("INVALID_ACTION","Action 的拒绝结果与当前执行记录不一致");a.add(c.outcomeId)}}let o=new Set;for(let a of r.reconciliations){if(Dn(a,["attempt","resolution","evidence"]),!Number.isSafeInteger(a.attempt)||a.attempt<1||a.attempt>=r.attempt||o.has(a.attempt)||a.resolution!=="not-executed"||a.evidence===null||a.evidence===void 0)throw new R("INVALID_ACTION","核对记录与执行尝试不一致");o.add(a.attempt)}if(r.status==="succeeded"||r.status==="failed"){if(Dn(r.outcome,["actionId","attempt","inputHash","claimToken","outcomeId","status","output","artifacts","summary","event"]),r.outcome.status!==r.status||r.outcome.output===void 0)throw new R("INVALID_ACTION","终态 Action 缺少匹配的结果");let a=r.receipts.find(s=>s.outcomeId===r.outcome.outcomeId);if(!a||a.hash!==j(r.outcome))throw new R("INVALID_ACTION","终态结果与已接受摘要不一致");mp({...r,input:null,status:"running",receipts:[]},r.outcome)}else if(r.outcome!==void 0)throw new R("INVALID_ACTION","非执行终态不能保存当前执行结果");return r}var ha=x(()=>{"use strict";pn();kr()});import{types as P1}from"node:util";import{createHash as O1}from"node:crypto";function x_(e,t){let r=e!==null&&typeof e=="object"&&t?.(e);if(r){let i=I_.get(e);if(i!==void 0)return i}let n=JSON.stringify(e);return r&&n.length<=64*1024&&I_.set(e,n),n}function T1(e,t,r){let n=new WeakMap,i=v=>{let w=n.get(v);if(w)return w;let y=Array.isArray(v)?[...v]:{...v};return n.set(v,y),y},o=i(e),a=[],s=[],c=[],l=new Map,u=new Map,f=new WeakMap,d=new Map,m=new Map,h=new Map,p=v=>{let w=v&&typeof v=="object"?f.get(v):void 0;if(w!==void 0)return w;let y=x_(v,r);return w=l.get(y),w===void 0&&(w=a.length,a.push(v),l.set(y,w)),v&&typeof v=="object"&&f.set(v,w),w},g=v=>{let w=h.get(v);if(w!==void 0)return w;let y=v.base===void 0?void 0:g(v.base),b=s.length;return s.push({...y===void 0?{}:{base:y},entries:v.entries.map(([N,A])=>[N,p(A)]),removed:[...v.removed]}),h.set(v,b),b};for(let v of t){let w=o,y=e;for(let Q of v.path.slice(0,-1)){y=y[Q];let F=i(y);Object.defineProperty(w,Q,{value:F,enumerable:!0,writable:!0,configurable:!0}),w=F}let b=v.path.at(-1),N=w[b];if(!N||typeof N!="object"||Array.isArray(N))continue;if(r?.(N)){let Q=__.get(N);if(!Q){let F=N,K=m.get(v.group),Z=Object.entries(F),re=K?Z.filter(([Be,B])=>!Object.hasOwn(K.source,Be)||p(K.source[Be])!==p(B)):Z,X=K?Object.keys(K.source).filter(Be=>!Object.hasOwn(F,Be)):[],Oe=K&&re.length+X.length<Z.length;Q={...Oe?{base:K.node}:{},entries:Oe?re:Z,removed:Oe?X:[]},__.set(N,Q)}m.set(v.group,{source:N,node:Q}),c.push({path:v.path,map:g(Q)}),Object.defineProperty(w,b,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let A=new Map;for(let[Q,F]of Object.entries(N)){let K=F&&typeof F=="object"?f.get(F):void 0;if(K===void 0){let Z=x_(F,r);K=l.get(Z),K===void 0&&(K=a.length,a.push(F),l.set(Z,K)),F&&typeof F=="object"&&f.set(F,K)}A.set(Q,K)}let S=JSON.stringify([...A]),_=u.get(S);if(_===void 0){let Q=d.get(v.group),F=[...A].filter(([re,X])=>Q?.entries.get(re)!==X),K=Q?[...Q.entries.keys()].filter(re=>!A.has(re)):[],Z=Q&&F.length+K.length<A.size;_=s.length,s.push({...Z?{base:Q.id}:{},entries:Z?F:[...A],removed:Z?K:[]}),u.set(S,_)}d.set(v.group,{id:_,entries:A}),c.push({path:v.path,map:_}),Object.defineProperty(w,b,{value:{},enumerable:!0,writable:!0,configurable:!0})}return c.length?{record:o,pool:{version:1,values:a,maps:s,bindings:c}}:{record:o}}function j1(){let e=[],t=o=>o===null?0:e[o].height,r=(o,a,s,c)=>{let l=e.length;return e.push({key:o,value:a,left:s,right:c,height:1+Math.max(t(s),t(c))}),l},n=(o,a,s,c)=>{if(t(s)>t(c)+1){let l=e[s];if(t(l.left)>=t(l.right))return r(l.key,l.value,l.left,r(o,a,l.right,c));let u=e[l.right];return r(u.key,u.value,r(l.key,l.value,l.left,u.left),r(o,a,u.right,c))}if(t(c)>t(s)+1){let l=e[c];if(t(l.right)>=t(l.left))return r(l.key,l.value,r(o,a,s,l.left),l.right);let u=e[l.left];return r(u.key,u.value,r(o,a,s,u.left),r(l.key,l.value,u.right,l.right))}return r(o,a,s,c)},i=(o,a,s)=>{if(o===null)return s===void 0?null:r(a,s,null,null);let c=e[o];if(a<c.key){let u=i(c.left,a,s);return u===c.left?o:n(c.key,c.value,u,c.right)}if(a>c.key){let u=i(c.right,a,s);return u===c.right?o:n(c.key,c.value,c.left,u)}if(s!==void 0)return s===c.value?o:r(a,s,c.left,c.right);if(c.left===null)return c.right;if(c.right===null)return c.left;let l=e[c.right];for(;l.left!==null;)l=e[l.left];return n(l.key,l.value,c.left,i(c.right,l.key,void 0))};return{nodes:e,set:i}}function O_(e){let{nodes:t,set:r}=j1(),n=[];for(let c of e.maps){let l=c.base===void 0?null:n[c.base];for(let u of c.removed)l=r(l,u,void 0);for(let[u,f]of c.entries)l=r(l,u,f);n.push(l)}let i=[],o=new Map,a=c=>{if(c===null)return null;let l=o.get(c);if(l!==void 0)return l;let u=t[c],f=a(u.left),d=a(u.right),m=i.length;return i.push({...u,left:f,right:d}),o.set(c,m),m},s=n.map(a);return{version:3,values:e.values,nodes:i,maps:s,bindings:e.bindings}}function T_(e,t,r){let n=T1(e,t,r);return{record:n.record,...n.pool?{pool:O_(n.pool)}:{}}}function*gp(e,t=e.root){if(t===null)return;let r=e.pool.nodes[t];yield*gp(e,r.left),yield[r.key,e.pool.values[r.value]],yield*gp(e,r.right)}function $1(e){let t=n=>{let i=e.root;for(;i!==null;){let o=e.pool.nodes[i];if(n===o.key)return o.value;i=n<o.key?o.left:o.right}},r=new Proxy({},{ownKeys:()=>[...gp(e)].map(([n])=>n),get:(n,i)=>typeof i=="string"?e.pool.values[t(i)??-1]:void 0,has:(n,i)=>typeof i=="string"&&t(i)!==void 0,getOwnPropertyDescriptor:(n,i)=>typeof i=="string"&&t(i)!==void 0?{value:e.pool.values[t(i)],enumerable:!0,configurable:!0,writable:!1}:void 0,set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1});return xi.set(r,e),r}function j_(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return gt("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(o=>!["version","values","maps","bindings"].includes(o))&&gt("JSON 引用池字段无效"),i.maps.forEach((o,a)=>{(!o||!Array.isArray(o.entries)||!Array.isArray(o.removed)||o.base!==void 0&&!Ts(o.base,a)||Object.keys(o).some(c=>!["base","entries","removed"].includes(c)))&&gt("JSON 映射引用无效");let s=new Set;for(let c of o.removed)(typeof c!="string"||s.has(c))&&gt("JSON 删除键无效"),s.add(c);for(let c of o.entries)(!Array.isArray(c)||c.length!==2||typeof c[0]!="string"||!Ts(c[1],i.values.length)||s.has(c[0]))&&gt("JSON 值引用无效"),s.add(c[0])}),j_(O_(i))}let r=e;if(r.version!==3||!Array.isArray(r.nodes)||Object.keys(r).some(i=>!["version","values","maps","bindings","nodes"].includes(i)))return gt("JSON 引用池版本或字段无效");let n=[];return r.nodes.forEach((i,o)=>{(!i||typeof i.key!="string"||!Ts(i.value,r.values.length)||![i.left,i.right].every(c=>c===null||Ts(c,o))||Object.keys(i).some(c=>!["key","value","left","right","height"].includes(c)))&&gt("JSON 树引用无效");let a=i.left===null?void 0:r.nodes[i.left],s=i.right===null?void 0:r.nodes[i.right];(i.height!==1+Math.max(a?.height??0,s?.height??0)||Math.abs((a?.height??0)-(s?.height??0))>1||i.left!==null&&n[i.left].max>=i.key||i.right!==null&&n[i.right].min<=i.key)&&gt("JSON 树顺序或平衡无效"),n.push({min:i.left===null?i.key:n[i.left].min,max:i.right===null?i.key:n[i.right].max})}),r.maps.some(i=>i!==null&&!Ts(i,r.nodes.length))&&gt("JSON 映射根无效"),r}function D1(e,t){let r=(h,p=0,g=new Set)=>{if(p>64&&gt("JSON 数据嵌套过深"),!(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"&&Number.isFinite(h))){if(typeof h!="object"||h===null||P1.isProxy(h)||g.has(h))return gt("JSON 数据无效");Object.getPrototypeOf(h)!==Object.prototype&&Object.getPrototypeOf(h)!==null&&!Array.isArray(h)&&gt("JSON 数据必须为普通对象"),g.add(h);for(let v of Reflect.ownKeys(h)){if(Array.isArray(h)&&v==="length")continue;let w=Object.getOwnPropertyDescriptor(h,v);(typeof v!="string"||!w.enumerable||!("value"in w))&&gt("JSON 数据不能包含访问器"),r(w.value,p+1,g)}Array.isArray(h)&&Object.keys(h).length!==h.length&&gt("JSON 数组不能稀疏"),g.delete(h)}};r(e),r(t);let n=j_(structuredClone(t)),i=structuredClone(e),o={validatedNodes:n.nodes.length,validationActions:0,validationResultMaps:0,validationEntries:0,validationMaterializedEntries:0,materializedMaps:0,materializedEntries:0,hashBytes:0,logicalHashBytes:0},a=new Set,s=new Set,c=new Set,l=new Map;for(let h of n.bindings){(!h||!Array.isArray(h.path)||h.path.length<1||h.path.length>16||h.path.some(w=>typeof w!="string"||["__proto__","constructor","prototype"].includes(w))||!Ts(h.map,n.maps.length)||Object.keys(h).some(w=>!["path","map"].includes(w)))&&gt("JSON 池绑定无效");let p=JSON.stringify(h.path);(s.has(p)||h.path.some((w,y)=>a.has(JSON.stringify(h.path.slice(0,y+1)))))&&gt("JSON 池绑定重复或重叠"),a.add(p),h.path.forEach((w,y)=>s.add(JSON.stringify(h.path.slice(0,y+1))));let g=i;for(let w of h.path.slice(0,-1))(!g||typeof g!="object"||!Object.hasOwn(g,w))&&gt("JSON 池绑定缺失"),g=g[w];let v=h.path.at(-1);(!g||!Object.hasOwn(g,v)||!g[v]||typeof g[v]!="object"||Array.isArray(g[v])||Object.keys(g[v]).length)&&gt("JSON 池绑定必须替换空对象"),Object.defineProperty(g,v,{value:$1({pool:n,root:n.maps[h.map],stats:o,checked:c,origins:l}),enumerable:!0,writable:!0,configurable:!0})}let u=new WeakMap,f=new Map,d=h=>{if(!h||typeof h!="object")return 0;let p=u.get(h);if(p!==void 0)return p;let g=xi.get(h),v=y=>{if(y===null)return 0;let b=f.get(y);if(b!==void 0)return b;let N=n.nodes[y],A=Math.max(1+d(n.values[N.value]),v(N.left),v(N.right));return f.set(y,A),A},w=g?v(g.root):Object.values(h).reduce((y,b)=>Math.max(y,1+d(b)),0);return u.set(h,w),w};d(i)>64&&gt("JSON 逻辑数据嵌套超过 64 层"),Kl(n),Kl(i);let m=h=>{if(!(!h||typeof h!="object"||xi.has(h)||zl.has(h))){zl.set(h,o);for(let p of Object.values(h))m(p)}};return m(i),{value:i,stats:o,materialize:(h=[])=>br(h.reduce((p,g)=>p?.[g],i)),hash:()=>Bn(i)}}function Kl(e){let t=new WeakSet,r=n=>{if(!(!n||typeof n!="object"||xi.has(n)||t.has(n))){t.add(n);for(let i of Object.values(n))r(i);Object.freeze(n)}};return r(e),e}function br(e){if(e===null||typeof e!="object")return e;let t=xi.get(e);if(t){t.stats.materializedMaps++;let r=[...gp(t)];return t.stats.materializedEntries+=r.length,Object.fromEntries(r.map(([n,i])=>[n,br(i)]))}return Array.isArray(e)?e.map(br):Object.fromEntries(Object.entries(e).map(([r,n])=>[r,br(n)]))}function vp(e,t){let r=xi.get(e);if(!r){for(let[i,o]of Object.entries(e))t(i,o);return}r.stats.validationResultMaps++;let n=i=>{if(i===null||r.checked.has(i))return;let o=r.pool.nodes[i];n(o.left),t(o.key,r.pool.values[o.value]),r.stats.validationEntries++,n(o.right),r.checked.add(i)};n(r.root)}function wp(e,t,r){let n=xi.get(e),i=(s,c)=>{let l=c.sequence;return t.get(l)!==s&&gt("WorkflowRun 结果来源不一致"),l};if(!n){for(let[s,c]of Object.entries(e))i(s,c)>=r&&gt("WorkflowRun 结果序号无效");return}let o=n.origins.get(t);o||(o=new Map,n.origins.set(t,o));let a=s=>{if(s===null)return 0;let c=o.get(s);if(c!==void 0)return c;let l=n.pool.nodes[s],u=Math.max(i(l.key,n.pool.values[l.value]),a(l.left),a(l.right));return o.set(s,u),u};a(n.root)>=r&&gt("WorkflowRun 结果序号无效")}function B1(e){return Object.keys(e).sort((t,r)=>{let n=i=>String(Number(i))===i&&Number.isInteger(Number(i))&&Number(i)>=0&&Number(i)<4294967295;return n(t)||n(r)?n(t)&&n(r)?Number(t)-Number(r):n(t)?-1:1:t<r?-1:t>r?1:0})}function Bn(e,t={}){let r=O1("sha256"),n=e&&typeof e=="object"?zl.get(e):void 0,i=l=>{if(!l||typeof l!="object")return;let u=xi.get(l)?.stats??zl.get(l);if(u)return u;for(let f of Object.values(l)){let d=i(f);if(d)return d}};n??=i(e);let o=n&&t.cachePrefixes!==!1?P_.get(n):void 0;n&&!o&&t.cachePrefixes!==!1&&(o={root:{hash:r.copy(),next:new Map},size:0},P_.set(n,o));let a=o?.root,s=l=>{let u=Buffer.byteLength(l);n&&(n.logicalHashBytes+=u);let f=a?.next.get(l);if(f){r=f.hash.copy(),a=f;return}if(r.update(l),n&&(n.hashBytes+=u),a&&o&&o.size<1e5){let d={hash:r.copy(),next:new Map};a.next.set(l,d),a=d,o.size++}else a=void 0},c=l=>{if(l===null||typeof l!="object"){s(JSON.stringify(l));return}if(Array.isArray(l)){s("["),l.forEach((u,f)=>{f&&s(","),c(u)}),s("]");return}s("{"),B1(l).forEach((u,f)=>{f&&s(","),s(JSON.stringify(u)+":"),c(l[u])}),s("}")};return c(e),r.digest("hex")}function Gl(e){return zl.get(e)??xi.get(e)?.stats}function yp(e,t,r=!0){let n=D1(e,t);return r?n.materialize():n.value}var __,I_,xi,zl,gt,Ts,P_,ga=x(()=>{"use strict";__=new WeakMap,I_=new WeakMap;xi=new WeakMap,zl=new WeakMap;gt=e=>{throw new Error(e)},Ts=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;P_=new WeakMap});function Yw(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function se(e){throw new R("INVALID_RUN",e)}function _t(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&se(`${t} 必须是 JSON 对象`),e}function gn(e,t,r){for(let n of Object.keys(e))t.includes(n)||se(`${r} 包含不支持的字段:${n}`)}function Ye(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&se(`${t} 必须是非空字符串且不超过 4096 字符`),e}function js(e,t,r=0){return(!Number.isSafeInteger(e)||e<r)&&se(`${t} 必须是大于等于 ${r} 的安全整数`),e}function No(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&se(`${t} 必须是 SHA-256 摘要`),e}function D_(e,t,r=!1){let n=_t(e,t);gn(n,r?["id","version","hash"]:["id","version"],t);let i={id:Ye(n.id,`${t}.id`),version:Ye(n.version,`${t}.version`)};return r&&(i.hash=No(n.hash,`${t}.hash`)),i}function Yl(e,t,r){let n=_t(e,t);if(!r&&mn(n)&&L_.has(n))return n;let i=(o,a)=>{Ye(o,`${t} step id`);let s=_t(a,`${t}.${o}`);gn(s,["sequence","value"],`${t}.${o}`),(!Object.hasOwn(s,"sequence")||!Object.hasOwn(s,"value"))&&se(`${t}.${o} 缺少 sequence 或 value`),js(s.sequence,`${t}.${o}.sequence`,1)};if(r)r.visitResults(n,i);else for(let[o,a]of Object.entries(n))i(o,a);return n}function B_(e,t,r){let n=_t(e,t);return gn(n,["from","to","results","activation"],t),(!Object.hasOwn(n,"from")||!Object.hasOwn(n,"to")||!Object.hasOwn(n,"results"))&&se(`${t} 缺少 from、to 或 results`),{from:n.from===null?null:Ye(n.from,`${t}.from`),to:Ye(n.to,`${t}.to`),results:Yl(n.results,`${t}.results`,r),...Object.hasOwn(n,"activation")?{activation:n.activation}:{}}}function kp(e,t,r,n){let i=`${t}:`;e.startsWith(i)||se(`${r} 不属于当前 Run`);let o=e.slice(i.length);/^[1-9][0-9]*$/.test(o)||se(`${r} 的步骤序号无效`);let a=Number(o);return(!Number.isSafeInteger(a)||a>n)&&se(`${r} 的步骤序号超出 Run 范围`),a}function W1(e,t,r,n){let i=_t(e,"Wait");gn(i,["id","stepId","sequence","status","proposal","proposalHash","choices","results","decision"],"Wait");for(let f of["id","stepId","sequence","status","proposal","proposalHash","choices","results"])Object.hasOwn(i,f)||se(`Wait 缺少 ${f}`);let o=Ye(i.id,"Wait.id"),a=Ye(i.stepId,"Wait.stepId"),s=js(i.sequence,"Wait.sequence",1);(s>r||kp(o,t,"Wait.id",r)!==s)&&se("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||se("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&se("Wait.choices 必须是非空数组");let c=i.choices.map(f=>Ye(f,"Wait.choices"));new Set(c).size!==c.length&&se("Wait.choices 不能重复");let l=No(i.proposalHash,"Wait.proposalHash");j(i.proposal)!==l&&se("Wait.proposal 与 proposalHash 不一致");let u={id:o,stepId:a,sequence:s,status:i.status,proposal:i.proposal,proposalHash:l,choices:c,results:Yl(i.results,"Wait.results",n)};if(i.decision!==void 0){let f=_t(i.decision,"Wait.decision");gn(f,["id","choice","proposalHash","reason"],"Wait.decision"),f.reason!==void 0&&!Yw(f.reason)&&se("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let d={id:Ye(f.id,"Wait.decision.id"),choice:Ye(f.choice,"Wait.decision.choice"),proposalHash:No(f.proposalHash,"Wait.decision.proposalHash"),...f.reason===void 0?{}:{reason:f.reason}};(i.status!=="resolved"||!c.includes(d.choice)||d.proposalHash!==l)&&se("Wait.decision 与 Wait 状态、选择或提案不一致"),u.decision=d}else i.status==="resolved"&&se("已解决的 Wait 必须保存对应 decision");return u}function L1(e,t,r,n){let i=_t(e,"EvidenceWait");gn(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let o=Ye(i.id,"EvidenceWait.id"),a=js(i.sequence,"EvidenceWait.sequence",1);(a>r||kp(o,t,"EvidenceWait.id",r)!==a)&&se("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||se("EvidenceWait.status 无效");let s={id:o,stepId:Ye(i.stepId,"EvidenceWait.stepId"),sequence:a,kind:Ye(i.kind,"EvidenceWait.kind"),status:i.status,results:Yl(i.results,"EvidenceWait.results",n)};if(i.receipt!==void 0){let c=_t(i.receipt,"EvidenceWait.receipt");gn(c,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),s.receipt={ref:Ye(c.ref,"EvidenceWait.receipt.ref"),contentHash:No(c.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:Ye(c.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let c=_t(i.invalidation,"EvidenceWait.invalidation");gn(c,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),s.invalidation={ref:Ye(c.ref,"EvidenceWait.invalidation.ref"),contentHash:No(c.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:Ye(c.submissionId,"EvidenceWait.invalidation.submissionId"),reason:Ye(c.reason,"EvidenceWait.invalidation.reason")}}return(s.status==="resolved"!=!!s.receipt||s.status==="invalidated"!=!!s.invalidation)&&se("EvidenceWait.receipt 与状态不一致"),s}function vn(e,t){let r=_t(ct(e),"WorkflowRun");return Rp(r,t)}function q_(e,t){if(e&&typeof e=="object"&&Xw.has(e)&&mn(e)){let r=e;return t!==void 0&&r.runId!==t&&se("WorkflowRun.runId 与存储键不一致"),r}return hn(e),V_(Rp(_t(structuredClone(e),"WorkflowRun"),t))}function bp(e,t,r){return Rp(_t(e,"WorkflowRun"),t,void 0,r)}function Ap(e,t){return hn(e),Rp(_t(e,"WorkflowRun"),e.runId,t&&Xw.has(t)&&mn(t)?t:void 0),V_(e)}function V_(e){ma(e),Xw.add(e);for(let r of e.actions)W_.add(r);let t=r=>L_.add(r);for(let r of Object.values(e.actionContexts))t(r.results);for(let r of e.waits)t(r.results);for(let r of e.evidenceWaits??[])t(r.results);for(let r of e.ready)t(r.results);for(let r of Object.values(e.joins))for(let n of Object.values(r))for(let i of n)t(i.results);return t(e.outputs),e}function Rp(e,t,r,n){gn(e,$_,"WorkflowRun");for(let B of $_.filter(ie=>ie!=="reason"&&ie!=="state"&&ie!=="evidenceWaits"&&ie!=="initialStateHash"&&ie!=="commands"))Object.hasOwn(e,B)||se(`WorkflowRun 缺少 ${B}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new R("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=Ye(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&se("WorkflowRun.runId 与存储键不一致");let o=js(e.revision,"WorkflowRun.revision",1),a=js(e.sequence,"WorkflowRun.sequence"),s=D_(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||se("WorkflowRun.status 无效"),e.reason!==void 0&&Ye(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||se("WorkflowRun 缺少 input");let c=_t(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(c).length===0&&se("WorkflowRun.definitionHashes 不能为空");for(let[B,ie]of Object.entries(c)){let pe;try{pe=JSON.parse(B)}catch{se("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(pe)||pe.length!==2||typeof pe[0]!="string"||typeof pe[1]!="string"||JSON.stringify(pe)!==B)&&se("WorkflowRun.definitionHashes 包含非规范的工作流引用"),No(ie,`WorkflowRun.definitionHashes.${B}`)}let l=JSON.stringify([s.id,s.version]);c[l]!==s.hash&&se("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&se("WorkflowRun.lineage 必须是最多 32 层的数组");let u=e.lineage.map(B=>Ye(B,"WorkflowRun.lineage"));(new Set(u).size!==u.length||u.includes(i))&&se("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&se("WorkflowRun.actions 和 waits 必须是数组");let f=e.actions.map(B=>{let ie;try{ie=B&&typeof B=="object"&&W_.has(B)&&mn(B)?B:Gw(B,n?.hash(B.input))}catch(pe){if(pe instanceof R&&pe.code==="UNSUPPORTED_PROTOCOL")throw pe;se(`WorkflowRun.actions 包含无效 Action:${pe.message}`)}return ie.executionOrigin&&ie.executionOrigin.workflow.id!==s.id&&se("Action 执行来源不属于当前工作流"),ie.runId!==i&&se(`Action ${ie.id} 不属于当前 Run`),new Set(ie.requiredCapabilities).size!==ie.requiredCapabilities.length&&se(`Action ${ie.id} 的 requiredCapabilities 不能重复`),ie}),d=new Map(f.map(B=>[B.id,B]));e.commands!==void 0&&!Array.isArray(e.commands)&&se("WorkflowRun.commands 必须是数组");let m=e.commands?.map(B=>{let ie=_t(B,"WorkflowRun.commands item");gn(ie,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let pe={id:Ye(ie.id,"WorkflowRun.commands.id"),name:Ye(ie.name,"WorkflowRun.commands.name"),inputHash:No(ie.inputHash,"WorkflowRun.commands.inputHash"),actionId:Ye(ie.actionId,"WorkflowRun.commands.actionId")};return d.has(pe.actionId)||se("WorkflowRun.commands 指向不存在的 Action"),pe});m&&new Set(m.map(B=>B.id)).size!==m.length&&se("WorkflowRun.commands 标识不能重复");let h=e.waits.map(B=>W1(B,i,a,n));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&se("WorkflowRun.evidenceWaits 必须是数组");let p=e.evidenceWaits?.map(B=>L1(B,i,a,n))??[],g=new Map;for(let B of f){let ie=kp(B.id,i,"Action.id",a);g.has(ie)&&se("WorkflowRun 的步骤序号不能重复"),g.set(ie,B.stepId)}for(let B of h)g.has(B.sequence)&&se("WorkflowRun 的步骤序号不能重复"),g.set(B.sequence,B.stepId);for(let B of p)g.has(B.sequence)&&se("WorkflowRun 的步骤序号不能重复"),g.set(B.sequence,B.stepId);g.size!==a&&se("WorkflowRun.sequence 与已激活步骤数量不一致");let v=_t(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(v).length!==f.length&&se("WorkflowRun.actionContexts 必须与 actions 一一对应");let w=new Map,y=r?new Map([...r.actions.map(B=>[r.actionContexts[B.id].sequence,B.stepId]),...r.waits.map(B=>[B.sequence,B.stepId]),...(r.evidenceWaits??[]).map(B=>[B.sequence,B.stepId])]):void 0;if(r&&y&&r.runId===i&&[...y].every(([B,ie])=>g.get(B)===ie)){let B=(ie,pe)=>w.set(ie,Math.min(w.get(ie)??1/0,pe));for(let ie of Object.values(r.actionContexts))B(ie.results,ie.sequence);for(let ie of r.waits)B(ie.results,ie.sequence);for(let ie of r.evidenceWaits??[])B(ie.results,ie.sequence);for(let ie of r.ready)B(ie.results,r.sequence+1);for(let ie of Object.values(r.joins))for(let pe of Object.values(ie))for(let it of pe)B(it.results,r.sequence+1);B(r.outputs,r.sequence+1)}let b=new Map;function N(B,ie){let pe=ie??a+1;if(n){n.validateOrigins(B,g,pe);return}let it=w.get(B);if(!(it!==void 0&&pe>=it&&mn(B))&&!((b.get(B)??1/0)<=pe)){b.set(B,pe);for(let[I,E]of Object.entries(B))(E.sequence>=(ie??a+1)||g.get(E.sequence)!==I)&&se(`WorkflowRun 结果 ${I} 的序号或来源不一致`)}}for(let B of f){Object.hasOwn(v,B.id)||se(`Action ${B.id} 缺少上下文`);let ie=_t(v[B.id],`actionContexts.${B.id}`);gn(ie,["sequence","results"],`actionContexts.${B.id}`);let pe=js(ie.sequence,`actionContexts.${B.id}.sequence`,1);pe!==kp(B.id,i,"Action.id",a)&&se(`Action ${B.id} 的上下文序号不一致`);let it=Yl(ie.results,`actionContexts.${B.id}.results`,n);N(it,pe)}for(let B of h)N(B.results,B.sequence);for(let B of p)N(B.results,B.sequence);Array.isArray(e.ready)||se("WorkflowRun.ready 必须是数组");let A=e.ready.map(B=>B_(B,"WorkflowRun.ready token",n));for(let B of A)N(B.results);let S=_t(e.joins,"WorkflowRun.joins"),_=Object.fromEntries(Object.entries(S).map(([B,ie])=>{Ye(B,"WorkflowRun.joins step id");let pe=_t(ie,`WorkflowRun.joins.${B}`),it=Object.fromEntries(Object.entries(pe).map(([I,E])=>{Ye(I,"WorkflowRun.joins parent id"),Array.isArray(E)||se(`WorkflowRun.joins.${B}.${I} 必须是数组`);let P=E.map(W=>{let M=B_(W,`WorkflowRun.joins.${B}.${I}`,n);return(M.to!==B||M.from!==I)&&se(`WorkflowRun.joins.${B}.${I} 包含错误来源的 token`),N(M.results),M});return[I,P]}));return[B,it]})),Q=Yl(e.outputs,"WorkflowRun.outputs",n);N(Q),Array.isArray(e.children)||se("WorkflowRun.children 必须是数组");let F=e.children.map(B=>{let ie=_t(B,"WorkflowRun.children item");gn(ie,["actionId","runId","workflow"],"WorkflowRun.children item");let pe=D_(ie.workflow,"WorkflowRun.children.workflow"),it=Ye(ie.actionId,"WorkflowRun.children.actionId"),I=Ye(ie.runId,"WorkflowRun.children.runId"),E=d.get(it);return(!E||E.type!=="child_workflow"||E.ref!==`${pe.id}@${pe.version}`||I!==`child-${j(it)}`||!Object.hasOwn(c,JSON.stringify([pe.id,pe.version])))&&se("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:it,runId:I,workflow:pe}});(new Set(F.map(B=>B.actionId)).size!==F.length||f.filter(B=>B.type==="child_workflow").length!==F.length)&&se("每个子工作流 Action 必须恰好对应一个 Child Run");let Z=f.some(B=>["pending","running","unknown"].includes(B.status)),re=h.some(B=>B.status==="pending"),X=p.some(B=>B.status==="pending"),Oe=Object.values(_).some(B=>Object.values(B).some(ie=>ie.length>0));return e.status==="running"&&!Z&&A.length===0&&se("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(Z||!re&&!X&&!Oe||A.length>0)&&se("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(Z||re||X||Oe||A.length>0)&&se("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&se(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:o,workflow:s,definitionHashes:c,...e.initialStateHash===void 0?{}:{initialStateHash:No(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:a,actions:f,...m===void 0?{}:{commands:m},actionContexts:v,waits:h,...e.evidenceWaits===void 0?{}:{evidenceWaits:p},ready:A,joins:_,outputs:Q,children:F,lineage:u,...e.reason===void 0?{}:{reason:e.reason}}}var W_,L_,Xw,$_,Xl=x(()=>{"use strict";ha();pn();kr();W_=new WeakSet,L_=new WeakSet,Xw=new WeakSet,$_=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"]});import{randomUUID as q1}from"node:crypto";async function va(e,t){let r=await(e.readProjection?e.readProjection(t):e.read(t));if(!r)throw new R("RUN_NOT_FOUND",`找不到工作流实例:${t}`);Gl(r)||(hn(r),r=structuredClone(r),Kl(r));let n="run"in r?r.run:r;if(!n||n.runId!==r.runId||n.revision!==r.revision)throw new R("INVALID_RUN","Run 与存储 envelope 身份不一致");let i;try{i=bp(n,t,{hash:Bn,visitResults:vp,validateOrigins:wp})}catch(s){throw s instanceof R?s:new R("INVALID_RUN",s instanceof Error?s.message:String(s))}Kl(i);let o=Gl(r);o&&(o.validationActions=i.actions.length,o.validationMaterializedEntries=o.materializedEntries);let a=e.queryScope??M_.get(e);return a||(a=q1(),M_.set(e,a)),Object.freeze({record:r,run:i,scope:a,stats:o,materialize:(s=[])=>br(s.reduce((c,l)=>c?.[l],i)),hash:()=>Bn(i)})}function Zw(e,t){let{run:r,scope:n}=e;["current","summary","history","action","artifact"].includes(t.view)||So("query.view 无效");let i={runId:r.runId,revision:r.revision,status:r.status,workflow:r.workflow,sequence:r.sequence},o={actions:r.actions.length,waits:r.waits.length,evidenceWaits:r.evidenceWaits?.length??0},a=r.actions.filter(d=>["pending","running","unknown"].includes(d.status)||d.status==="cancelled"&&d.claim&&!d.executionStop&&!d.cancellation);if(t.view==="summary")return br({...i,history:o,pending:{actions:a.length,waits:r.waits.filter(d=>d.status==="pending").length,evidenceWaits:(r.evidenceWaits??[]).filter(d=>d.status==="pending").length}});if(t.view==="current")return br({...i,input:r.input,...r.state===void 0?{}:{state:r.state},...r.reason===void 0?{}:{reason:r.reason},actions:a,waits:r.waits.filter(d=>d.status==="pending"),evidenceWaits:(r.evidenceWaits??[]).filter(d=>d.status==="pending"),outputs:r.outputs,history:o});if(t.view==="action"||t.view==="artifact"){let d=r.actions.find(p=>p.id===t.actionId);if(d||So("query.actionId 不属于当前 Run"),t.view==="action")return br({...i,action:d,context:r.actionContexts[d.id]});let m=(d.outcome?.artifacts??[]).map(p=>({...p,artifactId:j({actionId:d.id,...p})})),h=t.artifactId===void 0?m:m.filter(p=>p.artifactId===t.artifactId);return t.artifactId!==void 0&&!h.length&&So("query.artifactId 不属于所选 Action"),br({...i,actionId:d.id,artifacts:h})}let s=t.limit??25;(!Number.isSafeInteger(s)||s<1||s>100)&&So("query.limit 必须在 1–100 之间");let c=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(c)||So("query.filter 无效");let l=j({scope:n,runId:r.runId,revision:r.revision,filter:c}),u=0;if(t.cursor)try{let d=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf8"));(d.binding!==l||!Number.isSafeInteger(d.offset)||d.offset<0||Object.keys(d).some(m=>!["binding","offset"].includes(m)))&&So("query.cursor 与当前存储、版本或筛选不匹配"),u=d.offset}catch{So("query.cursor 无效或已经过期")}let f=[...c==="all"||c==="actions"?r.actions.map((d,m)=>({kind:"action",sequence:r.actionContexts[d.id].sequence,path:["actions",String(m)]})):[],...c==="all"||c==="waits"?r.waits.map((d,m)=>({kind:"wait",sequence:d.sequence,path:["waits",String(m)]})):[],...c==="all"||c==="evidenceWaits"?(r.evidenceWaits??[]).map((d,m)=>({kind:"evidenceWait",sequence:d.sequence,path:["evidenceWaits",String(m)]})):[]].sort((d,m)=>m.sequence-d.sequence);return u>f.length&&So("query.cursor 超出历史范围"),{...br(i),records:f.slice(u,u+s).map(d=>({kind:d.kind,sequence:d.sequence,value:e.materialize(d.path)})),total:f.length,...u+s<f.length?{nextCursor:Buffer.from(JSON.stringify({binding:l,offset:u+s})).toString("base64url")}:{}}}var M_,So,ey=x(()=>{"use strict";ga();pn();Xl();kr();M_=new WeakMap;So=e=>{throw new R("INVALID_REQUEST",e)}});var tu=D(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.regexpCode=We.getEsmExportName=We.getProperty=We.safeStringify=We.stringify=We.strConcat=We.addCodeArg=We.str=We._=We.nil=We._Code=We.Name=We.IDENTIFIER=We._CodeOrName=void 0;var Zl=class{};We._CodeOrName=Zl;We.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var wa=class extends Zl{constructor(t){if(super(),!We.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};We.Name=wa;var wn=class extends Zl{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof wa&&(r[n.str]=(r[n.str]||0)+1),r),{})}};We._Code=wn;We.nil=new wn("");function F_(e,...t){let r=[e[0]],n=0;for(;n<t.length;)ry(r,t[n]),r.push(e[++n]);return new wn(r)}We._=F_;var ty=new wn("+");function H_(e,...t){let r=[eu(e[0])],n=0;for(;n<t.length;)r.push(ty),ry(r,t[n]),r.push(ty,eu(e[++n]));return V1(r),new wn(r)}We.str=H_;function ry(e,t){t instanceof wn?e.push(...t._items):t instanceof wa?e.push(t):e.push(H1(t))}We.addCodeArg=ry;function V1(e){let t=1;for(;t<e.length-1;){if(e[t]===ty){let r=M1(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function M1(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof wa||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof wa))return`"${e}${t.slice(1)}`}function F1(e,t){return t.emptyStr()?e:e.emptyStr()?t:H_`${e}${t}`}We.strConcat=F1;function H1(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:eu(Array.isArray(e)?e.join(","):e)}function Q1(e){return new wn(eu(e))}We.stringify=Q1;function eu(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}We.safeStringify=eu;function U1(e){return typeof e=="string"&&We.IDENTIFIER.test(e)?new wn(`.${e}`):F_`[${e}]`}We.getProperty=U1;function J1(e){if(typeof e=="string"&&We.IDENTIFIER.test(e))return new wn(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}We.getEsmExportName=J1;function z1(e){return new wn(e.toString())}We.regexpCode=z1});var oy=D(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.ValueScope=Lr.ValueScopeName=Lr.Scope=Lr.varKinds=Lr.UsedValueState=void 0;var Wr=tu(),ny=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Np;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Np||(Lr.UsedValueState=Np={}));Lr.varKinds={const:new Wr.Name("const"),let:new Wr.Name("let"),var:new Wr.Name("var")};var Sp=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Wr.Name?t:this.name(t)}name(t){return new Wr.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Lr.Scope=Sp;var Ep=class extends Wr.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Wr._)`.${new Wr.Name(r)}[${n}]`}};Lr.ValueScopeName=Ep;var K1=(0,Wr._)`\n`,iy=class extends Sp{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?K1:Wr.nil}}get(){return this._scope}name(t){return new Ep(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:o}=i,a=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[o];if(s){let u=s.get(a);if(u)return u}else s=this._values[o]=new Map;s.set(a,i);let c=this._scope[o]||(this._scope[o]=[]),l=c.length;return c[l]=r.ref,i.setValue(r,{property:o,itemIndex:l}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Wr._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let o=Wr.nil;for(let a in t){let s=t[a];if(!s)continue;let c=n[a]=n[a]||new Map;s.forEach(l=>{if(c.has(l))return;c.set(l,Np.Started);let u=r(l);if(u){let f=this.opts.es5?Lr.varKinds.var:Lr.varKinds.const;o=(0,Wr._)`${o}${f} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))o=(0,Wr._)`${o}${u}${this.opts._n}`;else throw new ny(l);c.set(l,Np.Completed)})}return o}};Lr.ValueScope=iy});var Ee=D(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.or=Ne.and=Ne.not=Ne.CodeGen=Ne.operators=Ne.varKinds=Ne.ValueScopeName=Ne.ValueScope=Ne.Scope=Ne.Name=Ne.regexpCode=Ne.stringify=Ne.getProperty=Ne.nil=Ne.strConcat=Ne.str=Ne._=void 0;var Pe=tu(),Wn=oy(),Eo=tu();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return Eo._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return Eo.str}});Object.defineProperty(Ne,"strConcat",{enumerable:!0,get:function(){return Eo.strConcat}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return Eo.nil}});Object.defineProperty(Ne,"getProperty",{enumerable:!0,get:function(){return Eo.getProperty}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return Eo.stringify}});Object.defineProperty(Ne,"regexpCode",{enumerable:!0,get:function(){return Eo.regexpCode}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return Eo.Name}});var xp=oy();Object.defineProperty(Ne,"Scope",{enumerable:!0,get:function(){return xp.Scope}});Object.defineProperty(Ne,"ValueScope",{enumerable:!0,get:function(){return xp.ValueScope}});Object.defineProperty(Ne,"ValueScopeName",{enumerable:!0,get:function(){return xp.ValueScopeName}});Object.defineProperty(Ne,"varKinds",{enumerable:!0,get:function(){return xp.varKinds}});Ne.operators={GT:new Pe._Code(">"),GTE:new Pe._Code(">="),LT:new Pe._Code("<"),LTE:new Pe._Code("<="),EQ:new Pe._Code("==="),NEQ:new Pe._Code("!=="),NOT:new Pe._Code("!"),OR:new Pe._Code("||"),AND:new Pe._Code("&&"),ADD:new Pe._Code("+")};var Pi=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ay=class extends Pi{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Wn.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Ds(this.rhs,t,r)),this}get names(){return this.rhs instanceof Pe._CodeOrName?this.rhs.names:{}}},Cp=class extends Pi{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Pe.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Ds(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Pe.Name?{}:{...this.lhs.names};return Ip(t,this.rhs)}},sy=class extends Cp{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},cy=class extends Pi{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ly=class extends Pi{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},uy=class extends Pi{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},dy=class extends Pi{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Ds(this.code,t,r),this}get names(){return this.code instanceof Pe._CodeOrName?this.code.names:{}}},ru=class extends Pi{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(t,r)||(G1(t,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>ba(t,r.names),{})}},Oi=class extends ru{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},fy=class extends ru{},$s=class extends Oi{};$s.kind="else";var ya=class e extends Oi{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new $s(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Q_(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Ds(this.condition,t,r),this}get names(){let t=super.names;return Ip(t,this.condition),this.else&&ba(t,this.else.names),t}};ya.kind="if";var ka=class extends Oi{};ka.kind="for";var py=class extends ka{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Ds(this.iteration,t,r),this}get names(){return ba(super.names,this.iteration.names)}},my=class extends ka{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?Wn.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(t)}get names(){let t=Ip(super.names,this.from);return Ip(t,this.to)}},_p=class extends ka{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Ds(this.iterable,t,r),this}get names(){return ba(super.names,this.iterable.names)}},nu=class extends Oi{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};nu.kind="func";var iu=class extends ru{render(t){return"return "+super.render(t)}};iu.kind="return";var hy=class extends Oi{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&ba(t,this.catch.names),this.finally&&ba(t,this.finally.names),t}},ou=class extends Oi{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};ou.kind="catch";var au=class extends Oi{render(t){return"finally"+super.render(t)}};au.kind="finally";var gy=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
188
+ `:""},this._extScope=t,this._scope=new Wn.Scope({parent:t}),this._nodes=[new fy]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new ay(t,o,n)),o}const(t,r,n){return this._def(Wn.varKinds.const,t,r,n)}let(t,r,n){return this._def(Wn.varKinds.let,t,r,n)}var(t,r,n){return this._def(Wn.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Cp(t,r,n))}add(t,r){return this._leafNode(new sy(t,Ne.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Pe.nil&&this._leafNode(new dy(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,Pe.addCodeArg)(r,i));return r.push("}"),new Pe._Code(r)}if(t,r,n){if(this._blockNode(new ya(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new ya(t))}else(){return this._elseNode(new $s)}endIf(){return this._endBlockNode(ya,$s)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new py(t),r)}forRange(t,r,n,i,o=this.opts.es5?Wn.varKinds.var:Wn.varKinds.let){let a=this._scope.toName(t);return this._for(new my(o,a,r,n),()=>i(a))}forOf(t,r,n,i=Wn.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let a=r instanceof Pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Pe._)`${a}.length`,s=>{this.var(o,(0,Pe._)`${a}[${s}]`),n(o)})}return this._for(new _p("of",i,o,r),()=>n(o))}forIn(t,r,n,i=this.opts.es5?Wn.varKinds.var:Wn.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Pe._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new _p("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(ka)}label(t){return this._leafNode(new cy(t))}break(t){return this._leafNode(new ly(t))}return(t){let r=new iu;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(iu)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new hy;if(this._blockNode(i),this.code(t),r){let o=this.name("e");this._currNode=i.catch=new ou(o),r(o)}return n&&(this._currNode=i.finally=new au,this.code(n)),this._endBlockNode(ou,au)}throw(t){return this._leafNode(new uy(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Pe.nil,n,i){return this._blockNode(new nu(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(nu)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof ya))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};Ne.CodeGen=gy;function ba(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Ip(e,t){return t instanceof Pe._CodeOrName?ba(e,t.names):e}function Ds(e,t,r){if(e instanceof Pe.Name)return n(e);if(!i(e))return e;return new Pe._Code(e._items.reduce((o,a)=>(a instanceof Pe.Name&&(a=n(a)),a instanceof Pe._Code?o.push(...a._items):o.push(a),o),[]));function n(o){let a=r[o.str];return a===void 0||t[o.str]!==1?o:(delete t[o.str],a)}function i(o){return o instanceof Pe._Code&&o._items.some(a=>a instanceof Pe.Name&&t[a.str]===1&&r[a.str]!==void 0)}}function G1(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Q_(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Pe._)`!${vy(e)}`}Ne.not=Q_;var Y1=U_(Ne.operators.AND);function X1(...e){return e.reduce(Y1)}Ne.and=X1;var Z1=U_(Ne.operators.OR);function eF(...e){return e.reduce(Z1)}Ne.or=eF;function U_(e){return(t,r)=>t===Pe.nil?r:r===Pe.nil?t:(0,Pe._)`${vy(t)} ${e} ${vy(r)}`}function vy(e){return e instanceof Pe.Name?e:(0,Pe._)`(${e})`}});var je=D(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.checkStrictMode=Ce.getErrorPath=Ce.Type=Ce.useFunc=Ce.setEvaluated=Ce.evaluatedPropsToName=Ce.mergeEvaluated=Ce.eachItem=Ce.unescapeJsonPointer=Ce.escapeJsonPointer=Ce.escapeFragment=Ce.unescapeFragment=Ce.schemaRefOrVal=Ce.schemaHasRulesButRef=Ce.schemaHasRules=Ce.checkUnknownRules=Ce.alwaysValidSchema=Ce.toHash=void 0;var rt=Ee(),tF=tu();function rF(e){let t={};for(let r of e)t[r]=!0;return t}Ce.toHash=rF;function nF(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(K_(e,t),!G_(t,e.self.RULES.all))}Ce.alwaysValidSchema=nF;function K_(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let o in t)i[o]||Z_(e,`unknown keyword: "${o}"`)}Ce.checkUnknownRules=K_;function G_(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}Ce.schemaHasRules=G_;function iF(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Ce.schemaHasRulesButRef=iF;function oF({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,rt._)`${r}`}return(0,rt._)`${e}${t}${(0,rt.getProperty)(n)}`}Ce.schemaRefOrVal=oF;function aF(e){return Y_(decodeURIComponent(e))}Ce.unescapeFragment=aF;function sF(e){return encodeURIComponent(yy(e))}Ce.escapeFragment=sF;function yy(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Ce.escapeJsonPointer=yy;function Y_(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Ce.unescapeJsonPointer=Y_;function cF(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}Ce.eachItem=cF;function J_({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,o,a,s)=>{let c=a===void 0?o:a instanceof rt.Name?(o instanceof rt.Name?e(i,o,a):t(i,o,a),a):o instanceof rt.Name?(t(i,a,o),o):r(o,a);return s===rt.Name&&!(c instanceof rt.Name)?n(i,c):c}}Ce.mergeEvaluated={props:J_({mergeNames:(e,t,r)=>e.if((0,rt._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,rt._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,rt._)`${r} || {}`).code((0,rt._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,rt._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,rt._)`${r} || {}`),ky(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:X_}),items:J_({mergeNames:(e,t,r)=>e.if((0,rt._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,rt._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,rt._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,rt._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function X_(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,rt._)`{}`);return t!==void 0&&ky(e,r,t),r}Ce.evaluatedPropsToName=X_;function ky(e,t,r){Object.keys(r).forEach(n=>e.assign((0,rt._)`${t}${(0,rt.getProperty)(n)}`,!0))}Ce.setEvaluated=ky;var z_={};function lF(e,t){return e.scopeValue("func",{ref:t,code:z_[t.code]||(z_[t.code]=new tF._Code(t.code))})}Ce.useFunc=lF;var wy;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(wy||(Ce.Type=wy={}));function uF(e,t,r){if(e instanceof rt.Name){let n=t===wy.Num;return r?n?(0,rt._)`"[" + ${e} + "]"`:(0,rt._)`"['" + ${e} + "']"`:n?(0,rt._)`"/" + ${e}`:(0,rt._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,rt.getProperty)(e).toString():"/"+yy(e)}Ce.getErrorPath=uF;function Z_(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Ce.checkStrictMode=Z_});var Ti=D(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});var nr=Ee(),dF={data:new nr.Name("data"),valCxt:new nr.Name("valCxt"),instancePath:new nr.Name("instancePath"),parentData:new nr.Name("parentData"),parentDataProperty:new nr.Name("parentDataProperty"),rootData:new nr.Name("rootData"),dynamicAnchors:new nr.Name("dynamicAnchors"),vErrors:new nr.Name("vErrors"),errors:new nr.Name("errors"),this:new nr.Name("this"),self:new nr.Name("self"),scope:new nr.Name("scope"),json:new nr.Name("json"),jsonPos:new nr.Name("jsonPos"),jsonLen:new nr.Name("jsonLen"),jsonPart:new nr.Name("jsonPart")};by.default=dF});var su=D(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.extendErrors=ir.resetErrorsCount=ir.reportExtraError=ir.reportError=ir.keyword$DataError=ir.keywordError=void 0;var $e=Ee(),Pp=je(),Ar=Ti();ir.keywordError={message:({keyword:e})=>(0,$e.str)`must pass "${e}" keyword validation`};ir.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,$e.str)`"${e}" keyword must be ${t} ($data)`:(0,$e.str)`"${e}" keyword is invalid ($data)`};function fF(e,t=ir.keywordError,r,n){let{it:i}=e,{gen:o,compositeRule:a,allErrors:s}=i,c=rI(e,t,r);n??(a||s)?eI(o,c):tI(i,(0,$e._)`[${c}]`)}ir.reportError=fF;function pF(e,t=ir.keywordError,r){let{it:n}=e,{gen:i,compositeRule:o,allErrors:a}=n,s=rI(e,t,r);eI(i,s),o||a||tI(n,Ar.default.vErrors)}ir.reportExtraError=pF;function mF(e,t){e.assign(Ar.default.errors,t),e.if((0,$e._)`${Ar.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,$e._)`${Ar.default.vErrors}.length`,t),()=>e.assign(Ar.default.vErrors,null)))}ir.resetErrorsCount=mF;function hF({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let a=e.name("err");e.forRange("i",i,Ar.default.errors,s=>{e.const(a,(0,$e._)`${Ar.default.vErrors}[${s}]`),e.if((0,$e._)`${a}.instancePath === undefined`,()=>e.assign((0,$e._)`${a}.instancePath`,(0,$e.strConcat)(Ar.default.instancePath,o.errorPath))),e.assign((0,$e._)`${a}.schemaPath`,(0,$e.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,$e._)`${a}.schema`,r),e.assign((0,$e._)`${a}.data`,n))})}ir.extendErrors=hF;function eI(e,t){let r=e.const("err",t);e.if((0,$e._)`${Ar.default.vErrors} === null`,()=>e.assign(Ar.default.vErrors,(0,$e._)`[${r}]`),(0,$e._)`${Ar.default.vErrors}.push(${r})`),e.code((0,$e._)`${Ar.default.errors}++`)}function tI(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,$e._)`new ${e.ValidationError}(${t})`):(r.assign((0,$e._)`${n}.errors`,t),r.return(!1))}var Aa={keyword:new $e.Name("keyword"),schemaPath:new $e.Name("schemaPath"),params:new $e.Name("params"),propertyName:new $e.Name("propertyName"),message:new $e.Name("message"),schema:new $e.Name("schema"),parentSchema:new $e.Name("parentSchema")};function rI(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,$e._)`{}`:gF(e,t,r)}function gF(e,t,r={}){let{gen:n,it:i}=e,o=[vF(i,r),wF(e,r)];return yF(e,t,o),n.object(...o)}function vF({errorPath:e},{instancePath:t}){let r=t?(0,$e.str)`${e}${(0,Pp.getErrorPath)(t,Pp.Type.Str)}`:e;return[Ar.default.instancePath,(0,$e.strConcat)(Ar.default.instancePath,r)]}function wF({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,$e.str)`${t}/${e}`;return r&&(i=(0,$e.str)`${i}${(0,Pp.getErrorPath)(r,Pp.Type.Str)}`),[Aa.schemaPath,i]}function yF(e,{params:t,message:r},n){let{keyword:i,data:o,schemaValue:a,it:s}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:f}=s;n.push([Aa.keyword,i],[Aa.params,typeof t=="function"?t(e):t||(0,$e._)`{}`]),c.messages&&n.push([Aa.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Aa.schema,a],[Aa.parentSchema,(0,$e._)`${u}${f}`],[Ar.default.data,o]),l&&n.push([Aa.propertyName,l])}});var iI=D(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.boolOrEmptySchema=Bs.topBoolOrEmptySchema=void 0;var kF=su(),bF=Ee(),AF=Ti(),RF={message:"boolean schema is false"};function NF(e){let{gen:t,schema:r,validateName:n}=e;r===!1?nI(e,!1):typeof r=="object"&&r.$async===!0?t.return(AF.default.data):(t.assign((0,bF._)`${n}.errors`,null),t.return(!0))}Bs.topBoolOrEmptySchema=NF;function SF(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),nI(e)):r.var(t,!0)}Bs.boolOrEmptySchema=SF;function nI(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,kF.reportError)(i,RF,void 0,t)}});var Ay=D(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.getRules=Ws.isJSONType=void 0;var EF=["string","number","integer","boolean","null","object","array"],CF=new Set(EF);function _F(e){return typeof e=="string"&&CF.has(e)}Ws.isJSONType=_F;function IF(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Ws.getRules=IF});var Ry=D(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.shouldUseRule=Co.shouldUseGroup=Co.schemaHasRulesForType=void 0;function xF({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&oI(e,n)}Co.schemaHasRulesForType=xF;function oI(e,t){return t.rules.some(r=>aI(e,r))}Co.shouldUseGroup=oI;function aI(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Co.shouldUseRule=aI});var cu=D(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.reportTypeError=or.checkDataTypes=or.checkDataType=or.coerceAndCheckDataType=or.getJSONTypes=or.getSchemaTypes=or.DataType=void 0;var PF=Ay(),OF=Ry(),TF=su(),be=Ee(),sI=je(),Ls;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Ls||(or.DataType=Ls={}));function jF(e){let t=cI(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}or.getSchemaTypes=jF;function cI(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(PF.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}or.getJSONTypes=cI;function $F(e,t){let{gen:r,data:n,opts:i}=e,o=DF(t,i.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,OF.schemaHasRulesForType)(e,t[0]));if(a){let s=Sy(t,n,i.strictNumbers,Ls.Wrong);r.if(s,()=>{o.length?BF(e,t,o):Ey(e)})}return a}or.coerceAndCheckDataType=$F;var lI=new Set(["string","number","integer","boolean","null"]);function DF(e,t){return t?e.filter(r=>lI.has(r)||t==="array"&&r==="array"):[]}function BF(e,t,r){let{gen:n,data:i,opts:o}=e,a=n.let("dataType",(0,be._)`typeof ${i}`),s=n.let("coerced",(0,be._)`undefined`);o.coerceTypes==="array"&&n.if((0,be._)`${a} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,be._)`${i}[0]`).assign(a,(0,be._)`typeof ${i}`).if(Sy(t,i,o.strictNumbers),()=>n.assign(s,i))),n.if((0,be._)`${s} !== undefined`);for(let l of r)(lI.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),Ey(e),n.endIf(),n.if((0,be._)`${s} !== undefined`,()=>{n.assign(i,s),WF(e,s)});function c(l){switch(l){case"string":n.elseIf((0,be._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,be._)`"" + ${i}`).elseIf((0,be._)`${i} === null`).assign(s,(0,be._)`""`);return;case"number":n.elseIf((0,be._)`${a} == "boolean" || ${i} === null
189
+ || (${a} == "string" && ${i} && ${i} == +${i})`).assign(s,(0,be._)`+${i}`);return;case"integer":n.elseIf((0,be._)`${a} === "boolean" || ${i} === null
190
+ || (${a} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(s,(0,be._)`+${i}`);return;case"boolean":n.elseIf((0,be._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(s,!1).elseIf((0,be._)`${i} === "true" || ${i} === 1`).assign(s,!0);return;case"null":n.elseIf((0,be._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(s,null);return;case"array":n.elseIf((0,be._)`${a} === "string" || ${a} === "number"
191
+ || ${a} === "boolean" || ${i} === null`).assign(s,(0,be._)`[${i}]`)}}}function WF({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,be._)`${t} !== undefined`,()=>e.assign((0,be._)`${t}[${r}]`,n))}function Ny(e,t,r,n=Ls.Correct){let i=n===Ls.Correct?be.operators.EQ:be.operators.NEQ,o;switch(e){case"null":return(0,be._)`${t} ${i} null`;case"array":o=(0,be._)`Array.isArray(${t})`;break;case"object":o=(0,be._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=a((0,be._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=a();break;default:return(0,be._)`typeof ${t} ${i} ${e}`}return n===Ls.Correct?o:(0,be.not)(o);function a(s=be.nil){return(0,be.and)((0,be._)`typeof ${t} == "number"`,s,r?(0,be._)`isFinite(${t})`:be.nil)}}or.checkDataType=Ny;function Sy(e,t,r,n){if(e.length===1)return Ny(e[0],t,r,n);let i,o=(0,sI.toHash)(e);if(o.array&&o.object){let a=(0,be._)`typeof ${t} != "object"`;i=o.null?a:(0,be._)`!${t} || ${a}`,delete o.null,delete o.array,delete o.object}else i=be.nil;o.number&&delete o.integer;for(let a in o)i=(0,be.and)(i,Ny(a,t,r,n));return i}or.checkDataTypes=Sy;var LF={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,be._)`{type: ${e}}`:(0,be._)`{type: ${t}}`};function Ey(e){let t=qF(e);(0,TF.reportError)(t,LF)}or.reportTypeError=Ey;function qF(e){let{gen:t,data:r,schema:n}=e,i=(0,sI.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var dI=D(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});Op.assignDefaults=void 0;var qs=Ee(),VF=je();function MF(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)uI(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,o)=>uI(e,o,i.default))}Op.assignDefaults=MF;function uI(e,t,r){let{gen:n,compositeRule:i,data:o,opts:a}=e;if(r===void 0)return;let s=(0,qs._)`${o}${(0,qs.getProperty)(t)}`;if(i){(0,VF.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,qs._)`${s} === undefined`;a.useDefaults==="empty"&&(c=(0,qs._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,qs._)`${s} = ${(0,qs.stringify)(r)}`)}});var yn=D(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateUnion=Xe.validateArray=Xe.usePattern=Xe.callValidateCode=Xe.schemaProperties=Xe.allSchemaProperties=Xe.noPropertyInData=Xe.propertyInData=Xe.isOwnProperty=Xe.hasPropFunc=Xe.reportMissingProp=Xe.checkMissingProp=Xe.checkReportMissingProp=void 0;var ot=Ee(),Cy=je(),_o=Ti(),FF=je();function HF(e,t){let{gen:r,data:n,it:i}=e;r.if(Iy(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ot._)`${t}`},!0),e.error()})}Xe.checkReportMissingProp=HF;function QF({gen:e,data:t,it:{opts:r}},n,i){return(0,ot.or)(...n.map(o=>(0,ot.and)(Iy(e,t,o,r.ownProperties),(0,ot._)`${i} = ${o}`)))}Xe.checkMissingProp=QF;function UF(e,t){e.setParams({missingProperty:t},!0),e.error()}Xe.reportMissingProp=UF;function fI(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ot._)`Object.prototype.hasOwnProperty`})}Xe.hasPropFunc=fI;function _y(e,t,r){return(0,ot._)`${fI(e)}.call(${t}, ${r})`}Xe.isOwnProperty=_y;function JF(e,t,r,n){let i=(0,ot._)`${t}${(0,ot.getProperty)(r)} !== undefined`;return n?(0,ot._)`${i} && ${_y(e,t,r)}`:i}Xe.propertyInData=JF;function Iy(e,t,r,n){let i=(0,ot._)`${t}${(0,ot.getProperty)(r)} === undefined`;return n?(0,ot.or)(i,(0,ot.not)(_y(e,t,r))):i}Xe.noPropertyInData=Iy;function pI(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Xe.allSchemaProperties=pI;function zF(e,t){return pI(t).filter(r=>!(0,Cy.alwaysValidSchema)(e,t[r]))}Xe.schemaProperties=zF;function KF({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:a},s,c,l){let u=l?(0,ot._)`${e}, ${t}, ${n}${i}`:t,f=[[_o.default.instancePath,(0,ot.strConcat)(_o.default.instancePath,o)],[_o.default.parentData,a.parentData],[_o.default.parentDataProperty,a.parentDataProperty],[_o.default.rootData,_o.default.rootData]];a.opts.dynamicRef&&f.push([_o.default.dynamicAnchors,_o.default.dynamicAnchors]);let d=(0,ot._)`${u}, ${r.object(...f)}`;return c!==ot.nil?(0,ot._)`${s}.call(${c}, ${d})`:(0,ot._)`${s}(${d})`}Xe.callValidateCode=KF;var GF=(0,ot._)`new RegExp`;function YF({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,ot._)`${i.code==="new RegExp"?GF:(0,FF.useFunc)(e,i)}(${r}, ${n})`})}Xe.usePattern=YF;function XF(e){let{gen:t,data:r,keyword:n,it:i}=e,o=t.name("valid");if(i.allErrors){let s=t.let("valid",!0);return a(()=>t.assign(s,!1)),s}return t.var(o,!0),a(()=>t.break()),o;function a(s){let c=t.const("len",(0,ot._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:Cy.Type.Num},o),t.if((0,ot.not)(o),s)})}}Xe.validateArray=XF;function ZF(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Cy.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let a=t.let("valid",!1),s=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},s);t.assign(a,(0,ot._)`${a} || ${s}`),e.mergeValidEvaluated(u,s)||t.if((0,ot.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}Xe.validateUnion=ZF});var gI=D(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.validateKeywordUsage=ii.validSchemaType=ii.funcKeywordCode=ii.macroKeywordCode=void 0;var Rr=Ee(),Ra=Ti(),eH=yn(),tH=su();function rH(e,t){let{gen:r,keyword:n,schema:i,parentSchema:o,it:a}=e,s=t.macro.call(a.self,i,o,a),c=hI(r,n,s);a.opts.validateSchema!==!1&&a.self.validateSchema(s,!0);let l=r.name("valid");e.subschema({schema:s,schemaPath:Rr.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}ii.macroKeywordCode=rH;function nH(e,t){var r;let{gen:n,keyword:i,schema:o,parentSchema:a,$data:s,it:c}=e;oH(c,t);let l=!s&&t.compile?t.compile.call(c.self,o,a,c):t.validate,u=hI(n,i,l),f=n.let("valid");e.block$data(f,d),e.ok((r=t.valid)!==null&&r!==void 0?r:f);function d(){if(t.errors===!1)p(),t.modifying&&mI(e),g(()=>e.error());else{let v=t.async?m():h();t.modifying&&mI(e),g(()=>iH(e,v))}}function m(){let v=n.let("ruleErrs",null);return n.try(()=>p((0,Rr._)`await `),w=>n.assign(f,!1).if((0,Rr._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Rr._)`${w}.errors`),()=>n.throw(w))),v}function h(){let v=(0,Rr._)`${u}.errors`;return n.assign(v,null),p(Rr.nil),v}function p(v=t.async?(0,Rr._)`await `:Rr.nil){let w=c.opts.passContext?Ra.default.this:Ra.default.self,y=!("compile"in t&&!s||t.schema===!1);n.assign(f,(0,Rr._)`${v}${(0,eH.callValidateCode)(e,u,w,y)}`,t.modifying)}function g(v){var w;n.if((0,Rr.not)((w=t.valid)!==null&&w!==void 0?w:f),v)}}ii.funcKeywordCode=nH;function mI(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Rr._)`${n.parentData}[${n.parentDataProperty}]`))}function iH(e,t){let{gen:r}=e;r.if((0,Rr._)`Array.isArray(${t})`,()=>{r.assign(Ra.default.vErrors,(0,Rr._)`${Ra.default.vErrors} === null ? ${t} : ${Ra.default.vErrors}.concat(${t})`).assign(Ra.default.errors,(0,Rr._)`${Ra.default.vErrors}.length`),(0,tH.extendErrors)(e)},()=>e.error())}function oH({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function hI(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Rr.stringify)(r)})}function aH(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}ii.validSchemaType=aH;function sH({schema:e,opts:t,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let a=i.dependencies;if(a?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${o}: ${a.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}ii.validateKeywordUsage=sH});var wI=D(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.extendSubschemaMode=Io.extendSubschemaData=Io.getSubschema=void 0;var oi=Ee(),vI=je();function cH(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:a}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0,oi._)`${e.schemaPath}${(0,oi.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,oi._)`${e.schemaPath}${(0,oi.getProperty)(t)}${(0,oi.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,vI.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:a,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Io.getSubschema=cH;function lH(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:a}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:f}=t,d=s.let("data",(0,oi._)`${t.data}${(0,oi.getProperty)(r)}`,!0);c(d),e.errorPath=(0,oi.str)`${l}${(0,vI.getErrorPath)(r,n,f.jsPropertySyntax)}`,e.parentDataProperty=(0,oi._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(i!==void 0){let l=i instanceof oi.Name?i:s.let("data",i,!0);c(l),a!==void 0&&(e.propertyName=a)}o&&(e.dataTypes=o);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Io.extendSubschemaData=lH;function uH(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),o!==void 0&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r}Io.extendSubschemaMode=uH});var xy=D((iZ,yI)=>{"use strict";yI.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var a=o[i];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}});var bI=D((oZ,kI)=>{"use strict";var xo=kI.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Tp(t,n,i,e,"",e)};xo.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};xo.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};xo.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};xo.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Tp(e,t,r,n,i,o,a,s,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,o,a,s,c,l);for(var u in n){var f=n[u];if(Array.isArray(f)){if(u in xo.arrayKeywords)for(var d=0;d<f.length;d++)Tp(e,t,r,f[d],i+"/"+u+"/"+d,o,i,u,n,d)}else if(u in xo.propsKeywords){if(f&&typeof f=="object")for(var m in f)Tp(e,t,r,f[m],i+"/"+u+"/"+dH(m),o,i,u,n,m)}else(u in xo.keywords||e.allKeys&&!(u in xo.skipKeywords))&&Tp(e,t,r,f,i+"/"+u,o,i,u,n)}r(n,i,o,a,s,c,l)}}function dH(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var lu=D(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.getSchemaRefs=qr.resolveUrl=qr.normalizeId=qr._getFullPath=qr.getFullPath=qr.inlineRef=void 0;var fH=je(),pH=xy(),mH=bI(),hH=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function gH(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Py(e):t?AI(e)<=t:!1}qr.inlineRef=gH;var vH=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Py(e){for(let t in e){if(vH.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Py)||typeof r=="object"&&Py(r))return!0}return!1}function AI(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!hH.has(r)&&(typeof e[r]=="object"&&(0,fH.eachItem)(e[r],n=>t+=AI(n)),t===1/0))return 1/0}return t}function RI(e,t="",r){r!==!1&&(t=Vs(t));let n=e.parse(t);return NI(e,n)}qr.getFullPath=RI;function NI(e,t){return e.serialize(t).split("#")[0]+"#"}qr._getFullPath=NI;var wH=/#\/?$/;function Vs(e){return e?e.replace(wH,""):""}qr.normalizeId=Vs;function yH(e,t,r){return r=Vs(r),e.resolve(t,r)}qr.resolveUrl=yH;var kH=/^[a-z_][-a-z0-9._]*$/i;function bH(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Vs(e[r]||t),o={"":i},a=RI(n,i,!1),s={},c=new Set;return mH(e,{allKeys:!0},(f,d,m,h)=>{if(h===void 0)return;let p=a+d,g=o[h];typeof f[r]=="string"&&(g=v.call(this,f[r])),w.call(this,f.$anchor),w.call(this,f.$dynamicAnchor),o[d]=g;function v(y){let b=this.opts.uriResolver.resolve;if(y=Vs(g?b(g,y):y),c.has(y))throw u(y);c.add(y);let N=this.refs[y];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?l(f,N.schema,y):y!==Vs(p)&&(y[0]==="#"?(l(f,s[y],y),s[y]=f):this.refs[y]=p),y}function w(y){if(typeof y=="string"){if(!kH.test(y))throw new Error(`invalid anchor "${y}"`);v.call(this,`#${y}`)}}}),s;function l(f,d,m){if(d!==void 0&&!pH(f,d))throw u(m)}function u(f){return new Error(`reference "${f}" resolves to more than one schema`)}}qr.getSchemaRefs=bH});var fu=D(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.getData=Po.KeywordCxt=Po.validateFunctionCode=void 0;var II=iI(),SI=cu(),Ty=Ry(),jp=cu(),AH=dI(),du=gI(),Oy=wI(),ue=Ee(),ge=Ti(),RH=lu(),ji=je(),uu=su();function NH(e){if(OI(e)&&(TI(e),PI(e))){CH(e);return}xI(e,()=>(0,II.topBoolOrEmptySchema)(e))}Po.validateFunctionCode=NH;function xI({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,(0,ue._)`${ge.default.data}, ${ge.default.valCxt}`,n.$async,()=>{e.code((0,ue._)`"use strict"; ${EI(r,i)}`),EH(e,i),e.code(o)}):e.func(t,(0,ue._)`${ge.default.data}, ${SH(i)}`,n.$async,()=>e.code(EI(r,i)).code(o))}function SH(e){return(0,ue._)`{${ge.default.instancePath}="", ${ge.default.parentData}, ${ge.default.parentDataProperty}, ${ge.default.rootData}=${ge.default.data}${e.dynamicRef?(0,ue._)`, ${ge.default.dynamicAnchors}={}`:ue.nil}}={}`}function EH(e,t){e.if(ge.default.valCxt,()=>{e.var(ge.default.instancePath,(0,ue._)`${ge.default.valCxt}.${ge.default.instancePath}`),e.var(ge.default.parentData,(0,ue._)`${ge.default.valCxt}.${ge.default.parentData}`),e.var(ge.default.parentDataProperty,(0,ue._)`${ge.default.valCxt}.${ge.default.parentDataProperty}`),e.var(ge.default.rootData,(0,ue._)`${ge.default.valCxt}.${ge.default.rootData}`),t.dynamicRef&&e.var(ge.default.dynamicAnchors,(0,ue._)`${ge.default.valCxt}.${ge.default.dynamicAnchors}`)},()=>{e.var(ge.default.instancePath,(0,ue._)`""`),e.var(ge.default.parentData,(0,ue._)`undefined`),e.var(ge.default.parentDataProperty,(0,ue._)`undefined`),e.var(ge.default.rootData,ge.default.data),t.dynamicRef&&e.var(ge.default.dynamicAnchors,(0,ue._)`{}`)})}function CH(e){let{schema:t,opts:r,gen:n}=e;xI(e,()=>{r.$comment&&t.$comment&&$I(e),OH(e),n.let(ge.default.vErrors,null),n.let(ge.default.errors,0),r.unevaluated&&_H(e),jI(e),$H(e)})}function _H(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,ue._)`${r}.evaluated`),t.if((0,ue._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,ue._)`${e.evaluated}.props`,(0,ue._)`undefined`)),t.if((0,ue._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,ue._)`${e.evaluated}.items`,(0,ue._)`undefined`))}function EI(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,ue._)`/*# sourceURL=${r} */`:ue.nil}function IH(e,t){if(OI(e)&&(TI(e),PI(e))){xH(e,t);return}(0,II.boolOrEmptySchema)(e,t)}function PI({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function OI(e){return typeof e.schema!="boolean"}function xH(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&$I(e),TH(e),jH(e);let o=n.const("_errs",ge.default.errors);jI(e,o),n.var(t,(0,ue._)`${o} === ${ge.default.errors}`)}function TI(e){(0,ji.checkUnknownRules)(e),PH(e)}function jI(e,t){if(e.opts.jtd)return CI(e,[],!1,t);let r=(0,SI.getSchemaTypes)(e.schema),n=(0,SI.coerceAndCheckDataType)(e,r);CI(e,r,!n,t)}function PH(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ji.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function OH(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ji.checkStrictMode)(e,"default is ignored in the schema root")}function TH(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,RH.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function jH(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function $I({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)e.code((0,ue._)`${ge.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let a=(0,ue.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,ue._)`${ge.default.self}.opts.$comment(${o}, ${a}, ${s}.schema)`)}}function $H(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if((0,ue._)`${ge.default.errors} === 0`,()=>t.return(ge.default.data),()=>t.throw((0,ue._)`new ${i}(${ge.default.vErrors})`)):(t.assign((0,ue._)`${n}.errors`,ge.default.vErrors),o.unevaluated&&DH(e),t.return((0,ue._)`${ge.default.errors} === 0`))}function DH({gen:e,evaluated:t,props:r,items:n}){r instanceof ue.Name&&e.assign((0,ue._)`${t}.props`,r),n instanceof ue.Name&&e.assign((0,ue._)`${t}.items`,n)}function CI(e,t,r,n){let{gen:i,schema:o,data:a,allErrors:s,opts:c,self:l}=e,{RULES:u}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,ji.schemaHasRulesButRef)(o,u))){i.block(()=>BI(e,"$ref",u.all.$ref.definition));return}c.jtd||BH(e,t),i.block(()=>{for(let d of u.rules)f(d);f(u.post)});function f(d){(0,Ty.shouldUseGroup)(o,d)&&(d.type?(i.if((0,jp.checkDataType)(d.type,a,c.strictNumbers)),_I(e,d),t.length===1&&t[0]===d.type&&r&&(i.else(),(0,jp.reportTypeError)(e)),i.endIf()):_I(e,d),s||i.if((0,ue._)`${ge.default.errors} === ${n||0}`))}}function _I(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,AH.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0,Ty.shouldUseRule)(n,o)&&BI(e,o.keyword,o.definition,t.type)})}function BH(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(WH(e,t),e.opts.allowUnionTypes||LH(e,t),qH(e,e.dataTypes))}function WH(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{DI(e.dataTypes,r)||jy(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),MH(e,t)}}function LH(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&jy(e,"use allowUnionTypes to allow union type keyword")}function qH(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Ty.shouldUseRule)(e.schema,i)){let{type:o}=i.definition;o.length&&!o.some(a=>VH(t,a))&&jy(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function VH(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function DI(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function MH(e,t){let r=[];for(let n of e.dataTypes)DI(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function jy(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ji.checkStrictMode)(e,t,e.opts.strictTypes)}var $p=class{constructor(t,r,n){if((0,du.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ji.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",WI(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,du.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",ge.default.errors))}result(t,r,n){this.failResult((0,ue.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,ue.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,ue._)`${r} !== undefined && (${(0,ue.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?uu.reportExtraError:uu.reportError)(this,this.def.error,r)}$dataError(){(0,uu.reportError)(this,this.def.$dataError||uu.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,uu.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=ue.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=ue.nil,r=ue.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:a}=this;n.if((0,ue.or)((0,ue._)`${i} === undefined`,r)),t!==ue.nil&&n.assign(t,!0),(o.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==ue.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,ue.or)(a(),s());function a(){if(n.length){if(!(r instanceof ue.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,ue._)`${(0,jp.checkDataTypes)(c,r,o.opts.strictNumbers,jp.DataType.Wrong)}`}return ue.nil}function s(){if(i.validateSchema){let c=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,ue._)`!${c}(${r})`}return ue.nil}}subschema(t,r){let n=(0,Oy.getSubschema)(this.it,t);(0,Oy.extendSubschemaData)(n,this.it,t),(0,Oy.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return IH(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ji.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ji.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,ue.Name)),!0}};Po.KeywordCxt=$p;function BI(e,t,r,n){let i=new $p(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,du.funcKeywordCode)(i,r):"macro"in r?(0,du.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,du.funcKeywordCode)(i,r)}var FH=/^\/(?:[^~]|~0|~1)*$/,HH=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function WI(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(e==="")return ge.default.rootData;if(e[0]==="/"){if(!FH.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=ge.default.rootData}else{let l=HH.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(o=r[t-u],!i)return o}let a=o,s=i.split("/");for(let l of s)l&&(o=(0,ue._)`${o}${(0,ue.getProperty)((0,ji.unescapeJsonPointer)(l))}`,a=(0,ue._)`${a} && ${o}`);return a;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Po.getData=WI});var Dp=D(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var $y=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Dy.default=$y});var pu=D(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var By=lu(),Wy=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,By.resolveUrl)(t,r,n),this.missingSchema=(0,By.normalizeId)((0,By.getFullPath)(t,this.missingRef))}};Ly.default=Wy});var Wp=D(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.resolveSchema=kn.getCompilingSchema=kn.resolveRef=kn.compileSchema=kn.SchemaEnv=void 0;var Ln=Ee(),QH=Dp(),Na=Ti(),qn=lu(),LI=je(),UH=fu(),Ms=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,qn.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};kn.SchemaEnv=Ms;function Vy(e){let t=qI.call(this,e);if(t)return t;let r=(0,qn.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,a=new Ln.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),s;e.$async&&(s=a.scopeValue("Error",{ref:QH.default,code:(0,Ln._)`require("ajv/dist/runtime/validation_error").default`}));let c=a.scopeName("validate");e.validateName=c;let l={gen:a,allErrors:this.opts.allErrors,data:Na.default.data,parentData:Na.default.parentData,parentDataProperty:Na.default.parentDataProperty,dataNames:[Na.default.data],dataPathArr:[Ln.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ln.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ln.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ln._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,UH.validateFunctionCode)(l),a.optimize(this.opts.code.optimize);let f=a.toString();u=`${a.scopeRefs(Na.default.scope)}return ${f}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let m=new Function(`${Na.default.self}`,`${Na.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:f,scopeValues:a._values}),this.opts.unevaluated){let{props:h,items:p}=l;m.evaluated={props:h instanceof Ln.Name?void 0:h,items:p instanceof Ln.Name?void 0:p,dynamicProps:h instanceof Ln.Name,dynamicItems:p instanceof Ln.Name},m.source&&(m.source.evaluated=(0,Ln.stringify)(m.evaluated))}return e.validate=m,e}catch(f){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),f}finally{this._compilations.delete(e)}}kn.compileSchema=Vy;function JH(e,t,r){var n;r=(0,qn.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let o=GH.call(this,e,r);if(o===void 0){let a=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;a&&(o=new Ms({schema:a,schemaId:s,root:e,baseId:t}))}if(o!==void 0)return e.refs[r]=zH.call(this,o)}kn.resolveRef=JH;function zH(e){return(0,qn.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Vy.call(this,e)}function qI(e){for(let t of this._compilations)if(KH(t,e))return t}kn.getCompilingSchema=qI;function KH(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function GH(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Bp.call(this,e,t)}function Bp(e,t){let r=this.opts.uriResolver.parse(t),n=(0,qn._getFullPath)(this.opts.uriResolver,r),i=(0,qn.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return qy.call(this,r,e);let o=(0,qn.normalizeId)(n),a=this.refs[o]||this.schemas[o];if(typeof a=="string"){let s=Bp.call(this,e,a);return typeof s?.schema!="object"?void 0:qy.call(this,r,s)}if(typeof a?.schema=="object"){if(a.validate||Vy.call(this,a),o===(0,qn.normalizeId)(t)){let{schema:s}=a,{schemaId:c}=this.opts,l=s[c];return l&&(i=(0,qn.resolveUrl)(this.opts.uriResolver,i,l)),new Ms({schema:s,schemaId:c,root:e,baseId:i})}return qy.call(this,r,a)}}kn.resolveSchema=Bp;var YH=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qy(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,LI.unescapeFragment)(s)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!YH.has(s)&&l&&(t=(0,qn.resolveUrl)(this.opts.uriResolver,t,l))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,LI.schemaHasRulesButRef)(r,this.RULES)){let s=(0,qn.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=Bp.call(this,n,s)}let{schemaId:a}=this.opts;if(o=o||new Ms({schema:r,schemaId:a,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var VI=D((dZ,XH)=>{XH.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Jy=D((fZ,KI)=>{"use strict";var ZH=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Fy=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),eQ=RegExp.prototype.test.bind(/^\d*$/u),Sa=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Hy=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),FI=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Qy=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),tQ=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Vr=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)Vr[t]="%"+e[t>>4]+e[t&15]}function ar(e){return e<2048?Vr[192|e>>6]+Vr[128|e&63]:e<65536?Vr[224|e>>12]+Vr[128|e>>6&63]+Vr[128|e&63]:Vr[240|e>>18]+Vr[128|e>>12&63]+Vr[128|e>>6&63]+Vr[128|e&63]}function rQ(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var nQ=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),iQ=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),oQ=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),aQ=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function sQ(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!oQ(e[t])){if(e[t]==="%"&&t+2<e.length&&Sa(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function MI(e){let t=-1,r=0,n=-1,i=0;for(let s=0;s<e.length;s++)e[s]==="0"?(n===-1&&(n=s),i++,i>r&&(r=i,t=n)):(n=-1,i=0);if(r<2)return e.join(":");let o=e.slice(0,t).join(":"),a=e.slice(t+r).join(":");return o+"::"+a}function cQ(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=r.concat(n),o=0;for(let s=0;s<i.length;s++){let c=i[s];if(c==="")return;if(c.indexOf(".")!==-1){if(s!==i.length-1||t!==-1&&n.length===0||!Fy(c))return;o+=2;continue}if(!nQ(c))return;i[s]=parseInt(c,16).toString(16),o++}if(t===-1)return o!==8?void 0:MI(i);if(o>=8)return;let a=i.slice(0,r.length);for(let s=o;s<8;s++)a.push("0");for(let s=r.length;s<i.length;s++)a.push(i[s]);return MI(a)}function My(e){let t=e[0]==="["&&e[e.length-1]==="]";if((e[0]==="["||e[e.length-1]==="]")&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&iQ(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(lQ(n,":")<2)return{host:e,isIPV6:!1,error:t};let i="",o=n.indexOf("%");if(o!==-1){let s=n.slice(o,o+3).toLowerCase()==="%25"?3:1;if(i=n.slice(o+s),!sQ(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,o)}let a=cQ(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(i?"%"+i:""),escapedHost:a+(i?"%25"+i:""),isIPV6:!0}}function lQ(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function HI(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function uQ(e){if(e===""||e[0]==="/")return HI(e);let t=e.split("/"),r=t.length-1,n=[],i=!1;for(let o=0;o<=r;o++){let a=t[o];a==="."||a===".."?(a===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),i=o===r):n.push(a)}return i&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var dQ={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},fQ=/[@/?#:]/g,pQ=/[@/?#]/g;function QI(e,t){let r=t?pQ:fQ;return r.lastIndex=0,e.replace(r,n=>dQ[n])}function UI(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(Sa(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));t&&Hy(a)?r+=a:r+="%"+o,n+=2;continue}}r+=e[n]}return r}function mQ(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(Sa(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));a!=="."&&Hy(a)?t+=a:t+="%"+o,r+=2;continue}}if(FI(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=zI(i)?n:Vr[i];else if(i<55296||i>57343)t+=ar(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=ar(65536+(i-55296<<10)+(o-56320)),r++):t+=ar(65533)}else t+=ar(65533)}}return t}function hQ(e,t=!1){let r="",n=t&&e[0]!=="/";for(let i=0;i<e.length;i++){let o=e[i];if(o==="%"&&i+2<e.length){let a=e.slice(i+1,i+3);if(Sa(a)){r+="%"+a.toUpperCase(),i+=2;continue}}if(o==="/"&&(n=!1),FI(o)&&(o!==":"||!n))r+=o;else{let a=e.charCodeAt(i);if(a<128)r+=Vr[a];else if(a<55296||a>57343)r+=ar(a);else if(a<=56319&&i+1<e.length){let s=e.charCodeAt(i+1);s>=56320&&s<=57343?(r+=ar(65536+(a-55296<<10)+(s-56320)),i++):r+=ar(65533)}else r+=ar(65533)}}return r}function Uy(e,t){let r="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Sa(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(t(i))r+=i;else{let o=e.charCodeAt(n);if(o<128)r+=Vr[o];else if(o<55296||o>57343)r+=ar(o);else if(o<=56319&&n+1<e.length){let a=e.charCodeAt(n+1);a>=56320&&a<=57343?(r+=ar(65536+(o-55296<<10)+(a-56320)),n++):r+=ar(65533)}else r+=ar(65533)}}return r}function JI(e){return Uy(e,tQ)}function gQ(e){return Uy(e,Qy)}function vQ(e){return Uy(e,Qy)}function zI(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function wQ(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(Sa(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));Hy(a)?t+=a:t+="%"+o,r+=2;continue}}if(Qy(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=zI(i)?n:Vr[i];else if(i<55296||i>57343)t+=ar(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=ar(65536+(i-55296<<10)+(o-56320)),r++):t+=ar(65533)}else t+=ar(65533)}}return t}function yQ(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Sa(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function kQ(e){let t=[];if(e.userinfo!==void 0&&(t.push(JI(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!Fy(r)){let n=My(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=UI(r,!0),n=My(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=QI(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!eQ(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}KI.exports={nonSimpleDomain:aQ,recomposeAuthority:kQ,reescapeHostDelimiters:QI,normalizePercentEncoding:UI,normalizePathEncoding:mQ,serializePathEncoding:hQ,normalizeQueryFragmentEncoding:wQ,encodeUserinfo:JI,encodeQuery:gQ,encodeFragment:vQ,escapePreservingEscapes:yQ,removeDotSegments:HI,removeDotSegmentsRelative:uQ,isIPv4:Fy,isUUID:ZH,normalizeIPv6:My,stringArrayToHexStripped:rQ}});var ex=D((pZ,ZI)=>{"use strict";var{isUUID:bQ}=Jy(),AQ=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,RQ=["http","https","ws","wss","urn","urn:uuid"];function NQ(e){return RQ.indexOf(e)!==-1}function zy(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function GI(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function YI(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function SQ(e){return e.secure=zy(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function EQ(e){if((e.port===(zy(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function CQ(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(AQ);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,o=Ky(i);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function _Q(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,o=Ky(i);o&&(e=o.serialize(e,t));let a=e,s=e.nss;return a.path=`${n||t.nid}:${s}`,t.skipEscape=!0,a}function IQ(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!bQ(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function xQ(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var XI={scheme:"http",domainHost:!0,parse:GI,serialize:YI},PQ={scheme:"https",domainHost:XI.domainHost,parse:GI,serialize:YI},Lp={scheme:"ws",domainHost:!0,parse:SQ,serialize:EQ},OQ={scheme:"wss",domainHost:Lp.domainHost,parse:Lp.parse,serialize:Lp.serialize},TQ={scheme:"urn",parse:CQ,serialize:_Q,skipNormalize:!0},jQ={scheme:"urn:uuid",parse:IQ,serialize:xQ,skipNormalize:!0},qp={http:XI,https:PQ,ws:Lp,wss:OQ,urn:TQ,"urn:uuid":jQ};Object.setPrototypeOf(qp,null);function Ky(e){return e&&(qp[e]||qp[e.toLowerCase()])||void 0}ZI.exports={wsIsSecure:zy,SCHEMES:qp,isValidSchemeName:NQ,getSchemeHandler:Ky}});var hx=D((mZ,Qp)=>{"use strict";var{normalizeIPv6:ox,removeDotSegments:hu,removeDotSegmentsRelative:ax,recomposeAuthority:$Q,normalizePercentEncoding:Gy,normalizePathEncoding:DQ,serializePathEncoding:tx,normalizeQueryFragmentEncoding:rx,encodeQuery:BQ,encodeFragment:WQ,reescapeHostDelimiters:LQ,isIPv4:sx,nonSimpleDomain:qQ}=Jy(),{SCHEMES:cx,getSchemeHandler:Yy}=ex(),lx=/^[A-Za-z][A-Za-z0-9+.-]*$/u,ux="URI scheme is malformed.",Vp="URI host is malformed.",VQ=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function nx(e){let t=String(e);if(!lx.test(t))throw new TypeError(ux);return t}function MQ(e,t){return typeof e=="string"?e=YQ(e,t):typeof e=="object"&&(e=Fp(Ea(e,t),t)),e}function FQ(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:o,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:c,malformedScheme:l}=Mp(e,n),{parsed:u,malformedAuthorityOrPort:f,malformedPercentEncoding:d,malformedSchemeSpecific:m,malformedHost:h,malformedScheme:p}=Mp(t,n);if(o||f||a||d||s||m||c||h||l||p)throw new Error(i.error||u.error||"URI is malformed.");let g=dx(i,u,n,!0),v=Yy(r&&r.scheme||g.scheme),w=g.host,y=w!==void 0&&w!==""&&(sx(w)||ox(w).isIPV6);if(px(g,r||{},v,y))throw new Error(Vp);fx(g,r||{},v,y);let b=w&&w.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(w);if(g.error&&!b)throw new Error(g.error);return n.skipEscape=!0,Ea(g,n)}function dx(e,t,r,n){let i={};if(n||(e=Fp(Ea(e,r),r),t=Fp(Ea(t,r),r)),r=r||{},!r.tolerant&&t.scheme)i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=hu(t.path||""),i.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=hu(t.path||""),i.query=t.query;else{if(!t.path)i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query;else{if(t.path[0]==="/")i.path=hu(t.path);else{let o=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;o&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=e.scheme===void 0&&!o&&i.path[0]!=="/"?ax(i.path):hu(i.path)}i.query=t.query}i.userinfo=e.userinfo,i.host=e.host,i.port=e.port}i.scheme=e.scheme}return i.fragment=t.fragment,i}function HQ(e,t,r){let n=ix(e,r),i=ix(t,r);return n!==void 0&&i!==void 0&&n===i}function Ea(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[];r.scheme&&(r.scheme=nx(r.scheme));let o=Yy(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n);let a=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,s=(r.scheme===void 0||n.reference==="suffix")&&!a,c=!n.skipEscape&&s;r.path!==void 0&&(n.skipEscape?r.path=Gy(r.path):r.path=tx(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=nx(r.scheme),i.push(r.scheme,":"));let l=$Q(r);if(l!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(l),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(u=s&&u[0]!=="/"?ax(u):hu(u)),s&&(u=tx(u,!0)),l===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),i.push(u)}return r.query!==void 0&&i.push("?",BQ(r.query)),r.fragment!==void 0&&i.push("#",WQ(r.fragment)),i.join("")}var QQ=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,UQ=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,JQ=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function zQ(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function mu(e){if(e===void 0)return!1;let t=e.indexOf("%");for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function Hp(e){return e[0]==="["&&e[e.length-1]==="]"}function KQ(e){let t=e[4];return mu(e[3])||t!==void 0&&!Hp(t)&&mu(t)||mu(e[6])||mu(e[7])||mu(e[8])}function fx(e,t,r,n){if(px(e,t,r,n))return e.error=e.error||Vp,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!Hp(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&qQ(e.host)){let i;try{i=new URL("http://"+e.host)}catch(o){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+o,!0}if(!GQ(i))return e.error=e.error||Vp,!0;e.host=i.hostname}return!1}function px(e,t,r,n){return!!(e.host&&n===!1&&!Hp(e.host)&&(t.domainHost||r&&r.domainHost)&&VQ.test(e.host))}function GQ(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Mp(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,o=!1,a=!1,s=!1,c=!1,l=!1,u=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let f=e.match(UQ);f!==null&&f[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let d=e.match(JQ);if(d!==null){let h=d[1],p=h.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):h.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let m=e.match(QQ);if(m){n.scheme=m[1],n.userinfo=m[3],n.host=m[4],n.port=parseInt(m[5],10),n.path=m[6]||"",n.query=m[7],n.fragment=m[8],n.scheme!==void 0&&(lx.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||ux,l=!0)),o=KQ(m),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=m[5]);let h=zQ(n,m);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(sx(n.host)===!1){let v=Hp(n.host),w=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=ox(n.host);u=y.isIPV6||y.isIPVFuture===!0,c=w&&(!v||y.error===!0),n.host=u?y.host:y.host.toLowerCase(),c&&(n.error=n.error||Vp,i=!0)}else u=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let p=Yy(r.scheme||n.scheme);if(c||(s=fx(n,r,p,u)),e.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=u?n.host:Gy(n.host,!0);u||(g=Gy(g.toLowerCase())),n.host=u||r.scheme!=="null"?LQ(g,u):g}(!p||p&&!p.skipNormalize)&&(n.path&&(n.path=DQ(n.path)),n.query&&(n.query=rx(n.query)),n.fragment&&(n.fragment=rx(n.fragment))),p&&p.parse&&(p.parse(n,r),p===cx.urn&&n.nid===void 0&&(a=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:l}}function Fp(e,t){return Mp(e,t).parsed}function YQ(e,t){return mx(e,t).normalized}function mx(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}=Mp(e,t);return{normalized:n||i||o||a||s?e:Ea(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}}function ix(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Ea(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:c}=mx(r,t);return i||o||a||s||c?void 0:n}var Xy={SCHEMES:cx,normalize:MQ,resolve:FQ,resolveComponent:dx,equal:HQ,serialize:Ea,parse:Fp};Qp.exports=Xy;Qp.exports.default=Xy;Qp.exports.fastUri=Xy});var vx=D(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});var gx=hx();gx.code='require("ajv/dist/runtime/uri").default';Zy.default=gx});var Sx=D(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.CodeGen=zt.Name=zt.nil=zt.stringify=zt.str=zt._=zt.KeywordCxt=void 0;var XQ=fu();Object.defineProperty(zt,"KeywordCxt",{enumerable:!0,get:function(){return XQ.KeywordCxt}});var Fs=Ee();Object.defineProperty(zt,"_",{enumerable:!0,get:function(){return Fs._}});Object.defineProperty(zt,"str",{enumerable:!0,get:function(){return Fs.str}});Object.defineProperty(zt,"stringify",{enumerable:!0,get:function(){return Fs.stringify}});Object.defineProperty(zt,"nil",{enumerable:!0,get:function(){return Fs.nil}});Object.defineProperty(zt,"Name",{enumerable:!0,get:function(){return Fs.Name}});Object.defineProperty(zt,"CodeGen",{enumerable:!0,get:function(){return Fs.CodeGen}});var ZQ=Dp(),Ax=pu(),eU=Ay(),gu=Wp(),tU=Ee(),vu=lu(),Up=cu(),tk=je(),wx=VI(),rU=vx(),Rx=(e,t)=>new RegExp(e,t);Rx.code="new RegExp";var nU=["removeAdditional","useDefaults","coerceTypes"],iU=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),oU={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},aU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},yx=200;function sU(e){var t,r,n,i,o,a,s,c,l,u,f,d,m,h,p,g,v,w,y,b,N,A,S,_,Q;let F=e.strict,K=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=K===!0||K===void 0?1:K||0,re=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Rx,X=(i=e.uriResolver)!==null&&i!==void 0?i:rU.default;return{strictSchema:(a=(o=e.strictSchema)!==null&&o!==void 0?o:F)!==null&&a!==void 0?a:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:F)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:F)!==null&&u!==void 0?u:"log",strictTuples:(d=(f=e.strictTuples)!==null&&f!==void 0?f:F)!==null&&d!==void 0?d:"log",strictRequired:(h=(m=e.strictRequired)!==null&&m!==void 0?m:F)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:Z,regExp:re}:{optimize:Z,regExp:re},loopRequired:(p=e.loopRequired)!==null&&p!==void 0?p:yx,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:yx,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(y=e.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(b=e.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(N=e.addUsedSchema)!==null&&N!==void 0?N:!0,validateSchema:(A=e.validateSchema)!==null&&A!==void 0?A:!0,validateFormats:(S=e.validateFormats)!==null&&S!==void 0?S:!0,unicodeRegExp:(_=e.unicodeRegExp)!==null&&_!==void 0?_:!0,int32range:(Q=e.int32range)!==null&&Q!==void 0?Q:!0,uriResolver:X}}var wu=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...sU(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new tU.ValueScope({scope:{},prefixes:iU,es5:r,lines:n}),this.logger=pU(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,eU.getRules)(),kx.call(this,oU,t,"NOT SUPPORTED"),kx.call(this,aU,t,"DEPRECATED","warn"),this._metaOpts=dU.call(this),t.formats&&lU.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&uU.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),cU.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=wx;n==="id"&&(i={...wx},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(u,f){await o.call(this,u.$schema);let d=this._addSchema(u,f);return d.validate||a.call(this,d)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function a(u){try{return this._compileSchemaEnv(u)}catch(f){if(!(f instanceof Ax.default))throw f;return s.call(this,f),await c.call(this,f.missingSchema),a.call(this,u)}}function s({missingSchema:u,missingRef:f}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${f} cannot be resolved`)}async function c(u){let f=await l.call(this,u);this.refs[u]||await o.call(this,f.$schema),this.refs[u]||this.addSchema(f,u,r)}async function l(u){let f=this._loading[u];if(f)return f;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let a of t)this.addSchema(a,void 0,n,i);return this}let o;if(typeof t=="object"){let{schemaId:a}=this.opts;if(o=t[a],o!==void 0&&typeof o!="string")throw new Error(`schema ${a} must be string`)}return r=(0,vu.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(t){let r;for(;typeof(r=bx.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new gu.SchemaEnv({schema:{},schemaId:n});if(r=gu.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=bx.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,vu.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(hU.call(this,n,r),!r)return(0,tk.eachItem)(n,o=>ek.call(this,o)),this;vU.call(this,r);let i={...r,type:(0,Up.getJSONTypes)(r.type),schemaType:(0,Up.getJSONTypes)(r.schemaType)};return(0,tk.eachItem)(n,i.type.length===0?o=>ek.call(this,o,i):o=>i.type.forEach(a=>ek.call(this,o,i,a))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let o=i.split("/").slice(1),a=t;for(let s of o)a=a[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:l}=c.definition,u=a[s];l&&u&&(a[s]=Nx(u))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof t=="object")a=t[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,vu.normalizeId)(a||n);let l=vu.getSchemaRefs.call(this,t,n);return c=new gu.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):gu.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{gu.compileSchema.call(this,t)}finally{this.opts=r}}};wu.ValidationError=ZQ.default;wu.MissingRefError=Ax.default;zt.default=wu;function kx(e,t,r,n="error"){for(let i in e){let o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function bx(e){return e=(0,vu.normalizeId)(e),this.schemas[e]||this.refs[e]}function cU(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function lU(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function uU(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function dU(){let e={...this.opts};for(let t of nU)delete e[t];return e}var fU={log(){},warn(){},error(){}};function pU(e){if(e===!1)return fU;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var mU=/^[a-z_$][a-z0-9_$:-]*$/i;function hU(e,t){let{RULES:r}=this;if((0,tk.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mU.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function ek(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,a=i?o.post:o.rules.find(({type:c})=>c===r);if(a||(a={type:r,rules:[]},o.rules.push(a)),o.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,Up.getJSONTypes)(t.type),schemaType:(0,Up.getJSONTypes)(t.schemaType)}};t.before?gU.call(this,a,s,t.before):a.rules.push(s),o.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function gU(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function vU(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Nx(t)),e.validateSchema=this.compile(t,!0))}var wU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Nx(e){return{anyOf:[e,wU]}}});var Ex=D(rk=>{"use strict";Object.defineProperty(rk,"__esModule",{value:!0});var yU={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};rk.default=yU});var xx=D(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.callRef=Ca.getValidate=void 0;var kU=pu(),Cx=yn(),Mr=Ee(),Hs=Ti(),_x=Wp(),Jp=je(),bU={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:o,validateName:a,opts:s,self:c}=n,{root:l}=o;if((r==="#"||r==="#/")&&i===l.baseId)return f();let u=_x.resolveRef.call(c,l,i,r);if(u===void 0)throw new kU.default(n.opts.uriResolver,i,r);if(u instanceof _x.SchemaEnv)return d(u);return m(u);function f(){if(o===l)return zp(e,a,o,o.$async);let h=t.scopeValue("root",{ref:l});return zp(e,(0,Mr._)`${h}.validate`,l,l.$async)}function d(h){let p=Ix(e,h);zp(e,p,h,h.$async)}function m(h){let p=t.scopeValue("schema",s.code.source===!0?{ref:h,code:(0,Mr.stringify)(h)}:{ref:h}),g=t.name("valid"),v=e.subschema({schema:h,dataTypes:[],schemaPath:Mr.nil,topSchemaRef:p,errSchemaPath:r},g);e.mergeEvaluated(v),e.ok(g)}}};function Ix(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Mr._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Ca.getValidate=Ix;function zp(e,t,r,n){let{gen:i,it:o}=e,{allErrors:a,schemaEnv:s,opts:c}=o,l=c.passContext?Hs.default.this:Mr.nil;n?u():f();function u(){if(!s.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,Mr._)`await ${(0,Cx.callValidateCode)(e,t,l)}`),m(t),a||i.assign(h,!0)},p=>{i.if((0,Mr._)`!(${p} instanceof ${o.ValidationError})`,()=>i.throw(p)),d(p),a||i.assign(h,!1)}),e.ok(h)}function f(){e.result((0,Cx.callValidateCode)(e,t,l),()=>m(t),()=>d(t))}function d(h){let p=(0,Mr._)`${h}.errors`;i.assign(Hs.default.vErrors,(0,Mr._)`${Hs.default.vErrors} === null ? ${p} : ${Hs.default.vErrors}.concat(${p})`),i.assign(Hs.default.errors,(0,Mr._)`${Hs.default.vErrors}.length`)}function m(h){var p;if(!o.opts.unevaluated)return;let g=(p=r?.validate)===null||p===void 0?void 0:p.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=Jp.mergeEvaluated.props(i,g.props,o.props));else{let v=i.var("props",(0,Mr._)`${h}.evaluated.props`);o.props=Jp.mergeEvaluated.props(i,v,o.props,Mr.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=Jp.mergeEvaluated.items(i,g.items,o.items));else{let v=i.var("items",(0,Mr._)`${h}.evaluated.items`);o.items=Jp.mergeEvaluated.items(i,v,o.items,Mr.Name)}}}Ca.callRef=zp;Ca.default=bU});var Px=D(nk=>{"use strict";Object.defineProperty(nk,"__esModule",{value:!0});var AU=Ex(),RU=xx(),NU=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",AU.default,RU.default];nk.default=NU});var Ox=D(ik=>{"use strict";Object.defineProperty(ik,"__esModule",{value:!0});var Kp=Ee(),Oo=Kp.operators,Gp={maximum:{okStr:"<=",ok:Oo.LTE,fail:Oo.GT},minimum:{okStr:">=",ok:Oo.GTE,fail:Oo.LT},exclusiveMaximum:{okStr:"<",ok:Oo.LT,fail:Oo.GTE},exclusiveMinimum:{okStr:">",ok:Oo.GT,fail:Oo.LTE}},SU={message:({keyword:e,schemaCode:t})=>(0,Kp.str)`must be ${Gp[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Kp._)`{comparison: ${Gp[e].okStr}, limit: ${t}}`},EU={keyword:Object.keys(Gp),type:"number",schemaType:"number",$data:!0,error:SU,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Kp._)`${r} ${Gp[t].fail} ${n} || isNaN(${r})`)}};ik.default=EU});var Tx=D(ok=>{"use strict";Object.defineProperty(ok,"__esModule",{value:!0});var yu=Ee(),CU={message:({schemaCode:e})=>(0,yu.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,yu._)`{multipleOf: ${e}}`},_U={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:CU,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,o=i.opts.multipleOfPrecision,a=t.let("res"),s=o?(0,yu._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${o}`:(0,yu._)`${a} !== parseInt(${a})`;e.fail$data((0,yu._)`(${n} === 0 || (${a} = ${r}/${n}, ${s}))`)}};ok.default=_U});var $x=D(ak=>{"use strict";Object.defineProperty(ak,"__esModule",{value:!0});function jx(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}ak.default=jx;jx.code='require("ajv/dist/runtime/ucs2length").default'});var Dx=D(sk=>{"use strict";Object.defineProperty(sk,"__esModule",{value:!0});var _a=Ee(),IU=je(),xU=$x(),PU={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,_a.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,_a._)`{limit: ${e}}`},OU={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:PU,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,o=t==="maxLength"?_a.operators.GT:_a.operators.LT,a=i.opts.unicode===!1?(0,_a._)`${r}.length`:(0,_a._)`${(0,IU.useFunc)(e.gen,xU.default)}(${r})`;e.fail$data((0,_a._)`${a} ${o} ${n}`)}};sk.default=OU});var Bx=D(ck=>{"use strict";Object.defineProperty(ck,"__esModule",{value:!0});var TU=yn(),jU=je(),Qs=Ee(),$U={message:({schemaCode:e})=>(0,Qs.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Qs._)`{pattern: ${e}}`},DU={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:$U,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:a}=e,s=a.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=a.opts.code,l=c.code==="new RegExp"?(0,Qs._)`new RegExp`:(0,jU.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,Qs._)`${l}(${o}, ${s}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,Qs._)`!${u}`)}else{let c=(0,TU.usePattern)(e,i);e.fail$data((0,Qs._)`!${c}.test(${r})`)}}};ck.default=DU});var Wx=D(lk=>{"use strict";Object.defineProperty(lk,"__esModule",{value:!0});var ku=Ee(),BU={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,ku.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,ku._)`{limit: ${e}}`},WU={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:BU,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?ku.operators.GT:ku.operators.LT;e.fail$data((0,ku._)`Object.keys(${r}).length ${i} ${n}`)}};lk.default=WU});var Lx=D(uk=>{"use strict";Object.defineProperty(uk,"__esModule",{value:!0});var bu=yn(),Au=Ee(),LU=je(),qU={message:({params:{missingProperty:e}})=>(0,Au.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Au._)`{missingProperty: ${e}}`},VU={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qU,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:o,it:a}=e,{opts:s}=a;if(!o&&r.length===0)return;let c=r.length>=s.loopRequired;if(a.allErrors?l():u(),s.strictRequired){let m=e.parentSchema.properties,{definedProperties:h}=e.it;for(let p of r)if(m?.[p]===void 0&&!h.has(p)){let g=a.schemaEnv.baseId+a.errSchemaPath,v=`required property "${p}" is not defined at "${g}" (strictRequired)`;(0,LU.checkStrictMode)(a,v,a.opts.strictRequired)}}function l(){if(c||o)e.block$data(Au.nil,f);else for(let m of r)(0,bu.checkReportMissingProp)(e,m)}function u(){let m=t.let("missing");if(c||o){let h=t.let("valid",!0);e.block$data(h,()=>d(m,h)),e.ok(h)}else t.if((0,bu.checkMissingProp)(e,r,m)),(0,bu.reportMissingProp)(e,m),t.else()}function f(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,bu.noPropertyInData)(t,i,m,s.ownProperties),()=>e.error())})}function d(m,h){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(h,(0,bu.propertyInData)(t,i,m,s.ownProperties)),t.if((0,Au.not)(h),()=>{e.error(),t.break()})},Au.nil)}}};uk.default=VU});var qx=D(dk=>{"use strict";Object.defineProperty(dk,"__esModule",{value:!0});var Ru=Ee(),MU={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Ru.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Ru._)`{limit: ${e}}`},FU={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:MU,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?Ru.operators.GT:Ru.operators.LT;e.fail$data((0,Ru._)`${r}.length ${i} ${n}`)}};dk.default=FU});var Yp=D(fk=>{"use strict";Object.defineProperty(fk,"__esModule",{value:!0});var Vx=xy();Vx.code='require("ajv/dist/runtime/equal").default';fk.default=Vx});var Mx=D(mk=>{"use strict";Object.defineProperty(mk,"__esModule",{value:!0});var pk=cu(),Kt=Ee(),HU=je(),QU=Yp(),UU={message:({params:{i:e,j:t}})=>(0,Kt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Kt._)`{i: ${e}, j: ${t}}`},JU={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:UU,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:o,schemaCode:a,it:s}=e;if(!n&&!i)return;let c=t.let("valid"),l=o.items?(0,pk.getSchemaTypes)(o.items):[];e.block$data(c,u,(0,Kt._)`${a} === false`),e.ok(c);function u(){let h=t.let("i",(0,Kt._)`${r}.length`),p=t.let("j");e.setParams({i:h,j:p}),t.assign(c,!0),t.if((0,Kt._)`${h} > 1`,()=>(f()?d:m)(h,p))}function f(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function d(h,p){let g=t.name("item"),v=(0,pk.checkDataTypes)(l,g,s.opts.strictNumbers,pk.DataType.Wrong),w=t.const("indices",(0,Kt._)`{}`);t.for((0,Kt._)`;${h}--;`,()=>{t.let(g,(0,Kt._)`${r}[${h}]`),t.if(v,(0,Kt._)`continue`),l.length>1&&t.if((0,Kt._)`typeof ${g} == "string"`,(0,Kt._)`${g} += "_"`),t.if((0,Kt._)`typeof ${w}[${g}] == "number"`,()=>{t.assign(p,(0,Kt._)`${w}[${g}]`),e.error(),t.assign(c,!1).break()}).code((0,Kt._)`${w}[${g}] = ${h}`)})}function m(h,p){let g=(0,HU.useFunc)(t,QU.default),v=t.name("outer");t.label(v).for((0,Kt._)`;${h}--;`,()=>t.for((0,Kt._)`${p} = ${h}; ${p}--;`,()=>t.if((0,Kt._)`${g}(${r}[${h}], ${r}[${p}])`,()=>{e.error(),t.assign(c,!1).break(v)})))}}};mk.default=JU});var Fx=D(gk=>{"use strict";Object.defineProperty(gk,"__esModule",{value:!0});var hk=Ee(),zU=je(),KU=Yp(),GU={message:"must be equal to constant",params:({schemaCode:e})=>(0,hk._)`{allowedValue: ${e}}`},YU={keyword:"const",$data:!0,error:GU,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0,hk._)`!${(0,zU.useFunc)(t,KU.default)}(${r}, ${i})`):e.fail((0,hk._)`${o} !== ${r}`)}};gk.default=YU});var Hx=D(vk=>{"use strict";Object.defineProperty(vk,"__esModule",{value:!0});var Nu=Ee(),XU=je(),ZU=Yp(),eJ={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Nu._)`{allowedValues: ${e}}`},tJ={keyword:"enum",schemaType:"array",$data:!0,error:eJ,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:a}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let s=i.length>=a.opts.loopEnum,c,l=()=>c??(c=(0,XU.useFunc)(t,ZU.default)),u;if(s||n)u=t.let("valid"),e.block$data(u,f);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let m=t.const("vSchema",o);u=(0,Nu.or)(...i.map((h,p)=>d(m,p)))}e.pass(u);function f(){t.assign(u,!1),t.forOf("v",o,m=>t.if((0,Nu._)`${l()}(${r}, ${m})`,()=>t.assign(u,!0).break()))}function d(m,h){let p=i[h];return typeof p=="object"&&p!==null?(0,Nu._)`${l()}(${r}, ${m}[${h}])`:(0,Nu._)`${r} === ${p}`}}};vk.default=tJ});var Qx=D(wk=>{"use strict";Object.defineProperty(wk,"__esModule",{value:!0});var rJ=Ox(),nJ=Tx(),iJ=Dx(),oJ=Bx(),aJ=Wx(),sJ=Lx(),cJ=qx(),lJ=Mx(),uJ=Fx(),dJ=Hx(),fJ=[rJ.default,nJ.default,iJ.default,oJ.default,aJ.default,sJ.default,cJ.default,lJ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uJ.default,dJ.default];wk.default=fJ});var kk=D(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.validateAdditionalItems=void 0;var Ia=Ee(),yk=je(),pJ={message:({params:{len:e}})=>(0,Ia.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Ia._)`{limit: ${e}}`},mJ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:pJ,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,yk.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ux(e,n)}};function Ux(e,t){let{gen:r,schema:n,data:i,keyword:o,it:a}=e;a.items=!0;let s=r.const("len",(0,Ia._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Ia._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,yk.alwaysValidSchema)(a,n)){let l=r.var("valid",(0,Ia._)`${s} <= ${t.length}`);r.if((0,Ia.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,s,u=>{e.subschema({keyword:o,dataProp:u,dataPropType:yk.Type.Num},l),a.allErrors||r.if((0,Ia.not)(l),()=>r.break())})}}Su.validateAdditionalItems=Ux;Su.default=mJ});var bk=D(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.validateTuple=void 0;var Jx=Ee(),Xp=je(),hJ=yn(),gJ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return zx(e,"additionalItems",t);r.items=!0,!(0,Xp.alwaysValidSchema)(r,t)&&e.ok((0,hJ.validateArray)(e))}};function zx(e,t,r=e.schema){let{gen:n,parentSchema:i,data:o,keyword:a,it:s}=e;u(i),s.opts.unevaluated&&r.length&&s.items!==!0&&(s.items=Xp.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),l=n.const("len",(0,Jx._)`${o}.length`);r.forEach((f,d)=>{(0,Xp.alwaysValidSchema)(s,f)||(n.if((0,Jx._)`${l} > ${d}`,()=>e.subschema({keyword:a,schemaProp:d,dataProp:d},c)),e.ok(c))});function u(f){let{opts:d,errSchemaPath:m}=s,h=r.length,p=h===f.minItems&&(h===f.maxItems||f[t]===!1);if(d.strictTuples&&!p){let g=`"${a}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,Xp.checkStrictMode)(s,g,d.strictTuples)}}}Eu.validateTuple=zx;Eu.default=gJ});var Kx=D(Ak=>{"use strict";Object.defineProperty(Ak,"__esModule",{value:!0});var vJ=bk(),wJ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,vJ.validateTuple)(e,"items")};Ak.default=wJ});var Yx=D(Rk=>{"use strict";Object.defineProperty(Rk,"__esModule",{value:!0});var Gx=Ee(),yJ=je(),kJ=yn(),bJ=kk(),AJ={message:({params:{len:e}})=>(0,Gx.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Gx._)`{limit: ${e}}`},RJ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:AJ,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,yJ.alwaysValidSchema)(n,t)&&(i?(0,bJ.validateAdditionalItems)(e,i):e.ok((0,kJ.validateArray)(e)))}};Rk.default=RJ});var Xx=D(Nk=>{"use strict";Object.defineProperty(Nk,"__esModule",{value:!0});var bn=Ee(),Zp=je(),NJ={message:({params:{min:e,max:t}})=>t===void 0?(0,bn.str)`must contain at least ${e} valid item(s)`:(0,bn.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,bn._)`{minContains: ${e}}`:(0,bn._)`{minContains: ${e}, maxContains: ${t}}`},SJ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:NJ,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e,a,s,{minContains:c,maxContains:l}=n;o.opts.next?(a=c===void 0?1:c,s=l):a=1;let u=t.const("len",(0,bn._)`${i}.length`);if(e.setParams({min:a,max:s}),s===void 0&&a===0){(0,Zp.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&a>s){(0,Zp.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Zp.alwaysValidSchema)(o,r)){let p=(0,bn._)`${u} >= ${a}`;s!==void 0&&(p=(0,bn._)`${p} && ${u} <= ${s}`),e.pass(p);return}o.items=!0;let f=t.name("valid");s===void 0&&a===1?m(f,()=>t.if(f,()=>t.break())):a===0?(t.let(f,!0),s!==void 0&&t.if((0,bn._)`${i}.length > 0`,d)):(t.let(f,!1),d()),e.result(f,()=>e.reset());function d(){let p=t.name("_valid"),g=t.let("count",0);m(p,()=>t.if(p,()=>h(g)))}function m(p,g){t.forRange("i",0,u,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Zp.Type.Num,compositeRule:!0},p),g()})}function h(p){t.code((0,bn._)`${p}++`),s===void 0?t.if((0,bn._)`${p} >= ${a}`,()=>t.assign(f,!0).break()):(t.if((0,bn._)`${p} > ${s}`,()=>t.assign(f,!1).break()),a===1?t.assign(f,!0):t.if((0,bn._)`${p} >= ${a}`,()=>t.assign(f,!0)))}}};Nk.default=SJ});var tP=D(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.validateSchemaDeps=ai.validatePropertyDeps=ai.error=void 0;var Sk=Ee(),EJ=je(),Cu=yn();ai.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Sk.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Sk._)`{property: ${e},
192
+ missingProperty: ${n},
193
+ depsCount: ${t},
194
+ deps: ${r}}`};var CJ={keyword:"dependencies",type:"object",schemaType:"object",error:ai.error,code(e){let[t,r]=_J(e);Zx(e,t),eP(e,r)}};function _J({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function Zx(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let a in t){let s=t[a];if(s.length===0)continue;let c=(0,Cu.propertyInData)(r,n,a,i.opts.ownProperties);e.setParams({property:a,depsCount:s.length,deps:s.join(", ")}),i.allErrors?r.if(c,()=>{for(let l of s)(0,Cu.checkReportMissingProp)(e,l)}):(r.if((0,Sk._)`${c} && (${(0,Cu.checkMissingProp)(e,s,o)})`),(0,Cu.reportMissingProp)(e,o),r.else())}}ai.validatePropertyDeps=Zx;function eP(e,t=e.schema){let{gen:r,data:n,keyword:i,it:o}=e,a=r.name("valid");for(let s in t)(0,EJ.alwaysValidSchema)(o,t[s])||(r.if((0,Cu.propertyInData)(r,n,s,o.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:s},a);e.mergeValidEvaluated(c,a)},()=>r.var(a,!0)),e.ok(a))}ai.validateSchemaDeps=eP;ai.default=CJ});var nP=D(Ek=>{"use strict";Object.defineProperty(Ek,"__esModule",{value:!0});var rP=Ee(),IJ=je(),xJ={message:"property name must be valid",params:({params:e})=>(0,rP._)`{propertyName: ${e.propertyName}}`},PJ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xJ,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,IJ.alwaysValidSchema)(i,r))return;let o=t.name("valid");t.forIn("key",n,a=>{e.setParams({propertyName:a}),e.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},o),t.if((0,rP.not)(o),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(o)}};Ek.default=PJ});var _k=D(Ck=>{"use strict";Object.defineProperty(Ck,"__esModule",{value:!0});var em=yn(),Vn=Ee(),OJ=Ti(),tm=je(),TJ={message:"must NOT have additional properties",params:({params:e})=>(0,Vn._)`{additionalProperty: ${e.additionalProperty}}`},jJ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:TJ,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:o,it:a}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=a;if(a.props=!0,c.removeAdditional!=="all"&&(0,tm.alwaysValidSchema)(a,r))return;let l=(0,em.allSchemaProperties)(n.properties),u=(0,em.allSchemaProperties)(n.patternProperties);f(),e.ok((0,Vn._)`${o} === ${OJ.default.errors}`);function f(){t.forIn("key",i,g=>{!l.length&&!u.length?h(g):t.if(d(g),()=>h(g))})}function d(g){let v;if(l.length>8){let w=(0,tm.schemaRefOrVal)(a,n.properties,"properties");v=(0,em.isOwnProperty)(t,w,g)}else l.length?v=(0,Vn.or)(...l.map(w=>(0,Vn._)`${g} === ${w}`)):v=Vn.nil;return u.length&&(v=(0,Vn.or)(v,...u.map(w=>(0,Vn._)`${(0,em.usePattern)(e,w)}.test(${g})`))),(0,Vn.not)(v)}function m(g){t.code((0,Vn._)`delete ${i}[${g}]`)}function h(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,tm.alwaysValidSchema)(a,r)){let v=t.name("valid");c.removeAdditional==="failing"?(p(g,v,!1),t.if((0,Vn.not)(v),()=>{e.reset(),m(g)})):(p(g,v),s||t.if((0,Vn.not)(v),()=>t.break()))}}function p(g,v,w){let y={keyword:"additionalProperties",dataProp:g,dataPropType:tm.Type.Str};w===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(y,v)}}};Ck.default=jJ});var aP=D(xk=>{"use strict";Object.defineProperty(xk,"__esModule",{value:!0});var $J=fu(),iP=yn(),Ik=je(),oP=_k(),DJ={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&oP.default.code(new $J.KeywordCxt(o,oP.default,"additionalProperties"));let a=(0,iP.allSchemaProperties)(r);for(let f of a)o.definedProperties.add(f);o.opts.unevaluated&&a.length&&o.props!==!0&&(o.props=Ik.mergeEvaluated.props(t,(0,Ik.toHash)(a),o.props));let s=a.filter(f=>!(0,Ik.alwaysValidSchema)(o,r[f]));if(s.length===0)return;let c=t.name("valid");for(let f of s)l(f)?u(f):(t.if((0,iP.propertyInData)(t,i,f,o.opts.ownProperties)),u(f),o.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function l(f){return o.opts.useDefaults&&!o.compositeRule&&r[f].default!==void 0}function u(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};xk.default=DJ});var uP=D(Pk=>{"use strict";Object.defineProperty(Pk,"__esModule",{value:!0});var sP=yn(),rm=Ee(),cP=je(),lP=je(),BJ={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:o}=e,{opts:a}=o,s=(0,sP.allSchemaProperties)(r),c=s.filter(p=>(0,cP.alwaysValidSchema)(o,r[p]));if(s.length===0||c.length===s.length&&(!o.opts.unevaluated||o.props===!0))return;let l=a.strictSchema&&!a.allowMatchingProperties&&i.properties,u=t.name("valid");o.props!==!0&&!(o.props instanceof rm.Name)&&(o.props=(0,lP.evaluatedPropsToName)(t,o.props));let{props:f}=o;d();function d(){for(let p of s)l&&m(p),o.allErrors?h(p):(t.var(u,!0),h(p),t.if(u))}function m(p){for(let g in l)new RegExp(p).test(g)&&(0,cP.checkStrictMode)(o,`property ${g} matches pattern ${p} (use allowMatchingProperties)`)}function h(p){t.forIn("key",n,g=>{t.if((0,rm._)`${(0,sP.usePattern)(e,p)}.test(${g})`,()=>{let v=c.includes(p);v||e.subschema({keyword:"patternProperties",schemaProp:p,dataProp:g,dataPropType:lP.Type.Str},u),o.opts.unevaluated&&f!==!0?t.assign((0,rm._)`${f}[${g}]`,!0):!v&&!o.allErrors&&t.if((0,rm.not)(u),()=>t.break())})})}}};Pk.default=BJ});var dP=D(Ok=>{"use strict";Object.defineProperty(Ok,"__esModule",{value:!0});var WJ=je(),LJ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,WJ.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ok.default=LJ});var fP=D(Tk=>{"use strict";Object.defineProperty(Tk,"__esModule",{value:!0});var qJ=yn(),VJ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:qJ.validateUnion,error:{message:"must match a schema in anyOf"}};Tk.default=VJ});var pP=D(jk=>{"use strict";Object.defineProperty(jk,"__esModule",{value:!0});var nm=Ee(),MJ=je(),FJ={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,nm._)`{passingSchemas: ${e.passing}}`},HJ={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:FJ,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,a=t.let("valid",!1),s=t.let("passing",null),c=t.name("_valid");e.setParams({passing:s}),t.block(l),e.result(a,()=>e.reset(),()=>e.error(!0));function l(){o.forEach((u,f)=>{let d;(0,MJ.alwaysValidSchema)(i,u)?t.var(c,!0):d=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,nm._)`${c} && ${a}`).assign(a,!1).assign(s,(0,nm._)`[${s}, ${f}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(s,f),d&&e.mergeEvaluated(d,nm.Name)})})}}};jk.default=HJ});var mP=D($k=>{"use strict";Object.defineProperty($k,"__esModule",{value:!0});var QJ=je(),UJ={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((o,a)=>{if((0,QJ.alwaysValidSchema)(n,o))return;let s=e.subschema({keyword:"allOf",schemaProp:a},i);e.ok(i),e.mergeEvaluated(s)})}};$k.default=UJ});var vP=D(Dk=>{"use strict";Object.defineProperty(Dk,"__esModule",{value:!0});var im=Ee(),gP=je(),JJ={message:({params:e})=>(0,im.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,im._)`{failingKeyword: ${e.ifClause}}`},zJ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:JJ,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,gP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=hP(n,"then"),o=hP(n,"else");if(!i&&!o)return;let a=t.let("valid",!0),s=t.name("_valid");if(c(),e.reset(),i&&o){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(s,l("then",u),l("else",u))}else i?t.if(s,l("then")):t.if((0,im.not)(s),l("else"));e.pass(a,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);e.mergeEvaluated(u)}function l(u,f){return()=>{let d=e.subschema({keyword:u},s);t.assign(a,s),e.mergeValidEvaluated(d,a),f?t.assign(f,(0,im._)`${u}`):e.setParams({ifClause:u})}}}};function hP(e,t){let r=e.schema[t];return r!==void 0&&!(0,gP.alwaysValidSchema)(e,r)}Dk.default=zJ});var wP=D(Bk=>{"use strict";Object.defineProperty(Bk,"__esModule",{value:!0});var KJ=je(),GJ={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,KJ.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Bk.default=GJ});var yP=D(Wk=>{"use strict";Object.defineProperty(Wk,"__esModule",{value:!0});var YJ=kk(),XJ=Kx(),ZJ=bk(),e2=Yx(),t2=Xx(),r2=tP(),n2=nP(),i2=_k(),o2=aP(),a2=uP(),s2=dP(),c2=fP(),l2=pP(),u2=mP(),d2=vP(),f2=wP();function p2(e=!1){let t=[s2.default,c2.default,l2.default,u2.default,d2.default,f2.default,n2.default,i2.default,r2.default,o2.default,a2.default];return e?t.push(XJ.default,e2.default):t.push(YJ.default,ZJ.default),t.push(t2.default),t}Wk.default=p2});var kP=D(Lk=>{"use strict";Object.defineProperty(Lk,"__esModule",{value:!0});var At=Ee(),m2={message:({schemaCode:e})=>(0,At.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,At._)`{format: ${e}}`},h2={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:m2,code(e,t){let{gen:r,data:n,$data:i,schema:o,schemaCode:a,it:s}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:f}=s;if(!c.validateFormats)return;i?d():m();function d(){let h=r.scopeValue("formats",{ref:f.formats,code:c.code.formats}),p=r.const("fDef",(0,At._)`${h}[${a}]`),g=r.let("fType"),v=r.let("format");r.if((0,At._)`typeof ${p} == "object" && !(${p} instanceof RegExp)`,()=>r.assign(g,(0,At._)`${p}.type || "string"`).assign(v,(0,At._)`${p}.validate`),()=>r.assign(g,(0,At._)`"string"`).assign(v,p)),e.fail$data((0,At.or)(w(),y()));function w(){return c.strictSchema===!1?At.nil:(0,At._)`${a} && !${v}`}function y(){let b=u.$async?(0,At._)`(${p}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,At._)`${v}(${n})`,N=(0,At._)`(typeof ${v} == "function" ? ${b} : ${v}.test(${n}))`;return(0,At._)`${v} && ${v} !== true && ${g} === ${t} && !${N}`}}function m(){let h=f.formats[o];if(!h){w();return}if(h===!0)return;let[p,g,v]=y(h);p===t&&e.pass(b());function w(){if(c.strictSchema===!1){f.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function y(N){let A=N instanceof RegExp?(0,At.regexpCode)(N):c.code.formats?(0,At._)`${c.code.formats}${(0,At.getProperty)(o)}`:void 0,S=r.scopeValue("formats",{key:o,ref:N,code:A});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,At._)`${S}.validate`]:["string",N,S]}function b(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,At._)`await ${v}(${n})`}return typeof g=="function"?(0,At._)`${v}(${n})`:(0,At._)`${v}.test(${n})`}}}};Lk.default=h2});var bP=D(qk=>{"use strict";Object.defineProperty(qk,"__esModule",{value:!0});var g2=kP(),v2=[g2.default];qk.default=v2});var AP=D(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.contentVocabulary=Us.metadataVocabulary=void 0;Us.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Us.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var NP=D(Vk=>{"use strict";Object.defineProperty(Vk,"__esModule",{value:!0});var w2=Px(),y2=Qx(),k2=yP(),b2=bP(),RP=AP(),A2=[w2.default,y2.default,(0,k2.default)(),b2.default,RP.metadataVocabulary,RP.contentVocabulary];Vk.default=A2});var EP=D(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});om.DiscrError=void 0;var SP;(function(e){e.Tag="tag",e.Mapping="mapping"})(SP||(om.DiscrError=SP={}))});var _P=D(Fk=>{"use strict";Object.defineProperty(Fk,"__esModule",{value:!0});var Js=Ee(),Mk=EP(),CP=Wp(),R2=pu(),N2=je(),S2={message:({params:{discrError:e,tagName:t}})=>e===Mk.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Js._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},E2={keyword:"discriminator",type:"object",schemaType:"object",error:S2,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:o}=e,{oneOf:a}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,Js._)`${r}${(0,Js.getProperty)(s)}`);t.if((0,Js._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Mk.DiscrError.Tag,tag:l,tagName:s})),e.ok(c);function u(){let m=d();t.if(!1);for(let h in m)t.elseIf((0,Js._)`${l} === ${h}`),t.assign(c,f(m[h]));t.else(),e.error(!1,{discrError:Mk.DiscrError.Mapping,tag:l,tagName:s}),t.endIf()}function f(m){let h=t.name("valid"),p=e.subschema({keyword:"oneOf",schemaProp:m},h);return e.mergeEvaluated(p,Js.Name),h}function d(){var m;let h={},p=v(i),g=!0;for(let b=0;b<a.length;b++){let N=a[b];if(N?.$ref&&!(0,N2.schemaHasRulesButRef)(N,o.self.RULES)){let S=N.$ref;if(N=CP.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,S),N instanceof CP.SchemaEnv&&(N=N.schema),N===void 0)throw new R2.default(o.opts.uriResolver,o.baseId,S)}let A=(m=N?.properties)===null||m===void 0?void 0:m[s];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);g=g&&(p||v(N)),w(A,b)}if(!g)throw new Error(`discriminator: "${s}" must be required`);return h;function v({required:b}){return Array.isArray(b)&&b.includes(s)}function w(b,N){if(b.const)y(b.const,N);else if(b.enum)for(let A of b.enum)y(A,N);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function y(b,N){if(typeof b!="string"||b in h)throw new Error(`discriminator: "${s}" values must be unique strings`);h[b]=N}}}};Fk.default=E2});var IP=D((r7,C2)=>{C2.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var sm=D((at,Hk)=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.MissingRefError=at.ValidationError=at.CodeGen=at.Name=at.nil=at.stringify=at.str=at._=at.KeywordCxt=at.Ajv=void 0;var _2=Sx(),I2=NP(),x2=_P(),xP=IP(),P2=["/properties"],am="http://json-schema.org/draft-07/schema",zs=class extends _2.default{_addVocabularies(){super._addVocabularies(),I2.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(x2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(xP,P2):xP;this.addMetaSchema(t,am,!1),this.refs["http://json-schema.org/schema"]=am}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(am)?am:void 0)}};at.Ajv=zs;Hk.exports=at=zs;Hk.exports.Ajv=zs;Object.defineProperty(at,"__esModule",{value:!0});at.default=zs;var O2=fu();Object.defineProperty(at,"KeywordCxt",{enumerable:!0,get:function(){return O2.KeywordCxt}});var Ks=Ee();Object.defineProperty(at,"_",{enumerable:!0,get:function(){return Ks._}});Object.defineProperty(at,"str",{enumerable:!0,get:function(){return Ks.str}});Object.defineProperty(at,"stringify",{enumerable:!0,get:function(){return Ks.stringify}});Object.defineProperty(at,"nil",{enumerable:!0,get:function(){return Ks.nil}});Object.defineProperty(at,"Name",{enumerable:!0,get:function(){return Ks.Name}});Object.defineProperty(at,"CodeGen",{enumerable:!0,get:function(){return Ks.CodeGen}});var T2=Dp();Object.defineProperty(at,"ValidationError",{enumerable:!0,get:function(){return T2.default}});var j2=pu();Object.defineProperty(at,"MissingRefError",{enumerable:!0,get:function(){return j2.default}})});var PP,OP=x(()=>{"use strict";PP=new Map});function cm(e){let t=ri(e),r=xa.get(t);if(r)return xa.delete(t),xa.set(t,r),r;let i=PP.get(t)??new Uk.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),o={validate:i,errorsText:()=>Uk.Ajv.prototype.errorsText(i.errors)};if(t.length<=TP){for(;xa.size>=$2||Qk+t.length>TP;){let a=xa.keys().next().value;xa.delete(a),Qk-=a.length}xa.set(t,o),Qk+=t.length}return o}var Uk,$2,TP,xa,Qk,Jk=x(()=>{"use strict";Uk=tr(sm(),1);OP();kr();$2=128,TP=1024*1024,xa=new Map,Qk=0});function It(e){throw new R("INVALID_WORKFLOW",e)}function To(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&It(`${t} 必须是 JSON 对象`),e}function _u(e,t,r){for(let n of Object.keys(e))t.includes(n)||It(`${r} 包含不支持的字段:${n}`)}function sr(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&It(`${t} 必须是非空字符串且不超过 4096 字符`),e}function zk(e,t,r=!1){(!Array.isArray(e)||!r&&e.length===0)&&It(`${t} 必须是${r?"":"非空"}字符串数组`);let n=e.map(i=>sr(i,t));return new Set(n).size!==n.length&&It(`${t} 不能包含重复值`),n}function Kk(e,t){return zk(typeof e=="string"?[e]:e,t)}function Iu(e,t){let r=To(e,t);return _u(r,["id","version"],t),{id:sr(r.id,`${t}.id`),version:sr(r.version,`${t}.version`)}}function $P(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))$P(t);Object.freeze(e)}return e}function DP(e,t){try{let r=typeof e=="boolean"?e:To(e,t);typeof r!="boolean"&&r.$async===!0&&It(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),cm(r)}catch(r){It(`${t} 不是受支持的 JSON Schema:${r.message}`)}}function B2(e){let t=To(e,"step"),r=sr(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(r)||It(`不支持的步骤类型:${r}`);let n=r==="ask_user"?["proposalFrom","choices"]:r==="child_workflow"?["workflow"]:r==="await_evidence"?["kind"]:[];_u(t,[...D2,...n],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&It("step.retry 必须是 manual、idempotent 或 reconcile");let o={...t.ref===void 0?{}:{ref:sr(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:Iu(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:zk(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:zk(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&DP(t.outputSchema,"outputSchema"),r==="ask_user"?{...o,type:r,proposalFrom:Kk(t.proposalFrom,"step.proposalFrom"),choices:Kk(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:r==="child_workflow"?{...o,type:r,workflow:Iu(t.workflow,"step.workflow")}:r==="await_evidence"?(o.validator||It("await_evidence 必须声明验证器"),{...o,type:r,kind:sr(t.kind,"step.kind"),validator:o.validator}):{...o,type:r,ref:sr(t.ref,"step.ref")}}function An(e){if(jP.has(e))return e;let t=To(ct(e),"workflow");_u(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let r=sr(t.id,"workflow.id"),n=sr(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&It("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&It("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&DP(t.stateSchema,"stateSchema");let i=To(t.steps,"workflow.steps");Object.keys(i).length===0&&It("workflow.steps 必须至少包含一个步骤");let o=Object.fromEntries(Object.entries(i).map(([p,g])=>(sr(p,"step id"),[p,B2(g)])));function a(p,g){Object.hasOwn(o,p)||It(`${g} 引用了不存在的步骤:${p}`)}let s=Kk(t.entry,"workflow.entry");for(let p of s)a(p,"workflow.entry");let c=t.commands===void 0?{}:To(t.commands,"workflow.commands"),l={};for(let[p,g]of Object.entries(c)){sr(p,"workflow command name");let v=typeof g=="string"?{stepId:sr(g,`workflow.commands.${p}`)}:To(g,`workflow.commands.${p}`);_u(v,["stepId","validator"],`workflow.commands.${p}`);let w=sr(v.stepId,`workflow.commands.${p}.stepId`);a(w,`workflow.commands.${p}`);let y=o[w];(y.join||!["invoke_skill","call_tool","handoff"].includes(y.type))&&It(`workflow.commands.${p} 必须指向不带 join 的执行步骤`),Object.defineProperty(l,p,{value:{stepId:w,...v.validator===void 0?{}:{validator:Iu(v.validator,`workflow.commands.${p}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let u=t.transitions===void 0?[]:t.transitions;Array.isArray(u)||It("workflow.transitions 必须是数组");let f=new Set,d=u.map(p=>{let g=To(p,"transition");_u(g,["from","to","on"],"transition");let v=sr(g.from,"transition.from"),w=sr(g.to,"transition.to"),y=sr(g.on===void 0?"succeeded":g.on,"transition.on");a(v,"transition.from"),a(w,"transition.to");let b=JSON.stringify([v,w,y]);return f.has(b)&&It(`重复的状态转移:${v} -> ${w} (${y})`),f.add(b),{from:v,to:w,on:y}});for(let[p,g]of Object.entries(o)){if(g.join){let v=new Set(d.filter(w=>w.to===p).map(w=>w.from));for(let w of g.join)a(w,`${p}.join`),v.has(w)||It(`${p}.join 依赖缺少对应的进入边:${w}`);v.size!==g.join.length&&It(`${p}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let v of g.proposalFrom)a(v,`${p}.proposalFrom`)}let m=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof m!="number"||!Number.isSafeInteger(m)||m<1)&&It("workflow.maxTransitions 必须是正安全整数");let h=$P({id:r,version:n,entry:s,steps:o,...t.commands===void 0?{}:{commands:l},transitions:d,maxTransitions:m,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:Iu(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:Iu(t.transitionHandler,"workflow.transitionHandler")}});return jP.add(h),h}var D2,jP,Gk=x(()=>{"use strict";pn();kr();Jk();D2=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];jP=new WeakSet});function xu(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!0,enumerable:!0,writable:!0})}function lm(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value]))}function W2(e){let t={};for(let r of e)for(let[n,i]of Object.entries(r.results))(!Object.hasOwn(t,n)||i.sequence>t[n].sequence)&&xu(t,n,i);return t}function $i(e,t){if(e.status==="cancelled"||e.status==="failed")return;for(;e.ready.length>0;){let o=e.ready.shift(),a=t.steps[o.to],s=o.results;if(a.join?.length){if(o.from===null||!a.join.includes(o.from))throw new R("INVALID_JOIN","join 必须由其声明的父节点触发");Object.hasOwn(e.joins,o.to)||xu(e.joins,o.to,Object.fromEntries(a.join.map(d=>[d,[]])));let f=e.joins[o.to];if(f[o.from].push(o),a.join.some(d=>f[d].length===0))continue;s=W2(a.join.map(d=>f[d].shift()))}if(e.sequence>=t.maxTransitions){e.ready.unshift(o),e.status="failed",e.reason="TRANSITION_LIMIT: 工作流已达到允许的步骤激活次数";return}let c=++e.sequence,l=`${e.runId}:${c}`,u={input:a.input===void 0?e.input:a.input,outputs:lm(s),...o.activation===void 0?{}:{activation:o.activation}};if(a.type==="ask_user"){let f=Object.fromEntries(a.proposalFrom.map(m=>{if(!Object.hasOwn(s,m))throw new R("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${m}`);return[m,s[m].value]})),d={input:u.input,outputs:f,...o.activation===void 0?{}:{activation:o.activation}};e.waits.push({id:l,stepId:o.to,sequence:c,status:"pending",proposal:d,proposalHash:j(d),choices:[...a.choices],results:s})}else if(a.type==="await_evidence")e.evidenceWaits??=[],e.evidenceWaits.push({id:l,stepId:o.to,sequence:c,kind:a.kind,status:"pending",results:s});else{let f=a.type==="child_workflow"?`${a.workflow.id}@${a.workflow.version}`:a.ref,d=A_({id:l,runId:e.runId,stepId:o.to,type:a.type,ref:f,input:u,retry:a.retry,requiredCapabilities:a.requiredCapabilities});e.actions.push(d),xu(e.actionContexts,l,{sequence:c,results:s}),a.type==="child_workflow"&&e.children.push({actionId:l,runId:`child-${j(l)}`,workflow:a.workflow})}}let r=e.actions.some(o=>["pending","running","unknown"].includes(o.status)),n=e.waits.some(o=>o.status==="pending")||(e.evidenceWaits?.some(o=>o.status==="pending")??!1),i=Object.values(e.joins).some(o=>Object.values(o).some(a=>a.length>0));e.status=r?"running":n||i?"waiting":"completed"}function Gs(e,t,r,n,i,o,a,s){let c={sequence:n,value:o},l={...i};xu(l,r,c),(!Object.hasOwn(e.outputs,r)||e.outputs[r].sequence<=n)&&xu(e.outputs,r,c);let u=t.transitions.filter(m=>m.from===r),f=u.filter(m=>m.on===a),d=s??f.map(m=>m.to);if(d.length===0&&a==="failed"){e.status="failed",e.reason=`ACTION_FAILED: ${r}`;return}if(d.length===0&&s===void 0&&u.length>0)throw new R("TRANSITION_UNAVAILABLE",`步骤 ${r} 未声明 ${a} 的后续转换`);for(let m of d){let h=typeof m=="string"?m:m.stepId;if(!f.some(p=>p.to===h))throw new R("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:r,to:h,results:l,...typeof m=="string"?{}:{activation:m.input}})}}var BP=x(()=>{"use strict";ha();pn();kr()});import{randomUUID as Yk}from"node:crypto";import{types as eb}from"node:util";function WP(e){return Ge({runId:e.runId,revision:e.revision,status:e.status,sequence:e.sequence,workflow:e.workflow,input:e.input,...e.state===void 0?{}:{state:e.state},...e.reason===void 0?{}:{reason:e.reason},actions:e.actions.filter(t=>["pending","running","unknown"].includes(t.status)||t.status==="cancelled"&&t.claim&&!t.cancellation&&!t.executionStop),waits:e.waits.filter(t=>t.status==="pending"),evidenceWaits:(e.evidenceWaits??[]).filter(t=>t.status==="pending"),outputs:e.outputs,history:{actions:e.actions.length,waits:e.waits.length,evidenceWaits:e.evidenceWaits?.length??0}})}function lt(e){return JSON.stringify([e.id,e.version])}function en(e){if(e===void 0)return;if(!e||typeof e!="object"||eb.isProxy(e))throw new R("INVALID_JSON","context 必须是普通对象");let t={},r;for(let i of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new R("INVALID_JSON","context 必须使用普通数据属性");i==="signal"?r=o.value:o.value!==void 0&&Object.defineProperty(t,i,{value:o.value,enumerable:!0})}let n=ct(t);if(r!==void 0){if(!(r instanceof AbortSignal))throw new R("INVALID_JSON","signal 必须是 AbortSignal");n.signal=r}return n}function tb(e,t=new Set){if(e===null||typeof e!="object")return e;if(eb.isProxy(e))throw new R("INVALID_JSON","请求不能包含代理对象");if(t.size>64)throw new R("INVALID_JSON","请求数据嵌套超过 64 层");if(t.has(e))throw new R("INVALID_JSON","请求包含循环引用");let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw new R("INVALID_JSON","请求必须使用普通数据对象");t.add(e);let n=Array.isArray(e)?[]:{};for(let i of Reflect.ownKeys(e)){if(Array.isArray(e)&&i==="length")continue;let o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new R("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(n,i,{enumerable:!0,writable:!0,configurable:!0,value:tb(o.value,t)})}return t.delete(e),n}function Xk(e){if(e===null||typeof e!="object")return e;if(eb.isProxy(e))throw new R("INVALID_JSON","请求不能包含代理对象");let t={};for(let r of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,r);if(typeof r!="string"||!n.enumerable||!("value"in n))throw new R("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(t,r,{enumerable:!0,writable:!0,configurable:!0,value:r==="context"?en(n.value):tb(n.value)})}return t}function Pa(e){let t=tb(e),r=ct(t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t);if(!r||typeof r.accepted!="boolean"||r.reason!==void 0&&typeof r.reason!="string"||"allowCompleted"in r&&typeof r.allowCompleted!="boolean"||"allowFailed"in r&&typeof r.allowFailed!="boolean")throw new R("INVALID_VALIDATION","验证器必须返回布尔 accepted 和有效原因");return r}function Zk(e,t){let r=e.supports(Ge(t));if(typeof r!="boolean")throw new R("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return r}function si(e){if(e?.signal?.aborted)throw new R("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function Oa(e,t){if(e===t)return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>Object.hasOwn(t,n)&&Oa(e[n],t[n]))}function LP(e){return{...e,definitionHashes:{...e.definitionHashes},actions:[...e.actions],...e.commands?{commands:[...e.commands]}:{},actionContexts:{...e.actionContexts},waits:e.waits.map(t=>({...t})),...e.evidenceWaits?{evidenceWaits:e.evidenceWaits.map(t=>({...t}))}:{},ready:[...e.ready],joins:Object.fromEntries(Object.entries(e.joins).map(([t,r])=>[t,Object.fromEntries(Object.entries(r).map(([n,i])=>[n,[...i]]))])),outputs:{...e.outputs},children:[...e.children],lineage:[...e.lineage]}}function cr(e){let t=new Map,r=new Map;for(let k of e.workflows){let C=An(k),$=lt(C);if(t.has($))throw new R("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set($,C);let O=qP.get(C);O===void 0&&(O=j(C),qP.set(C,O)),r.set(C,O)}let n=new Map;for(let k of e.validators??[]){let C=lt(k);if(n.has(C))throw new R("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");n.set(C,k)}let i=new Map;for(let k of e.stateValidators??[]){let C=lt(k);if(i.has(C))throw new R("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(C,k)}let o=new Map;function a(k){let C=o.get(k);return C||(C=cm(k),o.set(k,C)),C}let s=new Map,c=new Map;for(let k of e.transitionHandlers??[]){let C=lt(k);if(c.has(C))throw new R("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");c.set(C,k)}let l=new Map;for(let k of e.evidenceValidators??[]){let C=lt(k);if(l.has(C))throw new R("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");l.set(C,k)}let u=new Map;for(let k of e.commandValidators??[]){let C=lt(k);if(u.has(C))throw new R("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");u.set(C,k)}for(let k of e.executors??[]){if(s.has(k.id))throw new R("DUPLICATE_EXECUTOR","不能重复注册同一执行器");s.set(k.id,k)}function f(k){let C=t.get(lt(k));if(!C)throw new R("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(k.hash!==void 0&&k.hash!==r.get(C))throw new R("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return C}function d(k){if(k.transitionHandler&&!c.has(lt(k.transitionHandler)))throw new R("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function m(k){if(k.stateValidator&&!i.has(lt(k.stateValidator)))throw new R("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function h(k){for(let C of Object.values(k.steps))if(C.type==="await_evidence"&&!l.has(lt(C.validator)))throw new R("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function p(k){for(let C of Object.values(k.commands??{}))if(C.validator&&!u.has(lt(C.validator)))throw new R("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(k,C,$){if(k.stateSchema!==void 0){let O=a(k.stateSchema);if(!O.validate(C))throw new R($,O.errorsText())}if(k.stateValidator){let O=i.get(lt(k.stateValidator));if(!O)throw new R("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let T=Pa(O.validate({state:ct(C)}));if(!T.accepted)throw new Error(T.reason??"业务状态未通过验证")}catch(T){throw new R($,T instanceof Error?T.message:String(T))}}}function v(k,C,$,O){if(!C.transitionHandler)return;let T=c.get(lt(C.transitionHandler));if(!T)throw new R("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let z=ct(T.apply({run:Ge(k),event:Ge($)})),Y=ct(z.state);g(C,Y,"TRANSITION_STATE_INVALID");let ee=new Set(C.transitions.filter(le=>le.from===$.stepId&&le.on===O).map(le=>le.to));if(!Array.isArray(z.next))throw new R("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let G=[],te=new Set;for(let le of z.next){let V;if(typeof le=="string")V=le;else if(le!==null&&typeof le=="object"&&!Array.isArray(le)){let Re=Object.keys(le);if(Re.length!==2||!Re.includes("stepId")||!Re.includes("input")||typeof le.stepId!="string")throw new R("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");V={stepId:le.stepId,input:ct(le.input)}}else throw new R("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let ve=typeof V=="string"?V:V.stepId,ae=j(V);if(!ee.has(ve)||te.has(ae))throw new R("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");te.add(ae),G.push(V)}return k.state=Y,G}function w(k,C=j){if(t.size>0)for(let[$,O]of Object.entries(k.definitionHashes)){let[T,z]=JSON.parse($),Y=f({id:T,version:z,hash:O});if(d(Y),m(Y),h(Y),p(Y),T===k.workflow.id&&z===k.workflow.version){let ee=new Map(k.actions.map(G=>[G.id,G]));for(let G of k.commands??[]){let te=ee.get(G.actionId),le=Object.hasOwn(Y.commands??{},G.name),V=te&&!le&&!Object.hasOwn(Y.steps,te.stepId)&&["succeeded","failed","cancelled"].includes(te.status);if(!te||!V&&(!le||Y.commands?.[G.name].stepId!==te.stepId)||te.input===null||typeof te.input!="object"||!Object.hasOwn(te.input,"activation")||C(te.input.activation)!==G.inputHash)throw new R("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(Y.stateSchema!==void 0&&Y.initialState===void 0&&k.initialStateHash===void 0)throw new R("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(Y,k.state,"RUN_STATE_INVALID");for(let G of k.ready){let te=()=>{throw new R("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(Y.steps,G.to)||te(),G.from===null){(!Y.entry.includes(G.to)||Object.keys(G.results).length>0||k.sequence!==0&&!(k.status==="failed"&&k.reason?.startsWith("TRANSITION_LIMIT:")))&&te();continue}let le=G.results[G.from];le||te();let V=k.actions.find(xr=>xr.stepId===G.from&&k.actionContexts[xr.id].sequence===le.sequence),ve=k.waits.find(xr=>xr.stepId===G.from&&xr.sequence===le.sequence),ae=k.evidenceWaits?.find(xr=>xr.stepId===G.from&&xr.sequence===le.sequence),Re=V?.outcome?V.outcome.status==="failed"?"failed":V.outcome.event??"succeeded":ve?.decision?.choice??(ae?.invalidation?"invalidated":ae?.receipt?"succeeded":void 0),dt=V?k.actionContexts[V.id].results:ve?.results??ae?.results,Mc=V?.outcome?V.outcome.output:ve?.decision?{choice:ve.decision.choice,proposal:ve.proposal}:ae?.invalidation?{ref:ae.invalidation.ref,contentHash:ae.invalidation.contentHash,reason:ae.invalidation.reason}:ae?.receipt?{ref:ae.receipt.ref,contentHash:ae.receipt.contentHash}:void 0;(!Re||!dt||V&&!["succeeded","failed"].includes(V.status)||ve&&ve.status!=="resolved"||ae&&!["resolved","invalidated"].includes(ae.status)||Mc===void 0||C(G.results)!==C({...dt,[G.from]:{sequence:le.sequence,value:Mc}})||!Y.transitions.some(xr=>xr.from===G.from&&xr.to===G.to&&xr.on===Re))&&te()}for(let G of k.evidenceWaits??[]){let te=Y.steps[G.stepId];if(!(!te&&G.status!=="pending")&&(!te||te.type!=="await_evidence"||te.kind!==G.kind))throw new R("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function y(k){let C=await e.store.read(k);if(!C)throw new R("RUN_NOT_FOUND",`找不到工作流实例:${k}`);let $=q_(C,k);return w($),ma($)}async function b(k,C,$){for(let O=0;O<32;O+=1){si(k.context);let T=O===0&&$?$:await y(k.runId),z=f(T.workflow);if(k.expectedRevision!==void 0&&k.expectedRevision!==T.revision)throw new R("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let Y=LP(T);if(await C(Y,z),hn(Y),Oa(Y,T))return T;if(Y.revision=T.revision+1,Ap(Y,T),w(Y),ma(Y),si(k.context),await e.store.compareAndSwap(k.runId,T.revision,Y))return Y}throw new R("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function N(k,C){let $=k.actions.find(O=>O.id===C);if(!$)throw new R("ACTION_NOT_FOUND","Run 不包含此 Action");return $}function A(k){if(k.status==="cancelled")throw new R("RUN_CANCELLED","Run 已取消,不能继续推进")}function S(k,C={}){let $=lt(k);if(Object.hasOwn(C,$))return C;C[$]=r.get(k);for(let O of Object.values(k.steps))O.type==="child_workflow"&&S(f(O.workflow),C);return C}async function _(k,C){if(si(k.context),C.length>32)throw new R("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let $=f(k.workflow);d($),m($),h($),p($);let O=Object.hasOwn(k,"initialState");if(O&&$.initialState!==void 0)throw new R("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let T=O?ct(k.initialState):$.initialState;if($.stateSchema!==void 0&&T===void 0)throw new R("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");T!==void 0&&g($,T,"INITIAL_STATE_INVALID");let z=T===void 0?void 0:j(T),Y=k.runId??Yk(),ee=ct(k.input),G={id:$.id,version:$.version,hash:r.get($)},te=await e.store.read(Y);if(te){if(j(te.workflow)!==j(G)||j(te.input)!==j(ee)||j(te.lineage)!==j(C)||(te.initialStateHash??($.initialState===void 0?void 0:j($.initialState)))!==z)throw new R("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return y(Y)}let le={protocolVersion:1,schemaVersion:1,runId:Y,revision:1,workflow:G,definitionHashes:S($),input:ee,...T===void 0?{}:{state:ct(T),initialStateHash:z},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:$.entry.map(V=>({from:null,to:V,results:{}})),joins:{},outputs:{},children:[],lineage:C};return $i(le,$),ma(le),si(k.context),Ap(le),w(le),await e.store.compareAndSwap(Y,null,le)?Ge(le):_({...k,runId:Y},C)}async function Q(k){return _(k,[])}async function F(k){let C=ct(k.input),$=j(C);if(!k.commandId.trim()||k.commandId.length>4096||!k.name.trim()||k.name.length>4096)throw new R("INVALID_COMMAND","命令标识和名称不能为空");for(let O=0;O<32;O+=1){si(k.context);let T=await y(k.runId),z=T.commands?.find(ae=>ae.id===k.commandId);if(z){if(z.name!==k.name||z.inputHash!==$)throw new R("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return T}if(k.expectedRevision!==T.revision)throw new R("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let Y=f(T.workflow),ee=Object.hasOwn(Y.commands??{},k.name)?Y.commands?.[k.name]:void 0;if(!ee)throw new R("COMMAND_NOT_FOUND","工作流未声明此命令");let G=ee.stepId;if(T.status==="cancelled")throw new R("RUN_TERMINAL","已停止的 Run 不能接受命令");if(T.actions.some(ae=>["running","unknown"].includes(ae.status)))throw new R("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let te=!1,le=!1;if(ee.validator){let ae=u.get(lt(ee.validator));if(!ae)throw new R("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let Re;try{Re=Pa(await ae.validate({run:Ge(T),name:k.name,input:Ge(C),context:en(k.context)}))}catch(dt){throw new R("COMMAND_VALIDATION_ERROR",dt instanceof Error?dt.message:String(dt))}if(te=Re.accepted&&Re.allowCompleted===!0,le=Re.accepted&&Re.allowFailed===!0,T.status==="failed"&&!le)throw new R("RUN_TERMINAL","已停止的 Run 不能接受命令");if(T.status==="completed"&&!te)throw new R("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!Re.accepted)throw new R("COMMAND_REJECTED",Re.reason??"命令未通过当前工作流状态验证")}if(T.status==="completed"&&!te)throw new R("RUN_TERMINAL","已停止的 Run 不能接受命令");if(T.status==="failed"&&!le)throw new R("RUN_TERMINAL","已停止的 Run 不能接受命令");let V=Ge(T);T.status==="failed"&&(V.status="running",delete V.reason),V.actions=V.actions.map(ae=>ae.status==="pending"?Jl(ae,`命令 ${k.name} 已取代待执行 Action`):ae);for(let ae of V.waits)ae.status==="pending"&&(ae.status="cancelled");for(let ae of V.evidenceWaits??[])ae.status==="pending"&&(ae.status="cancelled");V.ready=[{from:null,to:G,results:{},activation:C}],V.joins={},$i(V,Y);let ve=V.actions.at(-1);if(!ve||ve.stepId!==G||ve.status!=="pending")throw new R("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if(V.commands=[...V.commands??[],{id:k.commandId,name:k.name,inputHash:$,actionId:ve.id}],V.revision=T.revision+1,Ap(V,T),w(V),ma(V),si(k.context),await e.store.compareAndSwap(k.runId,T.revision,V))return Ge(V)}throw new R("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function K(k){for(let C of k.children)await e.store.read(C.runId)&&await P({runId:C.runId,reason:k.reason??"父工作流已取消"})}function Z(k,C,$){let O=f(k.workflow),T=Object.hasOwn(O.steps,$.stepId)?O.steps[$.stepId]:void 0;if(!T||T.type!=="child_workflow"||lt(T.workflow)!==lt(C.workflow)||$.type!==T.type||$.ref!==`${T.workflow.id}@${T.workflow.version}`||$.attempt!==1||$.retry!==T.retry||!Oa($.requiredCapabilities,T.requiredCapabilities??[])||$.claim&&($.claim.executorId!=="comet-child-workflow"||$.claim.sessionId!==void 0||![C.runId,`portable-${j(C.runId)}`].includes($.claim.token)))throw new R("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let z=$.input;if(!z||typeof z!="object"||Array.isArray(z)||!Oa(z,{input:T.input===void 0?k.input:T.input,outputs:lm(k.actionContexts[$.id].results),...Object.hasOwn(z,"activation")?{activation:z.activation}:{}}))throw new R("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let Y=f({...C.workflow,hash:k.definitionHashes[lt(C.workflow)]});if(Object.entries(S(Y)).some(([ee,G])=>k.definitionHashes[ee]!==G))throw new R("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return Y}function re(k,C,$,O,T){let z=O.initialState===void 0?void 0:j(O.initialState);if(T.runId!==C.runId||lt(T.workflow)!==lt(C.workflow)||T.workflow.hash!==k.definitionHashes[lt(C.workflow)]||!Oa(T.definitionHashes,S(O))||!Oa(T.input,$.input)||!Oa(T.lineage,[...k.lineage,k.runId])||(T.initialStateHash??z)!==z)throw new R("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function X(k){let C=await b(k,($,O)=>$i($,O));if(C.status==="cancelled")return await K(C),C;if(C.status==="failed"||C.children.length===0)return C;for(let $ of C.children){let O=N(C,$.actionId);if(!["pending","running","unknown"].includes(O.status))continue;let T=Z(C,$,O);O.status==="pending"&&(C=await Oe({runId:C.runId,actionId:O.id,attempt:O.attempt,inputHash:O.inputHash,executorId:"comet-child-workflow",claimToken:$.runId,capabilities:["child-workflow"],context:en(k.context)},!0),O=N(C,$.actionId));let z=O.status==="unknown"?await y($.runId):await _({runId:$.runId,workflow:$.workflow,input:O.input,context:en(k.context)},[...C.lineage,C.runId]);re(C,$,O,T,z);let Y=await y(C.runId);if(Y.status==="cancelled")return await K(Y),Y;let ee=await X({runId:$.runId,context:k.context});re(C,$,O,T,ee),["completed","failed","cancelled"].includes(ee.status)&&(C=await B({runId:C.runId,context:en(k.context),outcome:{actionId:O.id,attempt:O.attempt,inputHash:O.inputHash,claimToken:O.claim.token,outcomeId:`${$.runId}:${ee.revision}`,status:ee.status==="completed"?"succeeded":"failed",output:lm(ee.outputs)}},!0))}return y(C.runId)}async function Oe(k,C=!1,$){let O=k.claimToken??(k.context?.requestId?j({runId:k.runId,actionId:k.actionId,attempt:k.attempt,executorId:k.executorId,requestId:k.context.requestId}):Yk());return b(k,async T=>{if(A(T),T.status==="failed")throw new R("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let z=N(T,k.actionId);if(z.type==="child_workflow"&&!C)throw new R("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let Y=Jw(z,{executionOrigin:{workflow:{...T.workflow}},attempt:k.attempt,inputHash:k.inputHash,executorId:k.executorId,token:O,...k.sessionId===void 0?{}:{sessionId:k.sessionId}});if(!z.claim){let ee=new Set(k.capabilities??[]);if(z.requiredCapabilities.some(te=>!ee.has(te)))throw new R("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let G=s.get(k.executorId);if(G&&Zk(G,z)){if(z.requiredCapabilities.some(te=>!G.capabilities.includes(te)))throw new R("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await G.preflight?.(Ge(z),en(k.context),G.includeRun===!1?void 0:Ge(T)),si(k.context)}}T.actions[T.actions.indexOf(z)]=Y},$)}async function Be(k){return Oe(k)}async function B(k,C=!1,$){let O,T;try{O=hp(k.outcome)}catch(ee){T=ee}k={...k,outcome:O};let z,Y=await b(k,async(ee,G)=>{if(z=void 0,A(ee),!O)throw T;let te=N(ee,k.outcome.actionId);if(te.type==="child_workflow"&&!C)throw new R("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let le=mp(te,k.outcome);if(le.duplicate)return;let V=le.action.outcome,ve=ee.actions.indexOf(te);try{if(e.validateOutcome){let Re=Pa(await e.validateOutcome({run:Ge(ee),action:Ge(te),outcome:Ge(V),context:en(k.context)}));Re.accepted||(z={code:"OUTCOME_REJECTED",reason:Re.reason??"应用结果契约拒绝此结果"})}let ae=G.steps[te.stepId];if(!z&&V.status==="succeeded"&&ae.outputSchema!==void 0){let Re=a(ae.outputSchema);Re.validate(V.output)||(z={code:"OUTPUT_INVALID",reason:Re.errorsText()})}if(!z&&ae.validator){let Re=n.get(lt(ae.validator));if(!Re)throw new R("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let dt=Pa(await Re.validate({run:Ge(ee),action:Ge(te),outcome:Ge(V),context:en(k.context)}));dt.accepted||(z={code:"OUTCOME_REJECTED",reason:dt.reason?.trim()?dt.reason:"结果未满足业务验收条件"})}if(!z){let Re=LP(ee);Re.actions[ve]=le.action;let dt=Re.actionContexts[te.id],Mc=V.status==="failed"?"failed":V.event??"succeeded",xr=v(Re,G,{kind:"action-outcome",stepId:te.stepId,outcome:V},Mc);Gs(Re,G,te.stepId,dt.sequence,dt.results,V.output,Mc,xr),$i(Re,G),Object.assign(ee,Re)}}catch(ae){z={code:"OUTCOME_PROCESSING_ERROR",reason:ae instanceof Error&&ae.message.trim()?ae.message:"结果处理失败,请检查验证器或工作流定义"}}z&&(ee.actions[ve]={...te,receipts:le.action.receipts,rejectedOutcomes:[...te.rejectedOutcomes??[],{outcome:le.action.outcome,...z}]})},$);if(z)throw new R(z.code,z.reason);return Y}async function ie(k){return B(k)}async function pe(k){if(k.reason!==void 0&&!Yw(k.reason))throw new R("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return b(k,(C,$)=>{A(C);let O=C.waits.find(z=>z.id===k.waitId);if(!O)throw new R("WAIT_NOT_FOUND","Run 不包含此等待项");if(O.decision){if(O.decision.id!==k.decisionId||O.decision.choice!==k.choice||O.decision.proposalHash!==k.proposalHash||O.decision.reason!==k.reason)throw new R("DECISION_CONFLICT","等待项已经接受了不同的决定");return}if(O.status!=="pending"||O.proposalHash!==k.proposalHash)throw new R("STALE_PROPOSAL","提案已改变或等待项已终止,请重新审阅");if(!k.decisionId.trim()||!O.choices.includes(k.choice))throw new R("INVALID_DECISION","决定标识或选择不符合当前等待项");O.status="resolved",O.decision={id:k.decisionId,choice:k.choice,proposalHash:k.proposalHash,...k.reason===void 0?{}:{reason:k.reason}};let T=v(C,$,{kind:"wait-resolved",stepId:O.stepId,choice:k.choice,proposalHash:k.proposalHash,decisionId:k.decisionId},k.choice);Gs(C,$,O.stepId,O.sequence,O.results,{choice:k.choice,proposal:O.proposal},k.choice,T),$i(C,$)})}async function it(k){return b(k,async(C,$)=>{if(A(C),C.status==="failed")throw new R("RUN_FAILED","Run 已因失败停止,不能提交证据");let O=C.evidenceWaits?.find(G=>G.id===k.evidenceId);if(!O)throw new R("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(O.status!=="pending")throw new R("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(O.kind!==k.kind)throw new R("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!k.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(k.ref)||k.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(k.contentHash)||!k.submissionId.trim())throw new R("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let T=$.steps[O.stepId];if(!T||T.type!=="await_evidence"||T.kind!==k.kind)throw new R("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let z=l.get(lt(T.validator));if(!z)throw new R("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let Y=Pa(await z.validate({run:Ge(C),kind:k.kind,ref:k.ref,contentHash:k.contentHash,context:en(k.context)}));if(!Y.accepted||Y.actualHash!==k.contentHash)throw new R("EVIDENCE_REJECTED",Y.reason??"证据未通过验证或内容已改变");O.status="resolved",O.receipt={ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId};let ee=v(C,$,{kind:"evidence-recorded",stepId:O.stepId,evidenceKind:k.kind,ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId},"succeeded");Gs(C,$,O.stepId,O.sequence,O.results,{ref:k.ref,contentHash:k.contentHash},"succeeded",ee),$i(C,$)})}async function I(k){return b(k,async(C,$)=>{if(A(C),C.status==="failed")throw new R("RUN_FAILED","Run 已因失败停止,不能使证据失效");let O=C.evidenceWaits?.find(te=>te.id===k.evidenceId);if(!O)throw new R("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(O.status!=="pending")throw new R("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(O.kind!==k.kind)throw new R("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!k.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(k.ref)||k.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(k.contentHash)||!k.submissionId.trim())throw new R("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let T=$.steps[O.stepId];if(!T||T.type!=="await_evidence"||T.kind!==k.kind)throw new R("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!$.transitions.some(te=>te.from===O.stepId&&te.on==="invalidated"))throw new R("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let z=l.get(lt(T.validator));if(!z)throw new R("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let Y=Pa(await z.validate({run:Ge(C),kind:k.kind,ref:k.ref,contentHash:k.contentHash,context:en(k.context)}));if(Y.accepted&&Y.actualHash===k.contentHash)throw new R("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let ee=(Y.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);O.status="invalidated",O.invalidation={ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId,reason:ee};let G=v(C,$,{kind:"evidence-invalidated",stepId:O.stepId,evidenceKind:k.kind,ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId,reason:ee},"invalidated");Gs(C,$,O.stepId,O.sequence,O.results,{ref:k.ref,contentHash:k.contentHash,reason:ee},"invalidated",G),$i(C,$)})}async function E(k){return b(k,C=>{A(C);let $=C.waits.find(O=>O.id===k.waitId);if(!$||$.status!=="pending"||$.proposalHash!==k.proposalHash)throw new R("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");$.proposal=ct(k.proposal),$.proposalHash=j($.proposal)})}async function P(k){let C=await b(k,$=>{if($.status==="completed"){if(k.stoppedActions?.length)throw new R("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let O=$.status==="cancelled";if(O||($.actions=$.actions.map(T=>Jl(T,k.reason))),k.stoppedActions!==void 0){if(!Array.isArray(k.stoppedActions))throw new R("INVALID_ACTION","stoppedActions 必须是停止确认数组");let T=new Set;for(let z of k.stoppedActions){if(!z||typeof z!="object"||T.has(z.actionId))throw new R("INVALID_ACTION","停止确认重复或无效");T.add(z.actionId);let Y=N($,z.actionId);$.actions[$.actions.indexOf(Y)]=zw(Y,z)}}if(!O){for(let T of $.waits)T.status==="pending"&&(T.status="cancelled");for(let T of $.evidenceWaits??[])T.status==="pending"&&(T.status="cancelled");$.ready=[],$.status="cancelled",$.reason=k.reason}});return C.status==="cancelled"&&await K(C),C}async function W(k){return b(k,C=>{if(!Array.isArray(k.stoppedActions)||!k.stoppedActions.length)throw new R("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let $=new Set;for(let O of k.stoppedActions){if(!O||typeof O!="object"||$.has(O.actionId))throw new R("INVALID_ACTION","停止确认重复或无效");$.add(O.actionId);let T=N(C,O.actionId);C.actions[C.actions.indexOf(T)]=Kw(T,O)}})}async function M(k){return b(k,C=>{A(C);let $=N(C,k.actionId);if($.attempt!==k.attempt)throw new R("STALE_ACTION","Action 执行尝试已经改变");C.actions[C.actions.indexOf($)]=N_($,k.reason)})}async function H(k){return b(k,async(C,$)=>{A(C);let O=N(C,k.actionId);if(O.attempt!==k.attempt)throw new R("STALE_ACTION","Action 执行尝试已经改变");if(O.type==="child_workflow")throw new R("CHILD_MANAGED","子工作流由 Runtime 管理,不支持通过通用 retry 重置父 Action;保留原有子 Run 和执行记录");if(O.status==="succeeded"&&e.validateRecovery){if(k.expectedRevision===void 0)throw new R("REVISION_CONFLICT","恢复已提交结果必须绑定当前 Run 版本");if(k.reconciliation!==void 0)throw new R("OUTCOME_ALREADY_RECORDED","已提交结果不能声明未执行;请使用应用的语义恢复");if(typeof k.proposalHash!="string"||!k.proposalHash.trim())throw new R("INVALID_REQUEST","恢复已提交结果必须绑定当前应用决定");if(C.actions.some(G=>["running","unknown"].includes(G.status)))throw new R("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(C.status!=="completed"||C.ready.length>0||C.actions.some(G=>G.status==="pending")||C.waits.some(G=>G.status==="pending")||C.evidenceWaits?.some(G=>G.status==="pending")||Object.values(C.joins).some(G=>Object.values(G).some(te=>te.length>0))||!O.outcome||O.outcome.status!=="succeeded")throw new R("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let T=Pa(await e.validateRecovery({run:Ge(C),action:Ge(O),outcome:Ge(O.outcome),context:en(k.context),proposalHash:k.proposalHash}));if(!T.accepted)throw new R("ACTION_TERMINAL",T.reason??"应用拒绝恢复此结果");let z=O.outcome.event??"succeeded",Y=v(C,$,{kind:"action-outcome",stepId:O.stepId,outcome:O.outcome},z);if(Y?.length===0||Y===void 0&&!$.transitions.some(G=>G.from===O.stepId&&G.on===z))throw new R("ACTION_TERMINAL","应用未声明可恢复的后续工作");let ee=C.actionContexts[O.id];Gs(C,$,O.stepId,ee.sequence,ee.results,O.outcome.output,z,Y),$i(C,$);return}if(O.status==="failed"){let T=C.actionContexts[O.id].sequence,z=ee=>Object.hasOwn(ee,O.stepId)&&ee[O.stepId].sequence===T;if(Object.values(C.actionContexts).some(ee=>z(ee.results))||C.waits.some(ee=>z(ee.results))||C.evidenceWaits?.some(ee=>z(ee.results))||C.ready.some(ee=>z(ee.results))||Object.values(C.joins).some(ee=>Object.values(ee).some(G=>G.some(te=>z(te.results)))))throw new R("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}C.actions[C.actions.indexOf(O)]=S_(O,k.reconciliation),C.status="running",delete C.reason})}async function J(k,C){let $=s.get(k.executorId);if(!$)throw new R("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let O=C??await y(k.runId),T=N(O,k.actionId);if(T.status!=="pending")throw new R("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!Zk($,T))throw new R("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");si(k.context);let z=await Oe({...k,attempt:T.attempt,inputHash:T.inputHash,claimToken:Yk(),capabilities:$.capabilities},!1,O),Y=N(z,k.actionId),ee;try{si(k.context),ee=await $.execute(Ge(Y),en(k.context),$.includeRun===!1?void 0:Ge(z))}catch(te){let le=await y(k.runId),V=N(le,Y.id);throw le.status!=="cancelled"&&V.status==="running"&&V.attempt===Y.attempt&&await M({runId:k.runId,actionId:Y.id,attempt:Y.attempt,reason:te instanceof Error?te.message:String(te)}),new R("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let G=`${Y.id}:${Y.attempt}:executor-result`;try{return await B({runId:k.runId,context:en(k.context),outcome:{...ee,actionId:Y.id,attempt:Y.attempt,inputHash:Y.inputHash,claimToken:Y.claim.token,outcomeId:G}},!1,z)}catch(te){let le=await y(k.runId),V=N(le,Y.id);if(V.receipts.some(ve=>ve.outcomeId===G)){if(V.rejectedOutcomes?.some(ve=>ve.outcome.outcomeId===G))throw te;if(V.outcome?.outcomeId===G)return le}throw le.status!=="cancelled"&&V.status==="running"&&V.attempt===Y.attempt&&await M({runId:k.runId,actionId:Y.id,attempt:Y.attempt,reason:te instanceof Error?te.message.slice(0,4096):"执行结果无法提交"}),new R("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function ce(k){let C=k.maxActions??100;if(!Number.isSafeInteger(C)||C<1)throw new R("INVALID_REQUEST","maxActions 必须是正安全整数");let $=s.get(k.executorId);if(!$)throw new R("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let O=0,T=await y(k.runId),z=ee=>({reason:ee,run:T,actionsExecuted:O}),Y=ee=>{if(T.status==="completed"||T.status==="failed"||T.status==="cancelled")return T.status;if(T.actions.some(G=>G.status==="unknown"&&(!ee||G.type!=="child_workflow")))return"execution-unknown";if(T.actions.some(G=>G.status==="running"&&(!ee||G.type!=="child_workflow")))return"action-in-flight";if(T.waits.some(G=>G.status==="pending"))return"approval-required";if(T.evidenceWaits?.some(G=>G.status==="pending"))return"evidence-required"};for(;;){si(k.context);let ee=Y(!0);if(ee)return z(ee);(T.ready.length||T.children.length)&&(T=await X({runId:k.runId,context:k.context}));let G=Y(!1);if(G)return z(G);let te=T.actions.find(le=>le.status==="pending");if(!te)return z("idle");if(O>=C)return z("action-limit");if(!Zk($,te)||te.requiredCapabilities.some(le=>!$.capabilities.includes(le)))return z("executor-required");O++;try{T=await J({...k,actionId:te.id},T)}catch(le){if(!(le instanceof R)||le.code!=="EXECUTION_UNKNOWN"||(T=await y(k.runId),!T.actions.some(V=>V.status==="unknown")))throw le;return z("execution-unknown")}}}async function ne(k){let C=await va(e.store,k);return w(C.run,Bn),C}async function me(k){return Zw(await ne(k.runId),k)}function fe(k){return async(...C)=>{let $=C.map(O=>Xk(O));return Ge(await k(...$))}}return{start:fe(Q),dispatchCommand:fe(F),inspect:fe(y),inspectProjection:ne,query:fe(me),inspectCurrent:async k=>await me({runId:k,view:"current"}),executeCurrent:async k=>WP(await J(Xk(k))),runUntilBlockedCurrent:async k=>{let C=await ce(Xk(k));return{...C,run:WP(C.run)}},next:fe(X),claim:fe(Be),recordOutcome:fe(ie),resolveWait:fe(pe),recordEvidence:fe(it),invalidateEvidence:fe(I),reviseWait:fe(E),cancel:fe(P),acknowledgeStopped:fe(W),markUnknown:fe(M),retry:fe(H),execute:fe(k=>J(k)),runUntilBlocked:fe(ce)}}var qP,VP=x(()=>{"use strict";ey();ga();ha();pn();kr();Jk();Xl();Gk();BP();qP=new WeakMap});var MP=x(()=>{"use strict";pn();kr()});import{createRequire as L2}from"node:module";function dm(e,t){if(!um){let r=process.emitWarning;process.emitWarning=((n,...i)=>{String(n instanceof Error?n.message:n).startsWith("SQLite is an experimental feature and might change at any time")||Reflect.apply(r,process,[n,...i])});try{um=q2("node:sqlite").DatabaseSync}finally{process.emitWarning=r}}return t===void 0?new um(e):new um(e,t)}var q2,um,rb=x(()=>{"use strict";q2=L2(import.meta.url??__filename)});import{AsyncLocalStorage as V2}from"node:async_hooks";function HP(e){return Math.max(0,Math.min(e,(FP.getStore()?.deadline??1/0)-performance.now()))}function QP(){let e=FP.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new nb}var FP,nb,UP=x(()=>{"use strict";FP=new V2,nb=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}}});import{randomUUID as M2}from"node:crypto";import{promises as jo}from"node:fs";import Pu from"node:path";import{performance as JP}from"node:perf_hooks";async function zP(e){let t,r;try{let n=await jo.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock metadata must be a regular file: "+e);r=[n.dev,n.ino,n.size,n.mtimeMs].join(":"),t=await jo.readFile(e,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{let n=JSON.parse(t),i=n.nonce??n.id,o=typeof n.createdAt=="number"?n.createdAt:Date.parse(n.createdAt);if(typeof i=="string"&&i&&Number.isFinite(o))return{owner:{nonce:i,createdAt:o,...n.protocolVersion===2?{protocolVersion:2}:{},...typeof n.operation=="string"?{operation:n.operation}:{}},token:i,legacy:n.protocolVersion!==2}}catch{}return{owner:null,token:r,legacy:!0}}async function F2(e){let t=e+".sqlite";try{let n=await jo.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock database must be a regular file: "+t)}catch(n){if(n.code!=="ENOENT")throw n}let r;try{r=dm(Pu.toNamespacedPath(t))}catch(n){throw new Error("Unable to open Runtime lock database "+t,{cause:n})}try{return r.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE;"),r}catch(n){if(r.close(),/database is (?:locked|busy)/iu.test(String(n)))return null;throw new Error("Unable to acquire Runtime lock transaction "+t,{cause:n})}}function KP(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function H2(e,t={}){e=Pu.resolve(e),await jo.mkdir(Pu.dirname(e),{recursive:!0});let r=await jo.lstat(Pu.dirname(e));if(!r.isDirectory()||r.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+Pu.dirname(e));let n=JP.now()+HP(t.timeoutMs??3e4),i;for(;QP(),i=await F2(e),!i;){if(JP.now()>=n)throw new Error("Timed out waiting for file lock: "+e);await new Promise(s=>setTimeout(s,t.retryMs??20))}let o={protocolVersion:2,nonce:M2(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let s=await zP(e);if(s?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
195
+ Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));s&&await jo.unlink(e),await jo.writeFile(e,JSON.stringify(o),{mode:384,flag:"wx"})}catch(s){throw KP(i),s}let a=!1;return{owner:o,async release(){if(a)return!0;a=!0;let s=!0;try{let c=await zP(e);c?.token===o.nonce?c.owner?.createdAt===o.createdAt&&c.owner.operation===o.operation?await jo.unlink(e):(s=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
196
+ `)):c&&(s=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
197
+ `))}finally{KP(i)}return s}}}async function GP(e,t,r={}){let n=await H2(e,r),i;try{i=await t()}catch(o){try{await n.release()}catch(a){process.stderr.write("[comet] lock cleanup failed; preserved the original operation error: "+String(a)+`
198
+ `)}throw o}return await n.release(),i}var YP=x(()=>{"use strict";rb();UP()});import{randomUUID as XP}from"crypto";import{constants as Q2,promises as ut}from"fs";import ft from"path";async function ib(e,t){try{return await gs(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await ut.copyFile(e,t,Q2.COPYFILE_EXCL),{linked:!1}}function ja(e,t){let r=ft.relative(e,t);return r===""||!ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ft.sep}`)}function fm(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function U2(e,t){return ht(e,fm(t))}function Ta(e,t){return ht(fm(e),fm(t))}function ZP(e,t){return Ta(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pm(e){let t=await ut.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ut.realpath(e),...fm(t)}}async function lr(e){for(let t of e){let r=await ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!U2(t,r)||await ut.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function J2(e,t,r){let[n,i]=await Promise.all([ut.lstat(e),ut.realpath(e),lr(r)]);if(!n.isFile()||n.isSymbolicLink()||!Ta(n,t)||!ja(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function eO(e,t){let r=await ob(e,t);if(r)return r;let n=ft.resolve(e),i=ft.resolve(t);if(!ja(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let o=[await pm(n)],a=ft.relative(n,i).split(ft.sep).filter(Boolean),s=n;for(let c of a){await lr(o),s=ft.join(s,c);try{await ut.mkdir(s)}catch(u){if(u.code!=="EEXIST")throw u}let l=await pm(s);if(!ja(o[0].realPath,l.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${s}`);o.push(l)}return await lr(o),o}async function ob(e,t){let r=ft.resolve(e),n=ft.resolve(t);if(!ja(r,n))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await pm(r)],o=ft.relative(r,n).split(ft.sep).filter(Boolean),a=r;for(let s of o){a=ft.join(a,s);try{let c=await pm(a);if(!ja(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${a}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await lr(i),i}async function ab(e){let t;try{t=await ut.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function z2(e,t,r){let n=ft.dirname(e),i=await eO(r.containedRoot,n),o=ft.join(n,`.${ft.basename(e)}.${XP()}.tmp`),a,s,c;try{await r.beforeTemporaryOpen?.(),a=await ut.open(o,"wx"),s=await a.stat();let[l,u]=await Promise.all([ut.lstat(o),ut.realpath(o)]);if(await lr(i),!l.isFile()||l.isSymbolicLink()||!Ta(s,l)||!ja(i[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await a.writeFile(t,"utf8"):await a.writeFile(t),await a.sync(),c=await a.stat(),!Ta(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await a.close(),a=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await J2(o,c,i),await r.beforeCommit?.(),await lr(i);let f=await ut.lstat(o);if(!f.isFile()||f.isSymbolicLink()||!c||!ZP(f,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(r.requireAtomicPublication?await gs(o,e):await ib(o,e),await ut.unlink(o)):await ia(o,e),await ab(n)}catch(l){await a?.close();try{await lr(i),await ut.rm(o,{force:!0})}catch{}throw l}}async function Ht(e,t,r){await z2(e,t,r)}async function tO(e,t,r){let n=await ob(r.containedRoot,ft.dirname(e));if(!n)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await eO(r.containedRoot,ft.dirname(t)),o=await ut.lstat(e);if(!o.isFile()||o.isSymbolicLink())throw new Error("Contained link source must be a regular file");let a=ft.join(ft.dirname(t),`.${ft.basename(t)}.${XP()}.tmp`);try{await lr(n),await lr(i),await gs(e,a),await r.beforeCommit?.(),await lr(n),await lr(i);let s=await ut.lstat(a),c=await ut.lstat(e);if(!s.isFile()||s.isSymbolicLink()||!c.isFile()||c.isSymbolicLink()||!Ta(o,c)||!Ta(c,s)||o.size!==c.size||o.mtimeMs!==c.mtimeMs)throw new Error("Contained link source changed before publication");let l=await ut.lstat(t).catch(u=>{if(u.code==="ENOENT")return null;throw u});l?.isFile()&&!l.isSymbolicLink()&&Ta(c,l)?await nl(a):await ia(a,t),await ab(ft.dirname(t)),await lr(n),await lr(i)}catch(s){try{await lr(i),await ut.unlink(a)}catch{}throw s}}async function $a(e,t){let r=ft.dirname(e),n=await ob(t.containedRoot,r);if(!n)return!1;let i,o;try{i=await ut.lstat(e),o=await ut.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!ja(n[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await lr(n);let[a,s]=await Promise.all([ut.lstat(e),ut.realpath(e)]);if(!a.isFile()||a.isSymbolicLink()||!ZP(i,a)||s!==o)throw new Error("Contained file removal target changed before removal");return await nl(e),await lr(n),await ab(r),!0}var ci=x(()=>{"use strict";Gd();vs()});import{promises as Fr}from"fs";import Je from"path";import{AsyncLocalStorage as K2}from"node:async_hooks";async function mm(e,t,r={}){let n=Je.resolve(e),i=await cb(n,t),o=new Map,a=!1,s=d=>[d.dev,d.ino,d.mode,d.birthtimeNs,d.mtimeNs,d.ctimeNs].join(":"),c=d=>[d.dev,d.ino,d.mode,d.birthtimeNs].join(":"),l=async(d,m)=>JSON.stringify((await Fr.readdir(d,{withFileTypes:!0})).filter(h=>!m(h)).map(h=>[h.name,h.isDirectory(),h.isSymbolicLink()]).sort((h,p)=>String(h[0]).localeCompare(String(p[0]),"en"))),u=d=>{let m=o.get(d);return m||(m=(async()=>{let h=await Fr.lstat(d,{bigint:!0});if(!h.isDirectory()||h.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Je.relative(n,d)||"."}`);let p=await Fr.realpath(d);if(!Ys(i,p))throw new Error(`${t} resolves outside the project root`);let g=r.ignoredDirectoryEntries?.(Je.relative(n,d).replaceAll("\\","/")||".");return{stat:h,real:p,...g?{ignoreEntry:g,namespace:await l(d,g)}:{}}})(),m=m.catch(h=>{throw o.delete(d),h}),o.set(d,m)),m};await u(n);let f=async d=>{if(a)throw new Error(`${t} read session is already finished`);let m=Ao(d,t),h=n;for(let p of m.split("/").slice(0,-1))h=Je.join(h,p),await u(h);return Je.resolve(n,...m.split("/"))};return{observePath:f,async observeDirectory(d){let m=await f(d);return await u(m),m},async stat(d){let m=await f(d),h=await Fr.lstat(m,{bigint:!0});if(!h.isFile()||h.isSymbolicLink())throw new Error(`${t} must be a real file: ${d}`);return{target:m,stat:h}},async hash(d){let m=await f(d);return a_(m,{bigint:!0,label:`${t} ${d}`,verify:async(h,p)=>{if(!Ys(i,p.realPath))throw new Error(`${t} resolves outside the project root`);let g=n,v=[n];for(let w of Je.relative(n,Je.dirname(m)).split(Je.sep).filter(Boolean))g=Je.join(g,w),v.push(g);for(let w of v){let y=await o.get(w),b=await Fr.lstat(w,{bigint:!0});if(!b.isDirectory()||b.isSymbolicLink()||c(b)!==c(y.stat))throw new Error(`${t} directory changed while reading: ${Je.relative(n,w)||"."}`)}}})},async read(d,m,h={}){let p=await f(d);return da(p,m,{...h,label:`${t} ${d}`,verify:async(g,v)=>{if(!Ys(i,v.realPath))throw new Error(`${t} resolves outside the project root`);if(r.deferDirectoryChecks)return;let w=n,y=[n];for(let b of Je.relative(n,Je.dirname(p)).split(Je.sep).filter(Boolean))w=Je.join(w,b),y.push(w);for(let b of y){let N=await o.get(b),A=await Fr.lstat(b,{bigint:!0});if(!A.isDirectory()||A.isSymbolicLink()||c(A)!==c(N.stat))throw new Error(`${t} directory changed while reading: ${Je.relative(n,b)||"."}`)}}})},async finish(d={}){if(a)throw new Error(`${t} read session is already finished`);a=!0;let m=[];for(let[h,p]of o){let g=await p,v=await Fr.lstat(h,{bigint:!0});if(!v.isDirectory()||v.isSymbolicLink()||c(g.stat)!==c(v)||!d.allowDirectoryContentChanges&&s(g.stat)!==s(v)&&(!g.ignoreEntry||await l(h,g.ignoreEntry)!==g.namespace)||await Fr.realpath(h)!==g.real)throw new Error(`${t} directory changed while observing: ${Je.relative(n,h)||"."}`);s(g.stat)!==s(v)&&m.push(Je.relative(n,h).replaceAll("\\","/")||".")}return{changedDirectories:m}}}}function rO(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ys(e,t){let r=Je.relative(e,t);return r===""||!Je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Je.sep}`)}async function cb(e,t){let r=Je.resolve(e),n=await nO(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return iO(r)}async function oO(e,t,r,n){let i=e;for(let o=0;o<r.length;o++){i=Je.join(i,r[o]);let a;try{a=await nO(i)}catch(l){if(rO(l))return{exists:!1,kind:"missing"};throw l}if(a.isSymbolicLink()){let l=Je.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} crosses a symbolic link or junction at ${l}`)}let s=o===r.length-1;if(!s&&!a.isDirectory()){let l=Je.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} ancestor ${l} must be a real directory`)}if(s&&(n.expected==="file"&&!a.isFile()||n.expected==="directory"&&!a.isDirectory()||n.expected==="any"&&!a.isFile()&&!a.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let c=await iO(i);if(!Y2(t,c))throw new Error(`${n.label} resolves outside the project root`);if(s)return{exists:!0,kind:a.isFile()?"file":a.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function aO(e,t,r){let n=Ao(t,r.label),i=Je.resolve(e),o=await cb(i,r.label),a=n.split("/"),s=Je.resolve(i,...a);if(!Ys(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await oO(i,o,a,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function oe(e,t,r){if(r.expected===void 0)return aO(e,t,r);try{return await X2(e,t,r.expected)}catch(n){throw n instanceof Error&&n.message.includes("Protected project path")&&(n.message=n.message.replaceAll("Protected project path",r.label)),n}}async function xt(e,t,r){let n=Ao(t,r.label),i=Je.resolve(e),o=await cb(i,r.label),a=n.split("/"),s=i;for(let c of a){s=Je.join(s,c);let l;try{l=await Fr.lstat(s)}catch(d){if(!rO(d))throw d;try{await Fr.mkdir(s)}catch(m){if(m.code!=="EEXIST")throw m}l=await Fr.lstat(s)}let u=Je.relative(i,s).replaceAll("\\","/");if(l.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${u}`);if(!l.isDirectory())throw new Error(`${r.label} directory ${u} must be a real directory`);let f=await Fr.realpath(s);if(!Ys(o,f))throw new Error(`${r.label} resolves outside the project root`)}return await oO(i,o,a,{label:r.label,expected:"directory"}),s}async function sO(e,t,r,n){let i=!n.hooks&&!n.bigint?G2.getStore():void 0;if(i){let s=Je.resolve(e),c=i.get(s);return c||(c=mm(s,n.label,{deferDirectoryChecks:!0}).catch(l=>{throw i.delete(s),l}),i.set(s,c)),(await c).read(t,r,n)}let o=await mm(e,n.label),a=await o.read(t,r,n);return await o.finish({allowDirectoryContentChanges:!0}),a}async function De(e,t,r,n){if(n.hooks||n.bigint)return sO(e,t,r,n);try{return await Z2(e,t,r)}catch(i){throw i instanceof Error&&i.message.includes(sb)&&(i.message=i.message.replaceAll(sb,n.label)),i}}var G2,nO,iO,Y2,X2,sb,Z2,st=x(()=>{"use strict";yo();Ci();ti();G2=new K2;nO=fn("protectedChainLstat",e=>Fr.lstat(e)),iO=fn("protectedChainRealpath",e=>Fr.realpath(e)),Y2=Si("protectedChainInside",Ys);X2=fn("protectedInspectPath",(e,t,r)=>aO(e,t,{label:"Protected project path",expected:r}));sb="Cached protected project read",Z2=fn("protectedReadFile",(e,t,r)=>sO(e,t,r,{label:sb}))});function lO(e){return hm(e).encoded}function hm(e){let t=new WeakMap,r=new Map,n=u=>{if(typeof u=="string"){let h=r.get(u);return h===void 0&&(h=JSON.stringify(u).length,r.set(u,h)),h}if(u===null||typeof u!="object")return JSON.stringify(u).length;let f=cO.get(u)??t.get(u);if(f!==void 0)return f;let d=Object.entries(u),m=2+Math.max(0,d.length-1)+d.reduce((h,[p,g])=>h+(Array.isArray(u)?0:n(p)+1)+n(g),0);return t.set(u,m),mn(u)&&cO.set(u,m),m},i=n(e),o=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return o();let a=[],s=(u,f)=>{if(!u||typeof u!="object")return;let d=u;if(!(d.protocolVersion!==1||!Array.isArray(d.actions)||!d.actionContexts)){for(let[m,h]of d.actions.entries())h.input&&typeof h.input=="object"&&Object.hasOwn(h.input,"outputs")&&a.push({path:[...f,"actions",String(m),"input","outputs"],group:"outputs"});for(let[m,h]of Object.entries(d.actionContexts))h?.results&&a.push({path:[...f,"actionContexts",m,"results"],group:"results"});d.outputs&&a.push({path:[...f,"outputs"],group:"results"});for(let m of["ready","waits","evidenceWaits"])for(let[h,p]of(d[m]??[]).entries())p.results&&a.push({path:[...f,m,String(h),"results"],group:"results"})}};if(s(e,[]),s(e.run,["run"]),!a.length)return o();let c=T_(e,a,mn),l=JSON.stringify(c);return l.length<i*.9?{encoded:c,json:l}:o()}var cO,lb=x(()=>{"use strict";ga();kr();cO=new WeakMap});import{createHash as dO,randomUUID as aee}from"node:crypto";import{types as ez}from"node:util";import{promises as Rn}from"node:fs";import Pt from"node:path";function Da(e){if(typeof e!="string"||e.trim().length===0)throw new R("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function tz(e){return Da(e),dO("sha256").update(JSON.stringify(e)).digest("hex")}function gm(e){if(!Number.isSafeInteger(e)||e<1)throw new R("STORE_INVALID_REVISION","revision 必须是正安全整数")}function rz(e,t,r,n=!0){if(Da(e),ez.isProxy(r))throw new R("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&gm(t),hn(r);let i=n?structuredClone(r):r;if(!i||typeof i!="object"||Array.isArray(i)||i.runId!==e)throw new R("STORE_INVALID_RUN_ID","next.runId 必须与目标 runId 一致");if(gm(i.revision),i.revision!==(t??0)+1)throw new R("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}function nz(e,t,r){let n=ct(r);if(Da(e),!n||n.runId!==e)throw new R("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(gm(n.revision),t!==null&&t!==1||n.revision<=(t??0))throw new R("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(n)}function fO(e,t,r){let n=ct(e);n.revision=t;for(let i of r){let o=n;for(let a of i.slice(0,-1))o=o[a];o[i.at(-1)]=t}return n}function iz(e,t,r,n=[]){return(e?.revision??null)===t&&(e===null||ri(e)===ri(fO(r,1,n)))}function vt(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new R("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(I=>{if(I!=="run.revision")throw new R("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function r(I){for(let E of t){let P=I;for(let W of E){if(!P||typeof P!="object"||Array.isArray(P)||!Object.hasOwn(P,W))throw new R("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");P=P[W]}if(P!==I.revision)throw new R("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let n=Pt.resolve(e.rootDir),i=Pt.parse(n).root,o=Pt.relative(i,n).replaceAll("\\","/");if(!o)throw new R("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let a={label:"RuntimeStore root",expected:"directory"},s=tz,c="checkpoint.json",l="comet.runtime-store-format.v2",u=".runtime-store-v2",f=I=>`${u}/${s(I)}`,d=I=>`.runtime-store-history/${s(I)}`,m="comet.runtime-store-format.v3",h="comet.runtime-store-snapshot.v2",p=".write.lock",g=/^[0-9]{16}\.json$/u;function v(){return{record:null,compacted:!1,legacyRevision:null,formatPresent:!1}}async function w(I,E){let P=await De(n,I?`${I}/${E}`:E,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let W=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.bytes));return hn(W),W}catch{throw new R("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function y(I,E,P){if(!I||typeof I!="object"||Array.isArray(I)||I.runId!==E||I.revision!==P||!Number.isSafeInteger(P)||P<1)throw new R("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");r(I)}async function b(I,E=!1,P=s(I),W=!0){if(Da(I),!(await oe(i,o,a)).exists)return v();let M=await oe(n,P,{label:"RuntimeStore run",expected:"directory"});if(!M.exists)return v();let H=await Rn.lstat(M.target),J=await Rn.readdir(M.target,{withFileTypes:!0}),ce=await Rn.lstat(M.target);if(await oe(i,`${o}/${P}`,a),!H.isDirectory()||H.isSymbolicLink()||!ce.isDirectory()||ce.isSymbolicLink()||!ht({dev:H.dev,ino:H.ino,birthtime:H.birthtimeMs},{dev:ce.dev,ino:ce.ino,birthtime:ce.birthtimeMs}))throw new R("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let ne=new Set,me=[],fe=0;for(let V of J){if((V.name===`${p}.contenders`||V.name==="legacy"&&P===f(I))&&V.isDirectory()&&!V.isSymbolicLink())continue;if(!V.isFile()||V.isSymbolicLink())throw new R("STORE_INVALID_ENTRY",`版本文件无效:${V.name}`);if(/^\..+\.tmp$/u.test(V.name)||V.name===p||[p+".sqlite",p+".sqlite-journal",p+".sqlite-wal",p+".sqlite-shm"].includes(V.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test(V.name)||(ne.add(V.name),V.name===c))continue;if(!g.test(V.name))throw new R("STORE_INVALID_ENTRY",`版本文件无效:${V.name}`);let ve=Number(V.name.slice(0,-5));if(!Number.isSafeInteger(ve)||ve<1)throw new R("STORE_INVALID_ENTRY",`版本文件无效:${V.name}`);me.push(V.name),fe=Math.max(fe,ve)}let k=!1;if([f(I),d(I)].includes(P)&&me.length>0)throw new R("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(ne.has(c)){if(![f(I),d(I)].includes(P))throw new R("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let V=await w(P,c),ve=V?.record,ae=V?.legacyRevision;if(!V||![h,"comet.runtime-store-snapshot.v3"].includes(String(V.schema))||!ve||Object.keys(V).some(dt=>!["schema","record","hash","legacyRevision",...V.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(dt))||ae!==null&&(!Number.isSafeInteger(ae)||ae<1||ae>ve.revision)||V.hash!==j({record:ve,legacyRevision:ae,...V.schema==="comet.runtime-store-snapshot.v3"?{pool:V.pool}:{}}))throw new R("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let Re;try{Re=V.schema==="comet.runtime-store-snapshot.v3"?yp(ve,V.pool,W):ve}catch(dt){throw new R("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${dt instanceof Error?dt.message:String(dt)}`)}return y(Re,I,Re.revision),{record:Re,compacted:!0,legacyRevision:ae,formatPresent:k}}if(!fe)return v();let C=new Map,$=V=>`${String(V).padStart(16,"0")}.json`,O=V=>ne.has($(V));async function T(V){if(C.has(V))return C.get(V);let ve=await w(P,$(V));return(V<=2||V===fe)&&C.set(V,ve),ve}async function z(V,ve=0,ae=fe){if(y(V,I,ae),E)for(let Re of me){let dt=Number(Re.slice(0,-5));dt!==ve&&y(await T(dt),I,dt)}return{record:V,compacted:!1,legacyRevision:V.revision,formatPresent:!1}}let Y=await T(fe);if(fe===me.length&&(Y?.schema!==uO||Y?.runId!==void 0))return z(Y);if(!O(1))throw new R("STORE_MISSING_REVISION","版本历史缺少 revision 1");let ee=null;for(let V of[1,2]){if(!O(V))break;let ve=await T(V);if(ve?.schema!==uO||"runId"in ve)continue;let ae=ve.record;if(ae&&r(ae),!ae||ae.runId!==I||!Number.isSafeInteger(ae.revision)||ae.revision<V||ve.hash!==j(ae)||Object.keys(ve).some(Re=>!["schema","record","hash"].includes(Re))||V===2&&ri(await T(1))!==ri(fO(ae,1,t)))throw new R("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");ee={slot:V,record:ae};break}let G=ee?.record.revision??0,te=ee?.slot??0,le=fe===te?G:fe;if(le<G||me.length!==le-G+te||me.some(V=>{let ve=Number(V.slice(0,-5));return ve>te&&ve<=G})){let V=G+1;for(;O(V);)V+=1;throw new R("STORE_MISSING_REVISION",`版本历史缺少 revision ${V}`)}return z(ee&&fe===ee.slot?ee.record:Y,te,ee&&fe===ee.slot?ee.record.revision:fe)}async function N(I){let E=await oe(n,s(I),{label:"RuntimeStore format",expected:"any"}),P=await oe(n,`${f(I)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if(E.kind==="directory"&&P.exists&&(E=await oe(n,s(I),{label:"RuntimeStore format",expected:"any"})),E.kind==="directory"&&P.exists)throw new R("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let W=null;if(E.kind==="file"){let M=await w("",s(I));if(!M||M.runId!==I||(M.schema===l?!["pending","ready"].includes(M.state)||Object.keys(M).some(H=>!["schema","runId","state","writerProtocol"].includes(H)):M.schema!==m||!["closing","closed","reopening"].includes(M.state)||!Number.isSafeInteger(M.revision)||M.revision<1||typeof M.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(M.recordHash)||Object.keys(M).some(H=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(H))))throw new R("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(M.writerProtocol!==void 0&&M.writerProtocol!=="application-holder-v1")throw new R("STORE_WRITER_FENCED","存储协议版本不受支持");W=M}return{original:E,staged:P,marker:W}}function A(I){return Gl(I)?Bn(I,{cachePrefixes:!1}):j(I)}async function S(I,E){let P=await b(I,!1,f(I),!1),W=await b(I,!1,d(I),!1);if(!P.record&&!W.record||E.state==="closed"&&(P.record||!W.record))throw new R("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(P.record&&W.record){let H=await Rn.lstat(Pt.join(n,f(I),c)),J=await Rn.lstat(Pt.join(n,d(I),c)),ce={dev:H.dev,ino:H.ino,birthtime:H.birthtimeMs},ne={dev:J.dev,ino:J.ino,birthtime:J.birthtimeMs};if(!il(ce,ne)||!ht(ce,ne))throw new R("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let M=W.record??P.record;if(M.revision!==E.revision||A(M)!==E.recordHash||P.record&&P.record!==M&&A(P.record)!==E.recordHash)throw new R("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:M,active:!!P.record,history:!!W.record}}async function _(I){if(Da(I),!(await oe(i,o,a)).exists)return"missing";let E=await N(I),P=await oe(n,`${f(I)}/${c}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),W=await oe(n,`${d(I)}/${c}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(E.marker?.schema===m){if(!P.exists&&!W.exists||E.marker.state==="closed"&&(P.exists||!W.exists))throw new R("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return E.marker.state}if(W.exists)throw new R("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return E.marker||P.exists||E.original.kind==="directory"||E.staged.exists?"active":"missing"}async function Q(I,E,P){await Ht(Pt.join(n,s(I)),JSON.stringify({schema:m,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:I,state:E,revision:P.revision,recordHash:A(P)})+`
199
+ `,{containedRoot:n,requireAtomicPublication:!0})}async function F(I){let E=(await N(I)).marker;if(!E||!["closing","reopening"].includes(E.state))return;let P=E.state==="closing",W=(await S(I,E)).record,M=await S(I,E),H=P?f(I):d(I),J=P?d(I):f(I);await xt(n,J,{label:"RuntimeStore 历史目标"});let ce=Pt.join(n,H,c),ne=Pt.join(n,J,c),me=P?M.active:M.history;(P?M.history:M.active)||(await oe(n,`${H}/${c}`,{label:"RuntimeStore 历史源",expected:"file"}),await oe(n,J,{label:"RuntimeStore 历史目标",expected:"directory"}),await Rn.link(ce,ne),await S(I,E)),await Oe(Pt.dirname(ne)),await Oe(Pt.dirname(Pt.dirname(ne))),await Oe(n),me&&(await S(I,E),await $a(ce,{containedRoot:n,beforeRemove:async()=>{await S(I,E)}}),await Oe(Pt.dirname(ce))),P?await Q(I,"closed",W):await X(I,"ready",!1);let k=await Z(I,!1);if(!k||k.revision!==W.revision||A(k)!==A(W))throw new R("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function K(I,E,P){return Da(I),gm(E),Be(I,async()=>{await F(I);let W=(await N(I)).marker,M;if(W?.schema===m){if(P&&W.state==="reopening")throw new R("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!P&&W.state==="closing")throw new R("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(M=(await S(I,W)).record,M.revision!==E)return!1;if(P&&W.state==="closed")return!0}else{if(M=(await pe(I,!1)).record,!M||M.revision!==E)return!1;if(!P)return!0}return await Q(I,P?"closing":"reopening",M),await F(I),!0})}async function Z(I,E=!0){if(Da(I),!(await oe(i,o,a)).exists)return null;let P=await N(I);if(P.marker?.schema===m){let{record:H}=await S(I,P.marker);return E?br(H):H}if((await b(I,!1,d(I),!1)).record)throw new R("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let M=await b(I,!1,f(I),E);if(M.record){if(!P.marker&&!(await N(I)).marker)throw new R("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return M.record}if(P.original.kind==="directory"){let H=(await b(I)).record;if(!H&&(await N(I)).original.kind!=="directory")throw new R("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return H}if(P.marker?.state==="ready")throw new R("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(P.staged.exists){let H;try{H=(await b(I,!1,`${f(I)}/legacy`)).record}catch(J){throw(await N(I)).marker?.state==="ready"?new R("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):J}if(!H){let J=await N(I);if(!J.staged.exists||J.marker?.state==="ready")throw new R("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return H}return null}async function re(I,E=!0){for(let P=0;;P+=1)try{return await Z(I,E)}catch(W){let M=W instanceof jt&&W.reason==="changed",H=["ENOENT","ENOTDIR"].includes(W.code??""),J=W instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(W.message);if(!M&&!H&&!J||P>=15)throw W}}async function X(I,E,P){await Ht(Pt.join(n,s(I)),JSON.stringify({schema:l,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:I,state:E})+`
200
+ `,{containedRoot:n,exclusive:P,requireAtomicPublication:!0})}async function Oe(I){let E;try{E=await Rn.open(I,"r"),await E.sync()}catch(P){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(P.code??""))throw P}finally{await E?.close()}}async function Be(I,E){if(await xt(i,o,a),(await oe(n,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new R("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await xt(n,f(I),{label:"RuntimeStore run"}),await Oe(Pt.join(n,u)),await Oe(n);try{return e.singleWriter?await E():await GP(Pt.join(n,f(I),p),E)}catch(W){throw["ENOTSUP","EOPNOTSUPP"].includes(W.code??"")?new R("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):W}}async function B(I,E,P,W=hm(E)){let M=Pt.join(n,f(I)),H=P.legacyRevision,{encoded:J,json:ce}=W,ne=J.pool?{record:J.record,legacyRevision:H,pool:J.pool}:{record:E,legacyRevision:H},me=J.pool?"comet.runtime-store-snapshot.v3":h,fe=`{"schema":${JSON.stringify(me)},${ce.slice(1,-1)},"legacyRevision":${JSON.stringify(H)},"hash":${JSON.stringify(j(ne))}}
201
+ `;await Ht(Pt.join(M,c),fe,{containedRoot:n,exclusive:!P.compacted,requireAtomicPublication:!0}),P.formatPresent||await X(I,"ready",!1)}async function ie(I,E){if(E===null)return;let P=`${f(I)}/legacy`,W=await oe(n,P,{label:"RuntimeStore legacy",expected:"directory"});if(W.exists)try{for(let M of await Rn.readdir(W.target,{withFileTypes:!0}))M.isFile()&&!M.isSymbolicLink()&&g.test(M.name)&&Number(M.name.slice(0,-5))<=E&&await $a(Pt.join(W.target,M.name),{containedRoot:n});await oe(n,P,{label:"RuntimeStore legacy",expected:"directory"}),await Rn.rmdir(W.target).catch(M=>{if(M.code!=="ENOTEMPTY"&&M.code!=="EEXIST")throw M})}catch(M){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${M instanceof Error?M.message:String(M)}
202
+ `)}}async function pe(I,E=!0){let P=(await N(I)).marker;if(P?.writerProtocol&&P.writerProtocol!==e.writerProtocol)throw new R("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await F(I);let W=await N(I);if(W.marker?.schema===m)throw new R("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await b(I,!1,d(I),!1)).record)throw new R("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let H=await b(I,!1,f(I),E);if(H.record&&!W.marker)throw new R("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(W.original.kind==="directory"){await b(I,!0);let ce=await Rn.lstat(W.original.target);await oe(i,`${o}/${s(I)}`,a),await oe(n,f(I),a),await Rn.rename(W.original.target,W.staged.target);let ne=await Rn.lstat(W.staged.target);if(!ne.isDirectory()||ne.isSymbolicLink()||!ht({dev:ce.dev,ino:ce.ino,birthtime:ce.birthtimeMs},{dev:ne.dev,ino:ne.ino,birthtime:ne.birthtimeMs}))throw new R("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await Oe(Pt.join(n,f(I))),await Oe(n),W=await N(I)}if(!W.marker){try{await X(I,"pending",!0)}catch(ce){throw["EEXIST","EISDIR","ENOTDIR"].includes(ce.code??"")?new R("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):ce}W=await N(I)}let J=H;if(!J.record&&W.marker?.state==="ready")throw new R("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!J.record&&W.staged.exists?(J=await b(I,!0,`${f(I)}/legacy`),J.record&&(await B(I,J.record,J),J={...J,compacted:!0,formatPresent:!0})):J.record&&W.marker?.state==="pending"&&await X(I,"ready",!1),J.record&&(J.formatPresent=!0,await ie(I,J.legacyRevision)),J}return{queryScope:`file:${dO("sha256").update(n).digest("hex")}`,read:re,readProjection:I=>re(I,!1),readPartitionMetadata:_,settleRun:I=>ei(async()=>await _(I)==="missing"?"missing":Be(I,async()=>{await F(I);let E=(await N(I)).marker;return E&&e.writerProtocol&&E.writerProtocol!==e.writerProtocol&&await Ht(Pt.join(n,s(I)),JSON.stringify({...E,writerProtocol:e.writerProtocol})+`
203
+ `,{containedRoot:n,requireAtomicPublication:!0}),_(I)})),closeRun:(I,E)=>ei(()=>K(I,E,!0)),reopenRun:(I,E)=>ei(()=>K(I,E,!1)),async readDisposition(I){if(!await re(I,!1))return"missing";let P=(await N(I)).marker;return P?.schema===m?P.state:"active"},async restoreCheckpoint(I,E,P){let W=JSON.parse(nz(I,E,P));return r(W),Be(I,async()=>{let M=await pe(I);return iz(M.record,E,W,t)?(await B(I,W,M),!0):!1})},compareAndSwap:async(I,E,P)=>it(I,E,P)(),prepareCompareAndSwap:it};function it(I,E,P){rz(I,E,P,!1),r(P);let{json:W}=hm(P),M=JSON.parse(W);return()=>Be(I,async()=>{let H=await pe(I,!1);return(H.record?.revision??null)!==E?!1:(await B(I,M.record,H,{encoded:M,json:W}),!0)})}}var uO,Ou=x(()=>{"use strict";vs();yo();YP();ci();st();kr();ti();pn();lb();ga();uO="comet.runtime-store-checkpoint.v1"});import{createHash as pO}from"node:crypto";import{promises as Di}from"node:fs";import $o from"node:path";async function ub(e){let t=$o.resolve(e.rootDir),r=$o.parse(t).root,n=$o.relative(r,t).replaceAll("\\","/");if(!n)throw new R("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");if(!(await oe(r,n,{label:"RuntimeStore discovery",expected:"directory"})).exists)return[];let i=[];for(let o of await Di.readdir(t,{withFileTypes:!0}))if(!(/^\.[a-f0-9]{64}\.[a-f0-9-]{36}\.tmp$/u.test(o.name)&&o.isFile()&&!o.isSymbolicLink())&&o.name!==".runtime-store-coordination"){if([".runtime-store-v2",".runtime-store-history"].includes(o.name)){let a=await oe(t,o.name,{label:"RuntimeStore checkpoint directory",expected:"directory"});for(let s of await Di.readdir(a.target))i.push(s);continue}i.push(o.name)}return[...new Set(i)].sort((o,a)=>o.localeCompare(a))}async function oz(e,t,r,n=!1){let i=$o.resolve(e.rootDir),o=r?[...new Set(r)].filter(d=>d&&d!=="."&&d!==".."&&!d.includes("/")&&!d.includes("\\")):await ub(e),a=r?new Set(r):null,s=[],c=async d=>{let m=await oe(i,d,{label:"RuntimeStore source",expected:"file"});if(!m.exists)return null;let h=await Di.lstat(m.target);return[d,h.size,h.mtimeMs,h.ctimeMs,h.ino,h.dev]},l=async d=>{let m=await oe(i,d,{label:"RuntimeStore source directory",expected:"directory"});if(!m.exists)return null;let h=await Di.lstat(m.target),p=(await Di.readdir(m.target,{withFileTypes:!0})).map(g=>[g.name,g.isFile(),g.isDirectory(),g.isSymbolicLink()]).sort((g,v)=>String(g[0]).localeCompare(String(v[0])));return[d,h.mtimeMs,h.ctimeMs,h.ino,h.dev,p]},u=async d=>JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await De(i,d,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore discovery record"})).bytes)),f=n?8:1;for(let d=0;d<o.length;d+=f)await Promise.all(o.slice(d,d+f).map(async m=>{if(a&&!a.has(m))return;let h=await Di.lstat($o.join(i,m)).catch(()=>null),p={name:m,isFile:()=>h?.isFile(),isDirectory:()=>h?.isDirectory(),isSymbolicLink:()=>h?.isSymbolicLink()},g=null,v=!1;try{if(!/^[a-f0-9]{64}$/u.test(p.name)||p.isSymbolicLink())throw new R("STORE_INVALID_ENTRY","RuntimeStore 目录含异常项目");let w;if(p.isFile()){let N=await u(p.name);if(!["comet.runtime-store-format.v2","comet.runtime-store-format.v3"].includes(N.schema))throw new R("STORE_CORRUPT_RECORD","RuntimeStore 格式标记无效");if(w=N.runId,n&&N.schema==="comet.runtime-store-format.v3"&&N.state==="closed"){if(!Number.isSafeInteger(N.revision)||N.revision<1||N.writerProtocol!==void 0&&N.writerProtocol!=="application-holder-v1"||typeof N.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(N.recordHash)||Object.keys(N).some(_=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(_)))throw new R("STORE_CORRUPT_RECORD","RuntimeStore 历史标记损坏");let A=await oe(i,`.runtime-store-v2/${p.name}/checkpoint.json`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),S=await oe(i,`.runtime-store-history/${p.name}/checkpoint.json`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(A.exists||!S.exists)throw new R("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");v=!0}}else if(p.isDirectory()){await oe(i,p.name,{label:"RuntimeStore legacy directory",expected:"directory"});let N=(await Di.readdir($o.join(i,p.name))).filter(S=>/^[0-9]{16}\.json$/u.test(S)).sort();if(!N.length)throw new R("STORE_CORRUPT_RECORD","RuntimeStore 旧记录缺少版本");let A=await u(`${p.name}/${N.at(-1)}`);w=A.schema==="comet.runtime-store-checkpoint.v1"?A.record?.runId:A.runId}else throw new R("STORE_INVALID_ENTRY","RuntimeStore 项目类型无效");if(typeof w!="string"||!w.trim()||pO("sha256").update(JSON.stringify(w)).digest("hex")!==p.name)throw new R("STORE_CORRUPT_RECORD","RuntimeStore 记录身份与目录不匹配");if(g=w,v)return;let y=t?p.isFile()?[p.name,`.runtime-store-v2/${p.name}/checkpoint.json`,`.runtime-store-history/${p.name}/checkpoint.json`]:(await Di.readdir($o.join(i,p.name))).filter(N=>/^[0-9]{16}\.json$/u.test(N)).sort().map(N=>`${p.name}/${N}`):[],b=pO("sha256").update(JSON.stringify({files:await Promise.all(y.map(c)),directories:t?await Promise.all((p.isFile()?[`.runtime-store-v2/${p.name}`,`.runtime-store-history/${p.name}`]:[p.name]).map(l)):[]})).digest("hex");s.push({storageKey:p.name,runId:g,fingerprint:b,error:null})}catch(w){s.push({storageKey:p.name,runId:g,fingerprint:JSON.stringify(await Di.lstat($o.join(i,p.name)).then(y=>[y.size,y.mtimeMs,y.ctimeMs,y.ino]).catch(()=>null)),error:{code:w instanceof R?w.code:"STORE_UNREADABLE",message:w instanceof Error?w.message:String(w)}})}}));return s.sort((d,m)=>d.storageKey.localeCompare(m.storageKey))}async function db(e){return oz(e,!0)}var mO=x(()=>{"use strict";st();Ou();pn()});function vm(e){return az.test(e)?e:`portable-${j(e)}`}function fb(e){let t=lO(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:j(t)}:e}function sz(e){return{...e,revision:1,actions:e.actions.map(t=>{let r=new Set((t.rejectedOutcomes??[]).map(i=>i.outcome.outcomeId)),n={...t,receipts:t.receipts.filter(i=>!r.has(i.outcomeId)).map(i=>({...i}))};if(delete n.rejectedOutcomes,t.claim){let i=vm(t.claim.token);if(n.claim={...t.claim,token:i},t.executionStop&&(n.executionStop={...t.executionStop,claimToken:i}),t.cancellation&&(n.cancellation={...t.cancellation,claimToken:i}),t.outcome){n.outcome={...t.outcome,claimToken:i};let o=n.receipts.find(a=>a.outcomeId===t.outcome.outcomeId);o&&(o.hash=j(n.outcome))}}return t.status==="running"&&(n.status="unknown",n.reason="Portable recovery requires reconciliation of external execution"),n})}}function pb(e){let t=vn(sz(e),e.runId),r=j(t);return{schema:hO,hash:r,run:t,sourceRevision:e.revision,sourceHash:j({hash:r,sourceRevision:e.revision})}}function lz(e,t,r={},n=!1){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Portable Run checkpoint for ${t} is invalid`);hn(e);let i=e;if(![hO,"comet.workflow-run-checkpoint.v2"].includes(String(i.schema))||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash)||Object.keys(i).some(s=>!["schema","hash","run","sourceRevision","sourceHash",...i.schema==="comet.workflow-run-checkpoint.v2"?["pool","storageHash"]:[]].includes(s))||i.schema==="comet.workflow-run-checkpoint.v2"&&j({record:i.run,pool:i.pool})!==i.storageHash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=i.schema==="comet.workflow-run-checkpoint.v2"?yp(i.run,i.pool,!n):i.run;if((n?Bn:j)(o)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let a=n?bp(o,t,cz):vn(o,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==j({hash:i.hash,sourceRevision:i.sourceRevision}))throw new Error(`Portable Run checkpoint revision for ${t} is invalid or changed`);if(r.preserveSourceRevision)return{...a,revision:i.sourceRevision}}return a}function wm(e,t,r={}){return lz(e,t,r)}function mb(e){let t=structuredClone(e);for(let r of t.actions)r.claim&&!r.executionOrigin&&(r.executionOrigin={workflow:{...e.workflow}});return t}var Bi,hO,az,cz,gO=x(()=>{"use strict";Xl();kr();lb();ga();Bi="run_checkpoint",hO="comet.workflow-run-checkpoint.v1",az=/^portable-[a-f0-9]{64}$/u;cz={hash:Bn,visitResults:vp,validateOrigins:wp}});var Me=x(()=>{"use strict";VP();MP();Gk();Ou();mO();Xl();pn();kr();gO();ey()});function Ba(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}function wO(e,t){let r=(0,ym.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}function Do(e,t){let r=e.lastIndexOf(vO);if(e.startsWith(Tu)&&r>=0&&e.endsWith(`
204
+ `)){let n=e.slice(r+vO.length,-1);try{let i=JSON.parse(n);if(JSON.stringify(i)===n){let o=e.slice(0,r+1),a=wO(o,t);if(a&&typeof a=="object"&&!Array.isArray(a)&&!Object.hasOwn(a,Bi)&&Tu+(0,ym.stringify)(a)===o)return{...a,[Bi]:i}}}catch{}}return wO(e,t)}var ym,Tu,vO,ju=x(()=>{"use strict";ym=tr(jr(),1);Me();Tu=`# comet-execution: managed-run
205
+ `;vO=`
206
+ ${Bi}: `});function km(e){let t=e.input;if(!t||typeof t!="object"||typeof t.candidateId!="string"||!t.candidateId||typeof t.identityProvider!="string"||!t.identityProvider||typeof t.builderExecutionRef!="string"||!t.builderExecutionRef||t.verifierExecutionRef!==null&&typeof t.verifierExecutionRef!="string"||!Number.isSafeInteger(t.iteration)||t.iteration<1||!Number.isSafeInteger(t.goalCycle)||t.goalCycle<1||typeof t.registeredAt!="string"||Number.isNaN(Date.parse(t.registeredAt))||e.type!=="handoff"||e.ref!=="native-verifier"||e.stepId!=="native-verifier"||t.verifierExecutionRef!==null&&t.verifierExecutionRef===t.builderExecutionRef||e.claim&&(e.claim.executorId!==t.identityProvider||e.claim.token===t.builderExecutionRef||t.verifierExecutionRef!==null&&e.claim.token!==t.verifierExecutionRef))throw new Error("Native Verifier action binding is invalid");return t}function hb(e,t){let r=km(t);return t.runId===e.name&&r.candidateId===e.builder_handoff?.candidate_id&&r.identityProvider===e.builder_handoff.identity_provider&&r.builderExecutionRef===e.builder_handoff.builder_execution_ref&&r.iteration===e.loop.iteration&&r.goalCycle===e.loop.goal_cycle&&t.attempt===e.loop.attempt}function gb(e){let t=e.verifier_action;return t&&e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"&&["pending","running","unknown"].includes(t.status)&&hb(e,t)?t:void 0}function vb(e){return e.claim?.token??km(e).verifierExecutionRef}var $u=x(()=>{"use strict";ha();kr()});function Bu(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Xs,Du,Zs=x(()=>{"use strict";Xs="comet.native.v4",Du=["multi-session","single-session"]});var Rb={};Dd(Rb,{NativePortableStateVersionConflictError:()=>Wu,appendNativePortableHistory:()=>tn,compareAndSwapNativePortableState:()=>Ab,createNativePortableState:()=>rc,parseNativePortableState:()=>L,parseNativeReportedChecks:()=>li,readNativePortableState:()=>Gt,writeNativePortableState:()=>bb});import{promises as pz}from"node:fs";function yz(e,t){let r=Qt(e,"Native approved children plan");if(!Array.isArray(r.children))throw new Error("Native approved children plan requires children");let n=r.children.map(i=>{let o={...Qt(i,"Native approved child")};return r.schema==="comet.native.children.v2"&&!r.acceptance_index&&typeof o.summary=="string"?delete o.covers:delete o.summary,o});return rp(JSON.stringify({...r,children:n}),t.map(i=>i.id),{acceptanceCatalog:t})}function Qt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Nr(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function mt(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function yb(e,t){return e===null?null:mt(e,t)}function kO(e,t){let r=mt(e,t);if(!vz.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ec(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function pt(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function kz(e,t){return e===null?null:pt(e,t,Number.MIN_SAFE_INTEGER)}function Ot(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Nn(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((n,i)=>r(n,i))}function Rm(e,t){return Nn(e,t,(r,n)=>mt(r,`${t}[${n}]`))}function Wa(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function tc(e,t){let r=mt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Am(e,t,r=!1){let n=mt(e,t);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return n}function Sn(e,t){let r=Qt(e,t);return Nr(r,new Set(["text","truncated"]),t),{text:mt(r.text,`${t}.text`,{empty:!0}),truncated:ec(r.truncated,`${t}.truncated`)}}function bz(e,t){let r=`Native spec_changes[${t}]`,n=Qt(e,r);Nr(n,new Set(["capability","operation","source","delta_source","base_hash"]),r);let i=mt(n.capability,`${r}.capability`);if(!hz.test(i))throw new Error(`${r}.capability is invalid`);let o=Ot(n.operation,["create","modify","remove"],`${r}.operation`),a=n.source===null?null:Am(n.source,`${r}.source`),s=n.delta_source===void 0?void 0:Am(n.delta_source,`${r}.delta_source`),c=n.base_hash===void 0?void 0:n.base_hash===null?null:kO(n.base_hash,`${r}.base_hash`);if(o==="remove"&&a!==null)throw new Error(`${r} remove requires source null`);if(o!=="remove"&&a===null)throw new Error(`${r} ${o} requires a source`);if(s!==void 0&&o==="remove")throw new Error(`${r} remove cannot contain delta_source`);return{capability:i,operation:o,source:a,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function Az(e){let t="Native workspace",r=Qt(e,t);Nr(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let n=Ot(r.isolation,["current","branch","worktree"],`${t}.isolation`),i=yb(r.change_branch,`${t}.change_branch`),o=yb(r.target_branch,`${t}.target_branch`),a=r.finish===null?null:Ot(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(n==="current"&&a!==null)throw new Error("Native current workspace cannot contain a finish action");if(n==="current"&&i===null!=(o===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(n!=="current"&&(i===null||o===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:n,change_branch:i,target_branch:o,finish:a}}function Rz(e){let t="Native loop",r=Qt(e,t);Nr(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let n=Rm(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Wa(n,`${t}.previous_unresolved_ids`);let i=r.stop_reason===void 0?void 0:Ot(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Ot(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:pt(r.goal_cycle,`${t}.goal_cycle`,1),iteration:pt(r.iteration,`${t}.iteration`),attempt:pt(r.attempt,`${t}.attempt`),retry_epoch:pt(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:pt(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:pt(r.no_progress_count,`${t}.no_progress_count`),...i===void 0?{}:{stop_reason:i},execution_failure_count:pt(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:n,next_action:yb(r.next_action,`${t}.next_action`)}}function Nz(e,t){let r=`Native acceptance[${t}]`,n=Qt(e,r);Nr(n,new Set(["id","source","text","result","reason"]),r);let i=mt(n.id,`${r}.id`);if(!gz.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:Am(n.source,`${r}.source`),text:mt(n.text,`${r}.text`),result:Ot(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:Sn(n.reason,`${r}.reason`)}}function kb(e,t){let r=`Native builder_handoff.checks[${t}]`,n=Qt(e,r);return Nr(n,new Set(["name","result","note"]),r),{name:Sn(n.name,`${r}.name`),result:Ot(n.result,Kc,`${r}.result`),note:n.note===null?null:Sn(n.note,`${r}.note`)}}function li(e){return Nn(e,"Native reported checks",(t,r)=>{let n=Qt(t,`Native reported checks[${r}]`);return kb({name:Ct(mt(n.name,"Reported check name")),result:n.result,note:n.note==null?null:Ct(mt(n.note,"Reported check note"))},r)})}function Sz(e){let t="Native builder_handoff",r=Qt(e,t);Nr(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at","raw_input_ref"]),t);let n=Rm(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Wa(n,`${t}.addressed_acceptance_ids`);let i=r.review===null||r.review===void 0?null:Qt(r.review,`${t}.review`);return i&&Nr(i,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:mt(r.candidate_id,`${t}.candidate_id`),identity_provider:mt(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:mt(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:pt(r.iteration,`${t}.iteration`,1),summary:Sn(r.summary,`${t}.summary`),addressed_acceptance_ids:n,...r.acceptance_review===void 0?{}:{acceptance_review:dp(r.acceptance_review)},checks:Nn(r.checks,`${t}.checks`,kb),checks_truncated:ec(r.checks_truncated,`${t}.checks_truncated`),known_limits:Nn(r.known_limits,`${t}.known_limits`,(o,a)=>Sn(o,`${t}.known_limits[${a}]`)),known_limits_truncated:ec(r.known_limits_truncated,`${t}.known_limits_truncated`),review:i?{status:Ot(i.status,["passed"],`${t}.review.status`),summary:Sn(i.summary,`${t}.review.summary`),reviewer_execution_ref:mt(i.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:tc(r.submitted_at,`${t}.submitted_at`),...r.raw_input_ref!==void 0?{raw_input_ref:mt(r.raw_input_ref,`${t}.raw_input_ref`)}:{}}}function Ez(e,t){let r=`Native blockers[${t}]`,n=Qt(e,r);Nr(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=Rm(n.acceptance_ids,`${r}.acceptance_ids`);return Wa(i,`${r}.acceptance_ids`),{owner:Ot(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Sn(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:Ot(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Cz(e,t){let r=`Native verification.checks[${t}]`,n=Qt(e,r);return Nr(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:mt(n.id,`${r}.id`),name:Sn(n.name,`${r}.name`),argv_display:Nn(n.argv_display,`${r}.argv_display`,(i,o)=>Sn(i,`${r}.argv_display[${o}]`)),argv_truncated:ec(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:Am(n.cwd_ref,`${r}.cwd_ref`,!0),status:Ot(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:kz(n.exit_code,`${r}.exit_code`),duration_ms:pt(n.duration_ms,`${r}.duration_ms`)}}function _z(e){let t="Native verification",r=Qt(e,t);Nr(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","reported_checks","summary","risks","risks_truncated","completed_at"]),t);let n=Nn(r.checks,`${t}.checks`,Cz);Wa(n.map(o=>o.id),`${t}.checks IDs`);let i=mt(r.identity_provider,`${t}.identity_provider`);return{candidate_id:mt(r.candidate_id,`${t}.candidate_id`),identity_provider:i,verifier_execution_ref:mt(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:pt(r.iteration,`${t}.iteration`,1),attempt:pt(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":Ot(r.assurance,["host-attested","self-reviewed","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Ot(r.verdict,ea,`${t}.verdict`),checks:n,...r.reported_checks===void 0?{}:{reported_checks:Nn(r.reported_checks,`${t}.reported_checks`,kb)},summary:Sn(r.summary,`${t}.summary`),risks:Nn(r.risks,`${t}.risks`,(o,a)=>Sn(o,`${t}.risks[${a}]`)),risks_truncated:ec(r.risks_truncated,`${t}.risks_truncated`),completed_at:tc(r.completed_at,`${t}.completed_at`)}}function bO(e,t){let r=`Native history[${t}]`,n=Qt(e,r);Nr(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=Rm(n.unresolved_ids,`${r}.unresolved_ids`);return Wa(i,`${r}.unresolved_ids`),{goal_cycle:pt(n.goal_cycle,`${r}.goal_cycle`,1),iteration:pt(n.iteration,`${r}.iteration`),attempt:pt(n.attempt,`${r}.attempt`),outcome:Ot(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:Sn(n.summary,`${r}.summary`),completed_at:tc(n.completed_at,`${r}.completed_at`)}}function Iz(e){let t="Native history_overflow.outcome_counts",r=Qt(e,t),n=["pass","fail","blocked","execution-error","recovery"];return Nr(r,new Set(n),t),{pass:pt(r.pass,`${t}.pass`),fail:pt(r.fail,`${t}.fail`),blocked:pt(r.blocked,`${t}.blocked`),"execution-error":pt(r["execution-error"],`${t}.execution-error`),recovery:pt(r.recovery,`${t}.recovery`)}}function xz(e){let t="Native history_overflow",r=Qt(e,t);Nr(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let n=pt(r.dropped_entries,`${t}.dropped_entries`),i=r.first_dropped_at===null?null:tc(r.first_dropped_at,`${t}.first_dropped_at`),o=r.last_dropped_at===null?null:tc(r.last_dropped_at,`${t}.last_dropped_at`);if(n===0&&(i!==null||o!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(n>0&&(i===null||o===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let a=Iz(r.outcome_counts);if(Object.values(a).reduce((c,l)=>c+l,0)!==n)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:n,first_dropped_at:i,last_dropped_at:o,outcome_counts:a}}function Pz(e){if(e.verifier_action){if(km(e.verifier_action),e.verifier_action.runId!==e.name)throw new Error("Native Verifier action belongs to another change");if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"&&["pending","running","unknown"].includes(e.verifier_action.status)&&!hb(e,e.verifier_action))throw new Error("Native Verifier action is stale for the current candidate or attempt")}let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&Ul(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let n of r.acceptance_ids)if(!t.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");let r=["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance);if(e.verification.assurance!=="self-reviewed"&&r!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="self-reviewed"&&e.verification.verifier_execution_ref!==e.builder_handoff.builder_execution_ref)throw new Error("Native self-reviewed verification must use the Builder session");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.assurance!=="self-reviewed"&&e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let n=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,i=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Oz(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(n=>n.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function L(e){let t=Qt(e,"Native portable state");if(Nr(t,wz,"Native portable state"),t.schema!==Xs)throw new Error(`Native portable state schema must be ${Xs}`);let r=mt(t.name,"Native state name");if(!mz.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let n=Nn(t.spec_changes,"Native spec_changes",bz);Wa(n.map(s=>s.capability),"Native spec change capabilities");let i=Nn(t.acceptance,"Native acceptance",Nz);Wa(i.map(s=>s.id),"Native acceptance IDs");let o=Nn(t.history,"Native history",bO);if(o.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let a={schema:Xs,name:r,language:Ot(t.language,["en","zh-CN"],"Native state language"),phase:Ot(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Ot(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:pt(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:kO(t.shape_confirmation_hash,"Native Shape confirmation hash")},...(t.children_contract_ref??t.children_contract_hash)===void 0?{}:{children_contract_ref:mt(t.children_contract_ref??t.children_contract_hash,"Native children approval reference")},...t.children_contract_ref!==void 0&&t.children_contract_hash!==void 0?{children_contract_hash:mt(t.children_contract_hash,"Legacy children approval reference")}:{},...t.children_contract===void 0?{}:{children_contract:yz(t.children_contract,i)},...t.coordination_mode===void 0?{}:{coordination_mode:Ot(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:n,workspace:Az(t.workspace),loop:Rz(t.loop),acceptance:i,builder_handoff:t.builder_handoff===null?null:Sz(t.builder_handoff),...t.verifier_action===void 0?{}:{verifier_action:C_(t.verifier_action)},blockers:Nn(t.blockers,"Native blockers",Ez),verification:t.verification===null?null:_z(t.verification),history:o,history_overflow:xz(t.history_overflow),verification_result:Ot(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Ot(t.verification_report,["verification.md"],"Native verification_report"),archived:ec(t.archived,"Native archived"),created_at:tc(t.created_at,"Native created_at")};return Pz(a),Oz(a),a}function rc(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return L({schema:Xs,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Bu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function tn(e,t){let r=L(e),n=bO(t,r.history.length),i=[...r.history,n],o={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;i.length>50;){let a=i.shift();o.dropped_entries+=1,o.first_dropped_at??=a.completed_at,o.last_dropped_at=a.completed_at,o.outcome_counts[a.outcome]+=1}return L({...r,history:i,history_overflow:o})}async function Gt(e){let t=await pz.readFile(e,"utf8");return L(Do(t,"Native portable state"))}async function bb(e,t,r={}){let n=L(t);await et(e,(0,yO.stringify)(n),r)}async function Tz(e,t){let r=bm.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),o=r.then(()=>i);bm.set(e,o),await r;try{return await t()}finally{n(),bm.get(e)===o&&bm.delete(e)}}async function Ab(e){return Tz(e.file,async()=>{let t=pt(e.expectedStateVersion,"Native expected state version",1),r=L(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let n=await Gt(e.file);if(n.state_version===r.state_version&&JSON.stringify(n)===JSON.stringify(r))return n;if(n.state_version!==t)throw new Wu(t,n.state_version);return await bb(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let i=await Gt(e.file);if(i.state_version!==t)throw new Wu(t,i.state_version)}}),r})}var yO,mz,hz,gz,vz,wz,Wu,bm,Ae=x(()=>{"use strict";Ii();fp();vr();ta();yO=tr(jr(),1);ha();ju();$u();bt();Zs();mz=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hz=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gz=/^A[1-9][0-9]*$/u,vz=/^[a-f0-9]{64}$/u,wz=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","shape_semantic_snapshot","children_contract_ref","children_contract_hash","children_contract","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","verifier_action","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at","run_checkpoint","archive_receipt","application_checkpoint"]);Wu=class extends Error{constructor(r,n){super(`Native state version conflict: expected ${r}, got ${n}`);this.expectedStateVersion=r;this.actualStateVersion=n;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};bm=new Map});import{promises as AO}from"node:fs";import Lu from"node:path";function RO(e,t){return Lu.join(Mw(e,t),"supervisor")}function Nm(e,t){return Lu.join(RO(e,t),"state.json")}function NO(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==rl)throw new Error(`Native Supervisor state schema must be ${rl}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[i,o]of Object.entries(t.integration))if(i!=="checkExecution"&&(typeof o!="string"||o.length===0))throw new Error(`Native Supervisor integration field ${i} is invalid`);if(hs(t.integration.targetCommit,"Native Supervisor target commit"),hs(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let i=t.finalVerification.layers;if(!["complete","incomplete"].includes(i.childVerification)||!["complete","incomplete"].includes(i.parentIntegration)||!Array.isArray(i.parentChecks)||!i.parentChecks.every(o=>typeof o=="string")||!Array.isArray(i.notRerun)||!i.notRerun.every(o=>typeof o=="string")||!Array.isArray(i.incomplete)||!i.incomplete.every(o=>typeof o=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let i of t.history)if(!i||typeof i!="object"||typeof i.kind!="string"||typeof i.summary!="string"||typeof i.at!="string"||i.child!==null&&typeof i.child!="string"||i.runId!==null&&typeof i.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,n=new Set;for(let i of t.children){if(!i||typeof i!="object"||typeof i.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(i.name))throw new Error(`Native Supervisor child ${i.name} is duplicated`);if(r.add(i.name),!Array.isArray(i.dependsOn)||!i.dependsOn.every(o=>typeof o=="string"))throw new Error(`Native Supervisor child ${i.name} dependencies are invalid`);if(typeof i.summary!="string"&&i.summary!==null)throw new Error(`Native Supervisor child ${i.name} summary is invalid`);if(i.builderFailureCount!==void 0&&(!Number.isSafeInteger(i.builderFailureCount)||i.builderFailureCount<0))throw new Error(`Native Supervisor child ${i.name} Builder failure count is invalid`);if(i.projectRoot!==void 0&&i.projectRoot!==null&&(typeof i.projectRoot!="string"||i.projectRoot.length===0))throw new Error(`Native Supervisor child ${i.name} projectRoot is invalid`);for(let[o,a]of[["base",i.baseCommit],["candidate",i.candidateCommit],["verified",i.verifiedCommit],["integration",i.integrationCommit]])a!==null&&hs(a,`Native Supervisor child ${i.name} ${o} commit`);if(!Array.isArray(i.checks)||!Array.isArray(i.verification?.checks??[]))throw new Error(`Native Supervisor child ${i.name} evidence is invalid`);if(i.task!==null){if(!i.task||typeof i.task!="object")throw new Error(`Native Supervisor child ${i.name} task is invalid`);if(!["builder","verifier"].includes(i.task.role)||i.task.child!==i.name||typeof i.task.projectRoot!="string"||i.task.projectRoot.length===0||typeof i.task.runId!="string"||i.task.runId.length===0)throw new Error(`Native Supervisor child ${i.name} task identity is invalid`);if(hs(i.task.baseCommit,`Native Supervisor child ${i.name} task base commit`),n.has(i.task.runId))throw new Error(`Native Supervisor task runId ${i.task.runId} is duplicated`);if(n.add(i.task.runId),i.task.role==="verifier"&&i.task.baseCommit!==i.candidateCommit)throw new Error(`Native Supervisor child ${i.name} verifier base commit is invalid`);if(i.task.projectRoot!==i.projectRoot)throw new Error(`Native Supervisor child ${i.name} task projectRoot is invalid`);if(i.task.role==="builder"&&i.status!=="active"||i.task.role==="verifier"&&!["active","needs-reverify"].includes(i.status))throw new Error(`Native Supervisor child ${i.name} task status is invalid`)}}}async function En(e,t,r={}){try{let n=await AO.readFile(Nm(e,t),"utf8"),i=JSON.parse(n);if(i&&typeof i=="object"&&Array.isArray(i.children))for(let a of i.children)a.contractRef===void 0&&typeof a.contractHash=="string"&&(a.contractRef=a.contractHash),a.task&&a.task.contractRef===void 0&&typeof a.task.contractHash=="string"&&(a.task.contractRef=a.task.contractHash);if(i&&typeof i=="object"){let a=i;if(a.integration&&delete a.integration.checkExecution,Array.isArray(a.children))for(let s of a.children)s.task&&(delete s.task.checkExecution,delete s.task.checksReason)}if(NO(i),i.children.some(a=>!a.acceptanceScope||a.task&&!a.task.acceptance))try{let a=e;if(!a.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(Ae(),Rb)),c=await s(Lu.join(a.changesDir,t,"comet-state.yaml")),l=await dn({changeDir:Lu.join(a.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:un(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of i.children)l.contract.children.some(({name:f})=>f===u.name)&&(u.acceptanceScope=Ai(l.contract,u.name),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractRef=u.contractRef,u.task.verificationBoundary="child-scope-parent-reverifies-all"))}catch(a){if(!r.diagnostics)throw a}let o=e;if(o.changesDir)try{let{readNativePortableState:a}=await Promise.resolve().then(()=>(Ae(),Rb)),s=await a(Lu.join(o.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(i.integration.targetBranch=s.workspace.change_branch)}catch(a){if(a.code!=="ENOENT")throw a}return i}catch(n){if(n.code==="ENOENT")return null;throw n}}async function La(e,t){NO(t),await AO.mkdir(e.changesRuntimeDir,{recursive:!0}),await Pr(Nm(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}var Wi=x(()=>{"use strict";bt();vr();Ke();Yn()});import{randomUUID as jz}from"node:crypto";import{promises as qu,lstatSync as Nb,readFileSync as $z,realpathSync as Dz}from"node:fs";import ui from"node:path";function ic(e){try{if(q(e,["ls-files","--",nc]))return!1;let t=ui.join(e,nc),r=Nb(t);if(!r.isFile()||r.isSymbolicLink())return!1;let n=Ue(e),i=Sb(e);for(let s of[n,ui.dirname(i)]){let c=Nb(s);if(c.isSymbolicLink()||!c.isDirectory())return!1}let o=Nb(i);if(!o.isFile()||o.isSymbolicLink()||Dz(i)!==ui.resolve(i))return!1;let a=JSON.parse($z(i,"utf8"));return a.created===!0||typeof a.hash=="string"}catch{return!1}}async function SO(e){let t=ui.join(e,nc);try{await qu.access(t)}catch(i){if(i.code==="ENOENT")return;throw i}let r=await $n(e),n=Sb(e);await qu.mkdir(ui.dirname(n),{recursive:!0}),await Pr(n,{created:!0},{containedRoot:r})}function di(e,t=[]){return eo(e).every(r=>t.some(n=>r===n||r.startsWith(`${n}/`))||r===nc&&ic(e))}async function Vu(e){if(!ic(e))return;let t=await $n(e),r="native/preserved-configs/"+jz()+".yaml",n=ui.join(t,r);await qu.mkdir(ui.dirname(n),{recursive:!0}),await qu.copyFile(ui.join(e,nc),n),await Pr(Sb(e),{created:!0,preservedRef:r},{containedRoot:t}),await qu.unlink(ui.join(e,nc))}var nc,Sb,oc=x(()=>{"use strict";yr();rr();bt();nc=".comet/config.yaml",Sb=e=>ui.join(Ue(e),"native","workspace-config.json")});var ac,qa,Sm,fi,sc=x(()=>{"use strict";ac=class extends Error{constructor(r,n,i){super(`Native change ${r} revision conflict: expected ${n}, actual ${i}`);this.change=r;this.expectedRevision=n;this.actualRevision=i;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},qa=class extends Error{constructor(r,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Sm=class extends Error{constructor(r,n,i,o){super(`Canonical spec conflict for ${r}: expected ${n??"(missing)"}, actual ${i??"(missing)"}`);this.capability=r;this.expectedHash=n;this.actualHash=i;this.canonicalPath=o;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},fi=class extends Error{constructor(r,n,i){super(r,i);this.preparation=n;this.name="NativeWorkspacePreparationError"}preparation}});import{createHash as Bz}from"crypto";function Eb(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Wz(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Em(e,t={}){return(await Fu(e,t)).document}async function EO(e){try{return(await De(e,Mu,Ll,{label:Mu})).bytes}catch(t){if(Wz(t))return null;throw t}}function CO(e){return e?{exists:!0,sha256:Bz("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Cm(e){return CO(await EO(e))}async function Fu(e,t={}){let r=await EO(e);return{source:r?.toString("utf8")??null,document:r?Ps(r.toString("utf8"),t):null,identity:CO(r)}}async function Cb(e){return(await Em(e))?.config??null}var Mu,cc=x(()=>{"use strict";Ci();st();Mu=".comet/config.yaml"});var Fte,_b=x(()=>{"use strict";ci();cc();st();Fte=Number.MAX_SAFE_INTEGER});async function Ib(e,t){if(!t)return;let r=await Cm(e);if(!Eb(r,t))throw new Error("Project config changed before commit; rerun the operation")}var xb=x(()=>{"use strict";ci();Ci();cc();st();_b()});import Vz from"path";function Mz(e="docs",t="en"){return cp(e,t)}async function Fe(e){let t=(await Em(e))?.config??null;return t?.native?t:null}async function Qu(e){let t=await Fe(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function _m(e,t,r={}){let n=await Fu(e,{allowPartialProject:!0}),i=Ml(n.document?.value??{},t),o=Vz.join(e,...Ql.split("/"));await et(o,Vl(i,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Ib(e,n.identity)}})}async function _O(e){let t=await lp(e.startPath),r=await Fe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ql} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?up(e.explicitArtifactRoot):void 0;if(r&&n&&n!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${n}`);let i=r??Mz(n??"docs"),o=await he(t,i.native.artifact_root,{change:e.change});return{config:i,paths:o,configured:r!==null}}var Hu,Dt=x(()=>{"use strict";Ci();cc();xb();bt();Ke();Hu=ql});import{promises as Uu}from"node:fs";import Hr from"node:path";function OO(e,t){let r=Hr.relative(e,t);return r===""||!Hr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Hr.sep}`)}function IO(e){let t={...e.native};return delete t.max_parallel_children,JSON.stringify(t)}async function Im(e,t){let r=await Fe(e);if(r&&t){if(IO(r)!==IO(t))throw new Error(`Native worktree configuration differs from the source project: ${Hr.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await _m(e,t),await SO(e),!0):!1}async function xO(e,t){let r=["/.comet/runtime"];if(t&&OO(e,t)){let l=Hr.relative(e,t).replaceAll("\\","/");r.push(`/${l.replace(/\/+$/u,"")}/`)}let n=q(e,["rev-parse","--git-common-dir"]),i=Hr.resolve(e,n),o=Hr.join(i,"info","exclude"),a="";try{a=await Uu.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}let s=r.filter(l=>!a.split(/\r?\n/u).includes(l));if(s.length===0)return!1;await Uu.mkdir(Hr.dirname(o),{recursive:!0});let c=a.length===0||a.endsWith(`
207
+ `)?"":`
208
+ `;return await Uu.appendFile(o,`${c}${s.join(`
209
+ `)}
210
+ `,"utf8"),!0}function Fz(e,t,r){let n=Hr.resolve(e,r??Hr.join(".worktrees",t)),i=Hr.resolve(e,q(e,["rev-parse","--git-common-dir"]));if(OO(i,n))throw new Error("Native worktree path cannot be inside the Git common directory");if(Mt(e).some(o=>we(o,n)))throw new Error(`Native worktree path is already registered: ${n}`);return n}async function Hz(e){try{throw await Uu.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function PO(e){try{return await Uu.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Pb(e){let t=Hr.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let h=de(t);if(h.isGitWorktree&&h.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:h.currentBranch,targetBranch:h.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:h.currentBranch,targetBranch:h.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=de(t);if(!r.isGitWorktree||r.currentBranch===null||r.primaryWorktreeRoot===null||r.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Vg(t,n);let i=r.currentBranch===n,o=e.targetBranch??(i?void 0:r.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Vg(t,o),!zc(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);let a=await xO(r.primaryWorktreeRoot);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!i){if(!Zo(t))throw new Error("Native branch isolation requires a clean current working directory");if(zc(t,n))throw new Error(`Native change branch already exists: ${n}`);q(t,["switch","-c",n,o]),h=!0}let p;try{p=await Im(t,e.sourceConfig)}catch(g){throw new fi(`Native branch preparation is incomplete: ${g.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:p}}}if(i){if(!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?Hr.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!we(h,r.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${r.currentWorktreeRoot}`);let p;try{p=await Im(t,e.sourceConfig)}catch(g){throw new fi(`Native worktree preparation is incomplete: ${g.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:p}}}let s=Ld(r.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await PO(c.root)){let h=e.worktreePath?Hr.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!we(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let p;try{p=await Im(c.root,e.sourceConfig)}catch(g){throw new fi(`Native worktree preparation is incomplete: ${g.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:p}}}c&&!await PO(c.root)&&(q(r.primaryWorktreeRoot,["worktree","prune"]),s=Ld(r.primaryWorktreeRoot));let l=zc(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=Fz(r.primaryWorktreeRoot,e.name,e.worktreePath);await Hz(u);let f=await xO(r.primaryWorktreeRoot,u),m={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a||f,configInitialized:!1};try{q(r.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),m.createdBranch=!l,m.createdWorktree=!0,m.configInitialized=await Im(u,e.sourceConfig)}catch(h){throw new fi(`Native worktree preparation is incomplete: ${h.message}`,m,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:m}}var TO=x(()=>{"use strict";sc();sc();rr();Ze();Dt();oc()});import Va from"node:path";function wt(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function Rt(e,t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native Supervisor parent name: ${t}`);return Dg(e,".worktrees",`${t}-integration`)}function Bt(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return Dg(e,".worktrees",`${t}-${r}`)}async function xm(e){let t=Va.join(".worktrees",`${e.parent}-integration`);return Pb({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:wt(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Pm(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Pb({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Va.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function Tb(e,t){try{return q(e,["show-ref","--verify","--quiet",`refs/heads/${t}`]),!0}catch{return!1}}function Uz(e,t){let r=Va.relative(Va.resolve(e),Va.resolve(t));return r===""||!Va.isAbsolute(r)&&!r.startsWith(`..${Va.sep}`)}function Ob(e){if(de(e.targetRoot).currentBranch!==e.targetBranch||ye(e.targetRoot,e.targetBranch)!==e.targetCommit)throw new Error("Native Supervisor target branch changed during cleanup")}function lc(e){Ob(e);let t=Mt(e.projectRoot);for(let r of e.candidates){if(t.some(n=>we(n,r.root))){if(Uz(r.root,process.cwd()))throw new Error(`Native Supervisor cannot clean the current worktree: ${r.root}`);if(de(r.root).currentBranch!==r.branch||!di(r.root))throw new Error(`Native Supervisor cleanup found a changed worktree: ${r.root}`)}if(Tb(e.projectRoot,r.branch))try{q(e.projectRoot,["merge-base","--is-ancestor",r.branch,e.targetCommit])}catch{throw new Error(`Native Supervisor cleanup found an unintegrated branch: ${r.branch}`)}}}function Li(e){let t=Mt(e.projectRoot);return e.candidates.every(r=>!t.some(n=>we(n,r.root))&&!Tb(e.projectRoot,r.branch))}async function uc(e){if(!Li(e)){lc(e);for(let t of e.candidates)Ob(e),Mt(e.projectRoot).some(r=>we(r,t.root))&&(await Vu(t.root),q(e.projectRoot,["worktree","remove",t.root]));for(let t of e.candidates)Ob(e),Tb(e.projectRoot,t.branch)&&q(e.targetRoot,["branch","-d",t.branch]);if(!Li(e))throw new Error("Native Supervisor cleanup did not remove every temporary worktree")}}async function dc(e,t){let r=await En(e,t.name,{diagnostics:!0});if(!r)return null;let n=de(e.projectRoot).primaryWorktreeRoot??e.projectRoot,i=Rt(n,t.name),o=wt(t.name);if(r.parent!==t.name||!we(r.integration.worktree,i)||r.integration.branch!==o||!t.workspace.change_branch)throw new Error("Native Supervisor cleanup lacks its original parent workspace");let a=r.children.map(s=>{let c=s.projectRoot??s.task?.projectRoot??s.verification?.execution?.projectRoot,l=Bt(n,t.name,s.name);if(!c||!we(c,l)||!["integrated","archived"].includes(s.status))throw new Error("Native Supervisor cleanup requires its original integrated Child workspace: "+s.name);return{root:c,branch:"comet/supervisor/"+t.name+"/"+s.name}});return a.push({root:i,branch:o}),{projectRoot:e.projectRoot,targetRoot:e.projectRoot,targetBranch:t.workspace.change_branch,targetCommit:r.integration.headCommit,candidates:a}}var Sr=x(()=>{"use strict";Ze();jN();rr();Yn();Wi();oc();TO()});import{promises as Jz}from"node:fs";import jO from"node:path";function Nt(e,t){if(!Om.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=jO.join(e.changesDir,t);if(!Br(e.changesDir,r))throw new Error("Native change path escaped");return r}function Qr(e,t){return jO.join(Nt(e,t),$O)}async function Tm(e,t){try{let r=await Jz.readFile(Qr(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ju(e,t){if(!t)return;let r=de(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function ur(e,t){return Gt(Qr(e,t))}async function qi(e){let t=e.next.verifier_action;return t&&["pending","running","unknown"].includes(t.status)&&!gb(e.next)&&(e={...e,next:{...e.next,verifier_action:Jl(t,"The Native workflow left this Verifier attempt")}}),await Ab({file:Qr(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot})}var Om,$O,Yt=x(()=>{"use strict";ha();$u();Ze();rr();Ae();Ke();Om=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$O="comet-state.yaml"});import{promises as zz}from"node:fs";import Kz from"node:path";function fc(e){return Kz.join(e,".comet","current-change.json")}function Gz(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function DO(e){return e===null||typeof e=="string"}function Yz(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!Gz(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!DO(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:jm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==jm)throw new Error(`current change selection schema must be ${jm}`);if(t.workflow!=="native"&&t.workflow!=="classic"&&t.workflow!=="application")throw new Error("current change selection workflow must be native, classic or application");if(t.workflow==="application"&&(typeof t.applicationId!="string"||!t.applicationId.trim()||t.branch!==null))throw new Error("application selection requires applicationId and a null branch");if(t.workflow!=="application"&&t.applicationId!==void 0)throw new Error("built-in selection cannot retain another application identity");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!DO(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Ur(e){let t;try{let n=fc(e),{bytes:i}=await da(n,BO,{label:"current change selection"});t=i.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...Yz(t)}}async function jb(e){await zz.rm(fc(e),{force:!0})}async function Ma(e,t,r){let n=await Ur(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==r?!1:(await jb(e),!0)}var jm,BO,Xz,Bo=x(()=>{"use strict";ti();yo();jm="comet.selection.v2",BO=Number.MAX_SAFE_INTEGER;Xz=fn("readCometCurrentSelection",e=>Ur(e))});import{promises as LO}from"node:fs";import{AsyncLocalStorage as Zz}from"node:async_hooks";import dr from"node:path";function Er(e,t,r="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!qO.test(t))throw new Error(`Invalid change name: ${t}`);return`${r==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function $m(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Change runtime owner must be a JSON object");let n=e,i=n.schema===Mn&&n.workflow===t&&n.change===r,o=n.format==="compat"&&Object.keys(n).length===4,a=n.format==="sdk"&&Object.keys(n).length===6&&n.runId===r&&(typeof n.application=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(n.application)&&!Db.includes(n.application)||(t==="native"?n.application==="native":n.application==="classic-full"||n.application==="classic-hotfix"||n.application==="classic-tweak"));if(!i||!o&&!a)throw new Error(`Invalid change runtime owner for ${t}/${r}`);return n}async function pi(e,t,r,n){let i;try{({bytes:i}=await De(e,t,Number.MAX_SAFE_INTEGER,{label:"change runtime owner"}))}catch(a){if(a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new Error(`Invalid change runtime owner JSON for ${r}/${n}`)}return $m(o,r,n)}function VO(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function MO(e,t){return Er(e,t),`change-owner-records/${e}/${t}.json`}async function Dm(e,t,r){let n;try{n=await De(e,MO(t,r),Number.MAX_SAFE_INTEGER,{label:"canonical change runtime owner",bigint:!0})}catch(o){if(o.code==="ENOENT")return null;throw o}let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.bytes))}catch{throw new Error(`Invalid canonical Runtime owner for ${t}/${r}`)}return{owner:$m(i,t,r),identity:VO(n.stat)}}async function FO(e,t,r){let n=await mm(e,"change owner bindings"),i=async s=>{try{let{stat:c}=await n.stat(Er(t,r,s));return VO(c)}catch(c){if(c.code==="ENOENT")return null;throw c}},o=await i("active"),a=await i("history");return await n.finish({allowDirectoryContentChanges:!0}),{active:o,history:a}}async function HO(e,t,r=!1){let n=await FO(e,t.workflow,t.change);if(n.active===null&&n.history===null)return;if(n.active!==null&&n.history!==null)throw new Error(`Conflicting or missing Runtime owner for ${t.workflow}/${t.change}`);let i=r?null:await Dm(e,t.workflow,t.change);if(i?.identity&&i.identity===(n.active??n.history))return;let o=MO(t.workflow,t.change);await xt(e,dr.posix.dirname(o),{label:"canonical change runtime owners"});let a=Er(t.workflow,t.change,n.active?"active":"history");try{await tO(dr.join(e,a),dr.join(e,o),{containedRoot:e})}catch(s){if(!["ENOTSUP","EOPNOTSUPP"].includes(s.code??""))throw s}}async function tK(e,t,r){let n;try{n=await Dm(e,t,r)}catch(o){if(o instanceof jt&&o.reason==="changed")return null;throw o}if(!n?.identity)return null;let i=await FO(e,t,r);return i.active===n.identity&&i.history===null||i.history===n.identity&&i.active===null?n:null}async function Bb(e){let t=Vi.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??eK(e)}async function Wb(e,t,r=!1){let n=Vi.getStore();if(n?.active&&e.every(o=>n.roots.has(o)))return t();let i={roots:new Set(e),runtimeRoots:new Map,owners:new Map,projects:new Set,active:!0};try{let o=await Vi.run(i,()=>ei(()=>r?ip(t):t())),a=QO();for(let s of a.keys())[...i.projects].some(c=>s.startsWith(c+"\0"))&&a.delete(s);for(let[s,c]of i.owners)a.set(s,c);return o}finally{i.active=!1}}async function $b(e,t,r){let n=await tK(e,t,r);return n?n.owner:Wb([e],async()=>{let i=await pi(e,Er(t,r),t,r),o=await pi(e,Er(t,r,"history"),t,r);if(i&&o)throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);return i??o})}async function Mi(e,t,r,n={}){if(Er(t,r),!n.readOnly)return Vi.run(null,()=>ei(async()=>$b(await $n(e),t,r)));let[i,o]=await Bb(e),a=dr.parse(i).root,c=(await oe(a,dr.relative(a,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await $b(i,t,r):null,l=o?await $b(o,t,r):null;if(c&&l&&JSON.stringify(Object.entries(c).sort())!==JSON.stringify(Object.entries(l).sort()))throw new Error(`Conflicting current and legacy Runtime owners for ${t}/${r}`);return c??l}async function WO(e,t,r,n={}){let i=await Mi(e,t,r,n),o=i?.format==="sdk"?i:null,a=Vi.getStore();return n.readOnly&&a?.active&&a.owners.set(UO(e,t,r),o),o}async function qe(e,t,r,n={}){if(!n.readOnly||Vi.getStore()?.active)return WO(e,t,r,n);let i=QO(),o=UO(e,t,r);if(i.has(o))return i.get(o);let a=WO(e,t,r,n).catch(s=>{throw i.get(o)===a&&i.delete(o),s});return i.set(o,a),a}async function JO(e,t,r,n=!1){Er(t,"validate");let i=r.readOnly?await Bb(e):[await $n(e)],o=async()=>{let a={active:new Set,history:new Set};for(let s of i)for(let c of["active","history"]){let l=dr.parse(s).root,u=dr.posix.dirname(Er(t,"validate",c)),f=await oe(l,dr.relative(l,dr.join(s,u)).replaceAll("\\","/"),{label:`${t} ${c} change runtime owners`,expected:"directory"});if(!f.exists)continue;let d=await LO.readdir(f.target,{withFileTypes:!0});for(let m of d){if(m.isFile()&&/^\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.json\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/u.test(m.name))continue;if(t==="classic"&&c==="active"){let p=/^([a-z][a-z0-9]*(?:-[a-z0-9]+)*)\.lock(?:\.([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(?:tmp|removed))?$/u;if(m.isFile()&&p.test(m.name)||m.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(m.name))continue}if(!m.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${m.name}`);let h=m.name.slice(0,-5);if(!m.isFile()||!qO.test(h))throw new Error(`Invalid ${t} change runtime owner entry: ${m.name}`);a[c].add(h)}}return a};return n?o():Wb(i,o)}async function nK(e,t,r){return r.readOnly?rK(e,t,r):JO(e,t,r)}async function Lb(e,t,r={}){let n=r.readOnly?await Bb(e):[await $n(e)];return Wb(n,async()=>{r.readOnly&&Vi.getStore()?.runtimeRoots.set(e,n),Vi.getStore()?.projects.add(JSON.stringify([e,t]));let i=await nK(e,t,{readOnly:r.readOnly});if(r.partition==="history")return[...i.history].filter(u=>!i.active.has(u)).sort((u,f)=>u.localeCompare(f,"en"));let a=[...r.partition==="active"?i.active:new Set([...i.active,...i.history])],s=new Array(a.length),c=0;await Promise.all(Array.from({length:Math.min(r.readOnly?8:1,a.length)},async()=>{for(;;){let u=c++;if(u>=a.length)return;let f=a[u];try{let d=await qe(e,t,f,r);if(!d&&!await Mi(e,t,f,r))throw new Error(`${t} change runtime owner disappeared: ${f}`);s[u]={status:"fulfilled",value:d?f:null}}catch(d){s[u]={status:"rejected",reason:d}}}}));let l=[];for(let u of s){if(u.status==="rejected")throw u.reason;u.value&&l.push(u.value)}return l.sort((u,f)=>u.localeCompare(f,"en"))},r.readOnly===!0)}function zu(e,t){return JSON.stringify(Object.entries(e).sort())===JSON.stringify(Object.entries(t).sort())}async function qb(e,t,r){return t_(),Vi.run(null,()=>ei(async()=>{let n=await Ei(e);return Er(t.workflow,t.change),r(n)}))}async function iK(e,t,r){let n=$m(t,t.workflow,t.change);if(n.format!=="sdk"||n.workflow!=="native"||n.application!=="native")throw new Error("Only builtin Native owners can enter or leave history");await qb(e,n,i=>zO(i,n,r))}async function oK(e,t){let r=dr.posix.dirname(t).split("/");for(let n=r.length;n>=0;n-=1){let i=dr.join(e,...r.slice(0,n)),o;try{o=await LO.open(i,"r"),await o.sync()}catch(a){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(a.code??""))throw a}finally{await o?.close()}}}async function zO(e,t,r,n=!1){let i=t,o=r==="history"?"active":"history",a=Er(t.workflow,t.change,o),s=Er(t.workflow,t.change,r),c=await pi(e,a,t.workflow,t.change),l=await pi(e,s,t.workflow,t.change);if(!c&&!l||c&&!zu(c,i)||l&&!zu(l,i))throw new Error(`Change runtime owner identity changed for ${t.workflow}/${t.change}`);l||(await xt(e,dr.posix.dirname(s),{label:"change runtime owner directory"}),await Ht(dr.join(e,s),`${JSON.stringify(i)}
211
+ `,{containedRoot:e,exclusive:!0,requireAtomicPublication:!0})),await oK(e,s),c&&await $a(dr.join(e,a),{containedRoot:e,beforeRemove:async()=>{let u=await pi(e,a,t.workflow,t.change),f=await pi(e,s,t.workflow,t.change);if(!u||!f||!zu(u,i)||!zu(f,i))throw new Error("Change runtime owner changed during partition move")}}),n||await Dm(e,t.workflow,t.change),await HO(e,t,n)}async function Vb(e,t){await iK(e,t,"history")}async function KO(e,t,r){return qb(e,{workflow:t,change:r},async n=>{let i=await pi(n,Er(t,r),t,r),o=await pi(n,Er(t,r,"history"),t,r);if(i&&o&&!zu(i,o))throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);let a=i??o;if(i&&!o&&(i.format!=="sdk"||i.application!=="native"))return i;if(!a||a.format!=="sdk"||a.workflow!=="native"||a.application!=="native")throw new Error("Only builtin Native owners can be recovered from history");return await zO(n,a,"active",!0),a})}async function GO(e,t,r={}){let n=Er(t.workflow,t.change),i=$m(t,t.workflow,t.change);return qb(e,i,async o=>{if(await pi(o,Er(t.workflow,t.change,"history"),t.workflow,t.change))throw new Error(`Change ${t.workflow}/${t.change} is in history; restore its active owner before registering`);await xt(o,dr.posix.dirname(n),{label:"change runtime owner directory"});try{await Ht(dr.join(o,...n.split("/")),`${JSON.stringify(i)}
212
+ `,{containedRoot:o,exclusive:!0,requireAtomicPublication:!0})}catch(s){if(s.code!=="EEXIST")throw s;let c=await pi(o,n,t.workflow,t.change);if(JSON.stringify(c)!==JSON.stringify(i))throw new Error(`Change ${t.workflow}/${t.change} is already bound to another Runtime`,{cause:s})}return(r.canonical||await Dm(o,t.workflow,t.change))&&await HO(o,i),i})}function Wo(e,t,r={}){return GO(e,t,r)}function Mb(e,t){return GO(e,t)}var Mn,Db,eK,qO,Vi,QO,UO,rK,Xt=x(()=>{"use strict";yr();ti();ci();yo();st();yr();Mn="comet.change-owner.v1",Db=["native","classic-full","classic-hotfix","classic-tweak"],eK=fn("changeOwnerRuntimeRoots",e=>Dw(e)),qO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;Vi=new Zz,QO=Si("verifiedOwnerBatchResults",()=>new Map),UO=(e,t,r)=>`${JSON.stringify([e,t])}\0${r}`;rK=fn("changeOwnerPartitions",JO)});var eT={};Dd(eT,{listNativeSdkBuildPeers:()=>sK,nativeCurrentShapeActions:()=>XO,readNativeBuildWorkspace:()=>Lo,transferFile:()=>ZO,usesNativeSharedPlanning:()=>Fb});import{promises as aK}from"node:fs";import YO from"node:path";function Fb(e){return([...e.actions].reverse().find(r=>["shape.prepare","shape.revalidate"].includes(r.stepId))?.executionOrigin?.workflow.version??e.workflow.version)==="4"&&e.state.workspace.change_branch!==null}function XO(e){let t=[...e.actions].reverse().find(r=>["shape.prepare","shape.revalidate"].includes(r.stepId));return e.actions.slice(t?e.actions.indexOf(t)+1:0)}async function ZO(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Invalid Native change name");return YO.join(r??await $n(e),"native-build-workspaces",`${t}.json`)}async function Lo(e,t,r){try{return JSON.parse(await aK.readFile(await ZO(e,t,r),"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async function sK(e,t){let r=await $n(e),n=vt({singleWriter:!0,rootDir:YO.join(r,"sdk-runs","native")}),i=await n.read(t);if(!i||!Fb(i))return[];let o=[],a=de(e);for(let s of await Lb(e,"native",{readOnly:!0,partition:"active"})){if(s===t||await Lo(e,s))continue;let c=await n.read(s);if(!c||["completed","cancelled"].includes(c.status))continue;let l=c.state.workspace;l.change_branch!==null&&l.change_branch!==a.currentBranch||l.isolation==="worktree"&&!a.isSecondaryWorktree||o.push(s)}return o}var pc=x(()=>{"use strict";Me();Xt();Ze();yr()});var Hb=x(()=>{"use strict"});var tT=x(()=>{"use strict";st();ti();Me();Xt();yr();Hb()});import{promises as rT}from"node:fs";import lK from"node:path";function Fa(e){throw new R("STORE_INDEX_CORRUPT",e)}async function mc(e,t){let r=await oe(e,`applications/${t}`,{expected:"directory",label:"应用 Store 身份"});if(!r.exists)return null;let n=await rT.lstat(r.target,{bigint:!0});return`${n.dev}:${n.ino}:${n.birthtimeNs}`}async function Ku(e){if(!(await oe(e,Qb,{expected:"file",label:"工作区应用成员清单"})).exists)return null;try{let{checksum:t,...r}=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await De(e,Qb,Number.MAX_SAFE_INTEGER,{label:"工作区应用成员清单"})).bytes));return(r.schema!==nT||!Array.isArray(r.applications)||!r.applications.every(Ub)||new Set(r.applications).size!==r.applications.length||!r.identities||typeof r.identities!="object"||Array.isArray(r.identities)||!r.claims||typeof r.claims!="object"||Array.isArray(r.claims)||Object.keys(r.identities).length!==r.applications.length||Object.keys(r.claims).length!==r.applications.length||r.applications.some(n=>typeof r.identities[n]!="string"||!Array.isArray(r.claims[n])||r.claims[n].some(i=>!i||typeof i.runId!="string"||typeof i.applicationContentHash!="string"||typeof i.actionId!="string"||!Number.isSafeInteger(i.attempt)||typeof i.inputHash!="string"||i.claimToken!==null&&typeof i.claimToken!="string"))||j(r)!==t)&&Fa("工作区应用成员清单损坏"),r}catch(t){return Fa(`工作区应用成员清单无法读取:${t instanceof Error?t.message:String(t)}`)}}async function zb(e,t){await Ht(lK.join(e,Qb),JSON.stringify({...t,checksum:j(t)})+`
213
+ `,{containedRoot:e,requireAtomicPublication:!0})}async function iT(e,t,r,n=!1){let i=await xt(e,"applications",{label:"工作区应用 Store"}),o=await rT.readdir(i,{withFileTypes:!0});!n&&o.some(u=>!Ub(u.name)||!u.isDirectory())&&Fa("工作区应用分区无法确认;请保留现场并检查,不能忽略可能仍占用资源的应用");let a=o.filter(u=>Ub(u.name)&&u.isDirectory()).map(u=>u.name).sort(),s=await Ku(e),c=s??{schema:nT,applications:[],identities:{},claims:{}};for(let u of c.applications)n||await mc(e,u)!==c.identities[u]&&Fa(`已登记应用 ${u} 的 Store 目录缺失或身份改变;请恢复原目录或完整的 portable checkpoint`);a.includes(t)||(await xt(e,`applications/${t}`,{label:"当前应用 Store"}),a.push(t),a.sort());let l=!s;for(let u of a)c.applications.includes(u)||(c.claims[u]=await r(u),c.identities[u]=await mc(e,u),c.applications.push(u),l=!0);return l&&(c.applications.sort(),await zb(e,c)),c.applications}async function Kb(e,t,r,n=!1){if(!r.length)return;let i=await Ku(e);(!i||!n&&await mc(e,t)!==i.identities[t])&&Fa("领取前必须确认工作区应用成员身份");for(let o of r)i.claims[t].some(a=>Jb(a,o))||i.claims[t].push(o);await zb(e,i)}async function oT(e,t,r,n){let i=await Ku(e);if(!(!i||await mc(e,t)===i.identities[t]))for(let o of i.claims[t]??[])o.runId===r&&!n.some(a=>Jb(o,a))&&Fa(`portable checkpoint 缺少原执行身份:${r} / ${o.actionId};必须保留未知执行并核对停止事实`)}async function Gb(e,t,r,n=!1){let i=await Ku(e);if(!i||!i.applications.includes(t))return;let o=await mc(e,t),a=await r(t);if(o!==i.identities[t]){if((!n||!o)&&Fa("工作区应用 Store 身份已改变"),i.claims[t].some(s=>!a.some(c=>Jb(s,c))))return;i.identities[t]=o}i.claims[t]=a,await zb(e,i)}async function aT(e,t){let r=await Ku(e);if(!r?.applications.includes(t))return!1;try{return await mc(e,t)===r.identities[t]}catch{return!1}}var Qb,nT,Ub,Jb,sT=x(()=>{"use strict";Me();ci();st();Qb="application-scope-locks/workspace-applications.json",nT="comet.workspace-applications.v1",Ub=e=>typeof e=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e);Jb=(e,t)=>e.applicationContentHash===t.applicationContentHash&&e.runId===t.runId&&e.actionId===t.actionId&&e.attempt===t.attempt&&e.inputHash===t.inputHash&&e.claimToken===t.claimToken});function Yb(e,t="@"){if(!_e)return Xb.then(()=>Yb(e,t));let r=e.length+1,n=(_e.__heap_base.value||_e.__heap_base)+4*r-_e.memory.buffer.byteLength;n>0&&_e.memory.grow(Math.ceil(n/65536));let i=_e.sa(r-1);if(typeof Buffer<"u"?Buffer.from(_e.memory.buffer,i,2*(r-1)).write(e,"utf16le"):(uK?fK:dK)(e,new Uint16Array(_e.memory.buffer,i,r)),!_e.parse())throw Object.assign(new Error(`Parse error ${t}:${e.slice(0,_e.e()).split(`
214
+ `).length}:${_e.e()-e.lastIndexOf(`
215
+ `,_e.e()-1)}`),{idx:_e.e()});let o=[],a=[];for(;_e.ri();){let l=_e.is(),u=_e.ie(),f=_e.it(),d=_e.ai(),m=_e.id(),h=_e.ss(),p=_e.se(),g;_e.ip()&&(g=s(e.slice(m===-1?l-1:l,m===-1?u+1:u)));let v=null;for(v=[],_e.rsa();_e.ra();){let w=_e.aks(),y=_e.ake(),b=_e.avs(),N=_e.ave();v.push([c(e.slice(w,y)),c(e.slice(b,N))])}v.length===0&&(v=null),o.push({n:g,t:f,s:l,e:u,ss:h,se:p,d:m,a:d,at:v})}for(;_e.re();){let l=_e.es(),u=_e.ee(),f=_e.els(),d=_e.ele(),m=f<0?void 0:c(e.slice(f,d)),h=c(e.slice(l,u));a.push({s:l,e:u,ls:f,le:d,ss:_e.ess(),n:h,ln:m})}function s(l){try{return(0,eval)(l)}catch{}}function c(l){if(!l)return l;let u=l[0];return(u==='"'||u==="'")&&s(l)||l}return[o,a,!!_e.f(),!!_e.ms()]}function dK(e,t){let r=e.length,n=0;for(;n<r;){let i=e.charCodeAt(n);t[n++]=(255&i)<<8|i>>>8}}function fK(e,t){let r=e.length,n=0;for(;n<r;)t[n]=e.charCodeAt(n++)}var gne,uK,_e,pK,Xb,cT=x(()=>{"use strict";gne=(function(e){return e[e.Static=1]="Static",e[e.Dynamic=2]="Dynamic",e[e.ImportMeta=3]="ImportMeta",e[e.StaticSourcePhase=4]="StaticSourcePhase",e[e.DynamicSourcePhase=5]="DynamicSourcePhase",e[e.StaticDeferPhase=6]="StaticDeferPhase",e[e.DynamicDeferPhase=7]="DynamicDeferPhase",e})({}),uK=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;pK=()=>{return e="AGFzbQEAAAABKwhgAAF/YAF/AX9gAABgAn9/AX9gBH9/f38AYAN/f38Bf2ABfwBgA39/fwADPj0CAgEEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgABBQICAgYBAQYBAQEFAQEBAQECAgIBAQEDAQEHAQMDBAUBcAECAgUHAQGCAoCAAgYPAn8BQaCLBAt/AEGgiwQLB80BHgZtZW1vcnkCAAJzYQACAWUABQJpcwAGAmllAAcCc3MACAJzZQAJAml0AAoCYWkACwJpZAAMAmlwAA0CZXMADgJlZQAPA2VscwAQA2VsZQARA2VzcwASAnJpABMCcmUAFAFmABUCbXMAFgJyYQAXA2FrcwAYA2FrZQAZA2F2cwAaA2F2ZQAbA3JzYQAcBXBhcnNlAB0LX19oZWFwX2Jhc2UDAQtfaW5pdGlhbGl6ZQABGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAkHAQBBAQsBAAwBAQrZVz0oAEHYCkGAwAA2AgBB0ApBoIsENgIAQbgKQSo2AgBB1ApBgIAENgIACwQAEAALWQBB6AkgADYCACAAQQF0IgBBADsBoIsEQewJIABBoosEajYCAEHECUEANgIAQdQJQQA2AgBBzAlBADYCAEHICUEANgIAQdwJQQA2AgBB0AlBADYCAEGgiwQLuAEBAn9B7AlB7AkoAgAiBEEoajYCAAJAQdQJKAIAIgVFBEBBxAkgBDYCAAwBCyAFIAQ2AiQLQdQJIAQ2AgBB2AkgBTYCACAEIAA2AgggBEIANwIgIAQgA0EBRiIAOgAYIAQgAzYCFCAEQQA2AhAgBCACNgIEIAQgATYCACAEQQNBAUECIAAbIANBAkYiARs2AhwgBCACIAJBAmpBACAAGyABGzYCDCADQQFrQQFNBEBB8AlBAToAAAsLdwECf0HsCUHsCSgCACIEQRhqNgIAAkBB3AkoAgAiBUUEQEHICSAENgIADAELIAUgBDYCFAtB3AkgBDYCACAEIAM2AgwgBCACNgIIIAQgATYCBCAEIAA2AgBB4AkoAgAhACAEQQA2AhQgBCAANgIQQfAJQQE6AAALCABB9AkoAgALEwBBzAkoAgAoAgBBoIsEa0EBdQscAQF/QcwJKAIAKAIEIgBBoIsEa0EBdUF/IAAbCxMAQcwJKAIAKAIIQaCLBGtBAXULHAEBf0HMCSgCACgCDCIAQaCLBGtBAXVBfyAAGwsLAEHMCSgCACgCHAscAQF/QcwJKAIAKAIQIgBBoIsEa0EBdUF/IAAbCzUBAn9BfyEAAkACQAJAQcwJKAIAKAIUIgFBAWsOAgIBAAsgAUGgiwRrQQF1DwtBfiEACyAACwsAQcwJKAIALQAYCxMAQdAJKAIAKAIAQaCLBGtBAXULEwBB0AkoAgAoAgRBoIsEa0EBdQscAQF/QdAJKAIAKAIIIgBBoIsEa0EBdUF/IAAbCxwBAX9B0AkoAgAoAgwiAEGgiwRrQQF1QX8gABsLEwBB0AkoAgAoAhBBoIsEa0EBdQslAQF/QcwJQcwJKAIAIgBBJGpBxAkgABsoAgAiADYCACAAQQBHCyUBAX9B0AlB0AkoAgAiAEEUakHICSAAGygCACIANgIAIABBAEcLCABB+AktAAALCABB8AktAAALKwEBf0H8CUH8CSgCACIAQRBqQcwJKAIAQSBqIAAbKAIAIgA2AgAgAEEARwsTAEH8CSgCACgCAEGgiwRrQQF1CxMAQfwJKAIAKAIEQaCLBGtBAXULEwBB/AkoAgAoAghBoIsEa0EBdQsTAEH8CSgCACgCDEGgiwRrQQF1CwoAQfwJQQA2AgAL3g8BBn8jAEGA0ABrIgQkAEH4CUEBOgAAQYAIIQBBhApBgAg2AgBBnApBnosEIgJB6AkoAgBBAXRqIgU2AgBB8AlBADoAAEGACkEAOwEAQYIKQQA7AQBBiApBADoAAEH0CUEANgIAQeQJQQA6AABBjAogBEGAEGo2AgBBkAogBDYCAEGUCkEAOgAAA0AgACEBQZgKIAJBAmoiADYCAAJAAkACfwJAAkAgAiAFSQRAIAAvAQAiA0EJa0EFSQ0EAkACQAJAAkACQCADQeUAaw4FAQYGBgIACyADQSBGDQggA0EvRg0DIANBO0YNAgwFC0GCCi8BAA0BIAAQHkUNASACQQRqQYIIQQoQHw0BECBBmAooAgAhAEH4CS0AAA0BQYQKIAA2AgAgACIBIQIMBQsgAi8BBEHtAEcNACAAEB5FDQAgAikABkLwgLyDoI6AOlINABAhQZgKKAIAIQALQYQKIAA2AgAMBgsgAi8BBCIAQSpHBEAgAEEvRw0CECIMBQtBARAjDAQLIAAhAkEAQeQJLQAADQIaDAELQfgJQQA6AAALA0ACQEGYCiACQQJqIgA2AgACQAJAAkACQCACIAVJBEACQAJAAkACQAJAAkACQAJAAkACQAJAIAAvAQAiA0Egaw4QDwgFCAgICAUKAggIAQgIBgALAkACQAJAAkACQAJAIANB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACyADQQlrQQVJDRMgA0H7AGsOAwcMCAwLQYIKLwEADQwgABAeRQ0MIAJBBGpBgghBChAfDQwQIAwRCyACLwEEQe0ARw0LIAAQHkUNCyACKQAGQvCAvIOgjoA6Ug0LECEMEAsgAi8BBEHsAEcNCiAAEB5FDQogAkEGakGyCEEGEB8NCiACLwEMECRFDQpBlApBAToAAAwKC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBCDYCACAAIAE2AgQMDgtBggovAQAiAEUND0GCCiAAQQFrOwEADA0LQYAKLwEAIgBFDQxBggovAQAiA0UNDCADQQN0IARqQfgPaigCAEEFRw0MIAQgAEECdGpBBGsoAgAiACgCBA0MIAAgAUECajYCBEGYCiACQQRqNgIAQQEQJRogAEGYCigCACIANgIQQZgKIABBAms2AgAMDAtBggovAQAiAEUNDUGCCiAAQQFrIgM7AQBBgAovAQAiAEUNCyAEQYAQaiADQf//A3FBA3RqKAIAQQVHDQsgBCAAQQJ0akEEaygCACIDKAIERQRAIAMgAUECajYCBAsgAyACQQRqNgIMQYAKIABBAWs7AQAMCwsCQCABLwEAQSlHDQBB1AkoAgAiAEUNACAAKAIMIAFBAmpHDQBB1AlB2AkoAgAiADYCACAABEAgAEEANgIkDAELQcQJQQA2AgALQYIKQYIKLwEAIgBBAWo7AQAgBEGAEGogAEEDdGoiAEEGQQJBlAotAAAbNgIAIAAgATYCBEGUCkEAOgAADAoLQYIKLwEAIgBFDQtBggogAEEBayIAOwEAIARBgBBqIABB//8DcUEDdGooAgBBBEcNCQwICyADECYMCAsCQCACLwEEIgBBKkcEQCAAQS9HDQEQIgwKC0EBECMMCQsCQCABLwEAIgAQJwRAAkACQAJAIABBK2sOBAEKAgAKCyABQQJrLwEAQTBrQf//A3FBCkkNAwwJCyABQQJrLwEAQStGDQIMCAsgAUECay8BAEEtRg0BDAcLIABBKUcNACAEQYAQakGCCi8BAEEDdGooAgQQKA0GCwJAAkBBggovAQAiAkUgAEHmAEdyDQAgBEGAEGogAkEDdGoiA0EIaygCAEEBRw0AIAFBAmsvAQBB7wBHDQEgAUEEaxApRQ0BIANBBGsoAgBBnglBAxAqRQ0BDAcLIABB/QBHDQAgBEGAEGogAkEDdGoiAigCBBArDQYgAigCAEEGRg0GCyABECwNBUGICi0AACAAQS9GcSAAQQBHc0UNBQJAQdwJKAIAIgJFDQAgASACKAIASQ0AIAEgAigCBE0NBgsDQCABQaCLBEsEQEGECiABQQJrIgE2AgAgAS8BACIAEC1FDQELCyAAQf//A3EQLgRAA0AgAUGgiwRLBEBBhAogAUECayIBNgIAIAEvAQAQLg0BCwsgARAvDQYLQYgKQQE6AAAMBwtBggpBggovAQAiAEEBajsBACAEQYAQaiAAQQN0aiIAIAE2AgQgAEEDNgIADAULIANBMGtB//8DcUEKSSADQSByQeEAa0H//wNxQRpJcg0AAkACQCADQdwAaw4EAgEBAgALIANBJEYNAQsgA0GgAUYgA0GAAUlyDQULA0AgAC8BAiIBQSByQeEAayECAkAgAUEwa0H//wNxQQpJIAJB//8DcUEaSXINAAJAAkAgAUHcAGsOBAIBAQIACyABQSRGDQELIAFBoAFGIAFBgAFJcg0GC0GYCiAAQQJqIgA2AgAMAAsAC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBATYCACAAIAE2AgQMAwtBgAovAQBFQYIKLwEARUHkCS0AAEF/c3FxDAYLEDBBiApBADoAAAwBCxAxC0GECkGYCigCACIBNgIAC0GYCigCACECDAELCxAyQQALIQMgBEGA0ABqJAAgAw8LIAEhAAtBmAooAgAhAgwACwALFgAgAEGgiwRGBEBBAQ8LIABBAmsQMwtDAQN/AkAgAkUNAANAIAAtAAAiBCABLQAAIgVGBEAgAUEBaiEBIABBAWohACACQQFrIgINAQwCCwsgBCAFayEDCyADC9IIAQV/QZgKQZgKKAIAIgRBDGoiATYCAEHcCSgCACEDQQEQJSECAkACQAJAAkACQAJAIAFBmAooAgAiAEYEQCACEDRFDQELQeAJIAQ2AgACQAJAAkAgAkEqRwRAIAJB+wBHDQFBmAogAEECajYCAEEBECUhAkGcCigCACEBQZgKKAIAIQADQAJAIAJB//8DcSICQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlGiAAIAIQNiICQSxGBEBBmApBmAooAgBBAmo2AgBBARAlIQILIAJB/QBGDQMgAEGYCigCACIARg0IIAAgAU0NAAsMBwtBmAogAEECajYCAEEBECUaQZgKKAIAIgAgABA2GgwCC0H4CUEAOgAAAkACQAJAAkACQAJAIAJB4QBrDgwCCAQBCAMICAgICAUACyACQfYARg0EDAcLQZgKIABBDmoiBDYCAAJAAkACQAJAQQEQJUHhAGsOBgAMAgwMAQwLQZgKKAIAIgEpAAJC84Dkg+CNwDFSDQsgAS8BChAuRQ0LQZgKIAFBCmo2AgBBABAlGgtBmAooAgAiA0ECakGiCEEOEB8NCgJAIAMvARAiARAkDQAgAUEoaw4DAAsACwtBmAogA0EQajYCAEEBECUiAUEqRgRAQZgKQZgKKAIAQQJqNgIAQQEQJSEBCyABQShHDQEMCgtBmAooAgAiAykAAkLsgISDsI7AOVINCSADLwEKIgEQJEUgAUH7AEdxDQlBmAogA0EKajYCAEEBECUiAUH7AEYNCQtBmAooAgAhAyABEDUaQZgKKAIAIgEgA00NCCAAIAQgAyABEAQMCgtBmAogAEEKajYCAEEAECUaQZgKKAIAIQALQZgKIABBEGo2AgBBARAlIgBBKkYEQEGYCkGYCigCAEECajYCAEEBECUhAAsMCQsCQCAAKQACQuyAhIOwjsA5Ug0AIAAvAQoQLUUNAEGYCiAAQQpqNgIAQQEQJSEADAkLIABBBGohAAtBmAogAEEGajYCAEGcCigCACEDA0BBARAlIQBBmAooAgAiASADSw0HIAAQNyECQZgKKAIAIgAgAUYNBCACQT1GBEBBARA4IQJBmAooAgAhAAsgAkEsRw0EQZgKIABBAmo2AgAMAAsAC0HwCUEBOgAAQZgKQZgKKAIAQQJqNgIAC0EBECUhAEGYCigCACEBAkAgAEHmAEcNACABQQJqQZwIQQYQHw0AQZgKIAFBCGo2AgAgBEEBECVBABA5IANBFGpByAkgAxshAgNAIAIoAgAiAEUNAiAAQgA3AgggAEEUaiECDAALAAtBmAogAUECazYCAAsPCyAAIQEMAgsgACAEQQBBABAEQZgKIABBDGo2AgAPCxAyDwtBmAogAUECazYCAA8LQZgKKAIAIQEgABA1GiABQZgKKAIAIgAgASAAEARBmAogAEECazYCAAuKCwEKf0GYCkGYCigCACIGQQxqIgk2AgBBARAlIQBBmAooAgAhAgJAAkACQAJAAkACQAJ/IABBLkYEQEGYCiACQQJqNgIAQQEQJSIAQeQARwRAIABB8wBHBEAgAEHtAEcNB0GYCigCACIAQQJqQYwIQQYQHw0HQYQKKAIAIgEQOkUEQCABLwEAQS5GDQgLIAYgBiAAQQhqQQIQAw8LQZgKKAIAIgBBAmpBkghBChAfDQZBhAooAgAiARA6RQRAIAEvAQBBLkYNBwtBmAogAEEMajYCAEEBIQhBBSEEQQEQJSEAQQEMAgtBmAooAgAiACkAAkLlgJiD0IyAOVINBUGECigCACIBEDpFBEAgAS8BAEEuRg0GC0GYCiAAQQpqNgIAQQchBEEBIQVBARAlIQBBASEIQQIMAQsCQAJAIABB8wBHIAIgCU1yRQRAQfMAIQAgAkECakGSCEEKEB8NASACLwEMECRFDQFBmAogAkEMaiIANgIAQQEhCEEBECUhASAAQZgKKAIAIgRHBEBB5gAhACABQeYARwRAQQUhBCABIQBBAQwFC0EBIQMgBEECakGcCEEGEB8NBSAELwEIEC1FDQULQZgKIAI2AgBBByEEQQEhB0EAIQggASEAQQAMAwtBByEEQQEhByAAQeQARyACIAZBCmpNcg0BQeQAIQAgAikAAkLlgJiD0IyAOVINACACLwEKECRFDQBBmAogAkEKajYCAEEqIQBBASEFQQIhA0EBECUiAUEqRg0EQZgKIAI2AgBBACEFIAEhAEEADAILIAIhBAwCC0EACyEDIABBKEYEQEGMCigCAEGCCi8BACIFQQN0aiIAQQU2AgBBggogBUEBajsBACAAQZgKKAIAIgI2AgRBhAooAgAvAQBBLkYNBEGYCiACQQJqNgIAQQEQJSEAIAZBmAooAgAiAUEAIAIQA0HUCSgCACEDIAgEQCADIAQ2AhwLQYAKQYAKLwEAIgRBAWo7AQBBkAooAgAgBEECdGogAzYCAAJAIABBIkYgAEEnRnJFBEACQCAAQeAARw0AQZwKKAIAIQYgASEAA0AgACICIAZPDQECQAJAIABBAmoiAC8BACIHQdwAaw4FAAICAgUBCyACQQRqIQAMAQsgB0EkRw0AIAIvAQRB+wBHDQALC0GYCiABQQJrNgIADwsgABAmQZgKKAIAIQALQZgKIABBAmoiADYCAAJAAkACQEEBECVBKWsOBAECAgACC0GYCkGYCigCAEECajYCAEEBECUaIAMgADYCBEGYCigCACEAIANBAToAGCADIAA2AhAMCAtBggogBTsBACADIAA2AgRBmAooAgAhACADQQE6ABggAyAAQQJqNgIMQYAKIAQ7AQAPC0GYCkGYCigCAEECazYCAA8LIAdFIABB+wBHckUEQEGYCigCACEAQYIKLwEADQZBnAooAgAhAQNAAkACQCAAIAFJBEBBARAlIgBBIkYgAEEnRnINASAAQf0ARw0CQZgKQZgKKAIAQQJqNgIAC0EBECUhAUGYCigCACEAIAFB5gBGBEAgAEECakGcCEEGEB8NBwtBmAogAEEIajYCAEEBECUiAEEiRyAAQSdHcQ0GIAYgAEEAEDkPCyAAECYLQZgKQZgKKAIAQQJqIgA2AgAMAAsACwJAAkAgAEEnaw4EAwEBAwALIABBIkYNAgtBmAooAgAhBAsgBCAJRw0AQZgKIARBAms2AgAPCyAAQSpHIAVxDQJBggovAQANAkGYCigCACEAQZwKKAIAIQIDQCAAIAJPDQEgAC8BACIBQSdHIAFBIkdxBEBBmAogAEECaiIANgIADAEFIAYgASADEDkPCwALAAsQMgsPC0GYCkGYCigCAEECazYCAA8LQZgKIABBAms2AgALQwEDf0GYCigCACEAQZwKKAIAIQIDQAJAIABBAmohASAAIAJPDQAgASEAIAEvAQBBCmsOBAABAQABCwtBmAogATYCAAtwAQR/QZgKKAIAQQJqIQFBnAooAgAhBAJAA0AgASICQQJqIQEgAiAETw0BIAEvAQAhAwJAIABFBEAgA0EqRg0BIANBCmsOBAMCAgMCCyADQSpHDQELIAIvAQRBL0cNAAsgAkEEaiEBC0GYCiABNgIACwsAIABBn4CABBA8C30BBH9BnAooAgAhA0GYCigCACEBA0ACQAJAAkAgAS8BACICQS9GBEAgAS8BAiIBQSpHBEAgAUEvRg0CQS8PCyAAECMMAgsgAARAIAIQJA0CDAMLIAIQLg0BDAILECILQZgKQZgKKAIAIgRBAmoiATYCACADIARLDQELCyACC4YBAQR/QZgKKAIAIQFBnAooAgAhBAJAA0ACQCABIgJBAmohASACIARPDQAgAS8BACIDIABGDQIgA0HcAEcEQCADQQprDgQBAgIBAgsgAkEEaiEBIAIvAQRBDUcNASACQQZqIAEgAi8BBkEKRhshAQwBCwtBmAogATYCABAyDwtBmAogATYCAAtuAQF/AkAgAEEpRyAAQShrQf//A3FBB0lxIABBIWsiAUEFTUEAQQEgAXRBMXEbckUEQCAAQTprIgFB//8DcUElT0K/gICAoAIgAa2Ip0EBcUVyDQELQQEPCyAAQf0ARyAAQfsAa0H//wNxQQRJcQsuAQF/QQEhAQJAIABBlAlBBRAqDQAgAEGeCUEDECoNACAAQaQJQQIQKiEBCyABC28BAX8CfyAALwEAIgEQJCABQSlGciABQf0ARnJFBEBBACABQd0ARw0BGgsDQAJAIABBoIsETQ0AIAEQJEUNACAAQQJrIgAvAQAhAQwBCwtBASABQSlGIAFB3QBGciABQf0ARnINABogARA0QQFzCws+AQJ/AkAgACACQQF0IgJrIgRBAmoiAEGgiwRJDQAgACABIAIQHw0AIABBoIsERgRAQQEPCyAEEDMhAwsgAwuDAQECf0EBIQICQAJAAkACQAJAAkAgAC8BACIBQTtrDgQFBAQBAAsCQCABQeUAaw4EAwQEAgALIAFBKUYNBCABQfkARw0DIABBAmtBsAlBBhAqDwsgAEECay8BAEE9Rg8LIABBAmtBqAlBBBAqDwsgAEECa0G8CUEDECoPC0EAIQILIAILqgMBAn8CQAJAAkACQAJAAkACQAJAAkACQCAALwEAQeQAaw4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEECay8BAEHpAGsOBAAKCgEKCyAAQQRrQbgIQQIQKg8LIABBBGtBvAhBAxAqDwsCQAJAAkAgAEECay8BAEHzAGsOAwABAgoLIABBBGsvAQAiAUHhAEcEQCABQewARw0KIABBBmtB5QAQOw8LIABBBmtB4wAQOw8LIABBBGtBwghBBBAqDwsgAEEEa0HKCEEGECoPCyAAQQJrLwEAQe8ARw0GIABBBGsvAQBB5QBHDQYgAEEGay8BACIBQfAARwRAIAFB4wBHDQcgAEEIa0HWCEEGECoPCyAAQQhrQeIIQQIQKg8LIABBAmtB5ghBBBAqDwtBASECIABBAmsiAEHpABA7DQQgAEHuCEEFECoPCyAAQQJrQeQAEDsPCyAAQQJrQfgIQQcQKg8LIABBAmtBhglBBBAqDwsgAEECay8BACIBQe8ARwRAIAFB5QBHDQEgAEEEa0HuABA7DwsgAEEEa0GOCUEDECohAgsgAgs0AQF/IABBoAFGIABBCWsiAUEXTUEAQQEgAXRBn4CABHEbckUEQCAAEDQgAEEuR3EPC0EBCwsAIABBjYCABBA8C0gBAn8CQCAALwEAIgJB5QBHBEAgAkHrAEcNASAAQQJrQeYIQQQQKg8LIABBAmsvAQBB9QBHDQAgAEEEa0HKCEEGECohAQsgAQvbAQEEf0GYCigCACEAQZwKKAIAIQMDQCAAQQJqIQECQAJAIAAgA08NAAJAAkACQCABLwEAIgJB2wBrDgIBAgALIAEhACACQQprDgQCBAQCAwsCQANAAkAgAUECaiEAIAEgA08NAAJAAkAgAC8BACICQdwAaw4CAAQBCyABQQRqIQEMAgsgACEBIAJBCmsOBAABAQABCwtBmAogADYCABAyQZgKKAIAIQAMBAtBmAogADYCAAwDCyAAQQRqIQAMAgtBmAogATYCABAyDwsgAkEvRw0AC0GYCiAANgIAC94BAQR/QZgKKAIAIQBBnAooAgAhAwJAAkADQAJAIAAiAUECaiEAIAEgA08NAAJAAkACQCAALwEAIgJB3ABrDgUCBAQEAQALIAJBJEcNAyABLwEEQfsARw0DQZgKIAFBBGoiAjYCAEGMCigCAEGCCi8BACIAQQN0aiIBQQQ2AgBBggogAEEBajsBACABIAI2AgQPC0GYCiAANgIAQYIKQYIKLwEAQQFrIgE7AQBBjAooAgAgAUH//wNxQQN0aigCAEEDRw0DDAQLIAFBBGohAAwBCwtBmAogADYCAAsQMgsLMwEBf0HkCUEBOgAAQZgKKAIAIQBBmApBnAooAgBBAmo2AgBB9AkgAEGgiwRrQQF1NgIACz0BAX8Cf0EBIAAvAQAiAUEJa0H//wNxQQVJIAFBgAFyQaABRnINABpBACABEDRFDQAaIAAQOiABQS5HcgsLXgEBfwJAIABB+P8DcUEoRiAAQSFrIgFBBU1BAEEBIAF0QTFxG3JFBEAgAEE6ayIBQf//A3FBJU9Cv4CAgKADIAGtiKdBAXFFcg0BC0EBDwsgAEH7AGtB//8DcUEESQtXAQN/QZgKKAIAIQEDQAJAIABB//8DcSICECQEQCAAIQMMAQsgACEDIAIQNA0AQQAhA0GYCiABQQJqIgI2AgAgAS8BAiEAIAIhASAADQELCyADQf//A3ELpQEBBH8CQEGYCigCACIDLwEAIgVB4QBHBEAgASECIAAhBAwBC0GYCiADQQRqNgIAQQEQJSECQZgKKAIAIQQCQCACQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlIQVBmAooAgAhAwsgAyAERwRAIAQgAkEAIAAgACABRiIAG0EAIAEgABsQBAsgBQvTBAEHf0GYCigCACEBAkAgAEHf/wNxQdsARgRAIAEvAQAhBUGYCiABQQJqNgIAQf0AQd0AIAVB+wBGGyEGQQEQJSEDQZwKKAIAIQcDQAJAIAYgA0H//wNxIgJGQZgKKAIAIgEgB0tyDQACQCACQS5HDQAgAS8BAkEuRw0AIAEvAQRBLkcNAEGYCiABQQZqNgIAQQEQJRA3IQMMAgsCQAJ/AkAgBUH7AEYEQAJAIAJBIkYgAkEnRnJFBEAgAkHbAEcNAUEAEDgaQZgKQZgKKAIAQQJqNgIAIAEMBAsgAhAmQZgKQZgKKAIAQQJqNgIAIAEMAwsgASEAIANBMGtB//8DcUEJSw0BA0AgACICQQJqIQAgAi8BAiIDQTBrQf//A3FBCkkNACADQcEAayIEQR5NQQBBASAEdEG/gIGEBHEbDQAgA0HhAGsiBEEXTUEAQQEgBHRBv8CBBHEbDQACQAJAIANBK2sOBAABAAIBCyACLwEAQSByQeUARg0BCwtBmAogADYCACABDAILIAJBLEYEQEGYCiABQQJqNgIAQQEQJSEDDAULIAIQNyECDAILIAIQNRpBmAooAgALIQBBARAlIgJBOkYEQEGYCkGYCigCAEECajYCAEEBECUQNyECDAELIAAgAU0NACABIAAgASAAEAQLIAJBPUYEQEEAEDghAgtBmAooAgAhASACQSxHDQBBmAogAUECajYCAEEBECUhAwwBCwtBmAogAUECajYCAAwBCyAAEDUaQZgKKAIAIgAgAU0NACABIAAgASAAEAQLQQEQJQvgDgEMf0GECkGYCigCACIBNgIAQZAKKAIAIQpBjAooAgAhB0GcCigCACEMQYIKLwEAIQsgASIDIQUCQANAQZgKIAVBAmoiBDYCACAFIAxPBEBBACEIDAILAkACQCAELwEAIgIQLg0AAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQEGCCi8BACIGIAtHDQAgAiEIAkACQCACQSlrDgQcAQEcAAsgAkE7RiACQd0ARnIgAkH9AEZyDRkLIAAgCXFBAUcNAAJAIAJBImsODgsODg4OCxAIDg4HDg4MAAsCQCACQdsAaw4PBQ4GDg4NDg4EDgIODg4DAAsCQCACQfsAaw4DCQ4KAAsgAkEKaw4EGg0NGg0LAkAgAkEiaw4OCg0NDQ0KDwcNDQYNDQsACwJAIAJB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACwJAIAJBCmsOBBcNDRcACyACQfsAaw4DBwwIDAsgBg0MIAQQHkUNDCAFQQRqQYIIQQoQHw0MECAMEgsgBS8BBEHtAEcNCyAEEB5FDQsgBSkABkLwgLyDoI6AOlINCxAhDBELIAUvAQRB7ABHDQogBBAeRQ0KIAVBBmpBsghBBhAfDQogBS8BDBAkRQ0KQZQKQQE6AAAMCgsgByAGQQN0aiIBQQg2AgBBggogBkEBajsBACABIAM2AgQMDwsgBkUND0GCCiAGQQFrOwEADA4LIAZFDQ1BgAovAQAiAUUNDSAHIAZBA3RqQQhrKAIAQQVHDQ0gCiABQQJ0akEEaygCACIBKAIEDQ0gASADQQJqNgIEQZgKIAVBBGo2AgBBARAlGiABQZgKKAIAIgE2AhBBmAogAUECazYCAAwNCyAGRQ0NQYIKIAZBAWsiBDsBAEGACi8BACIBRQ0MIAcgBEH//wNxQQN0aigCAEEFRw0MIAogAUECdGpBBGsoAgAiBCgCBEUEQCAEIANBAmo2AgQLIAQgBUEEajYCDEGACiABQQFrOwEADAwLAkAgAy8BAEEpRw0AQdQJKAIAIgFFDQAgASgCDCADQQJqRw0AQdQJQdgJKAIAIgE2AgAgAQRAIAFBADYCJAwBC0HECUEANgIACyAHIAZBA3RqIgFBBkECQZQKLQAAGzYCAEGCCiAGQQFqOwEAIAEgAzYCBEGUCkEAOgAADAsLIAZFDQtBggogBkEBayIBOwEAIAcgAUH//wNxQQN0aigCAEEERw0KDAkLIAIQJgwJCwJAIAUvAQQiBEEqRwRAIARBL0cNARAiDAwLQQEQIwwLCwJAIAMvAQAiBRAnBEACQAJAAkAgBUEraw4EAQsCAAsLIANBAmsvAQBBMGtB//8DcUEKSQ0DDAoLIANBAmsvAQBBK0YNAgwJCyADQQJrLwEAQS1GDQEMCAsgBUEpRw0AIAcgBkEDdGooAgQQKA0HCwJAAkAgBkUgBUHmAEdyDQAgByAGQQN0aiIBQQhrKAIAQQFHDQAgA0ECay8BAEHvAEcNASADQQRrEClFDQEgAUEEaygCAEGeCUEDECpFDQEMCAsgBUH9AEcNACAHIAZBA3RqIgEoAgQQKw0HIAEoAgBBBkYNBwsgAxAsDQZBiAotAAAgBUEvRnEgBUEAR3NFDQZB3AkoAgAiAUUNBCADIAEoAgBJDQQgAyEEIAMgASgCBE0NBgwFCyAHIAZBA3RqIgEgAzYCBEGCCiAGQQFqOwEAIAFBAzYCAAwGCyACQTBrQf//A3FBCkkgAkEgckHhAGtB//8DcUEaSXINAAJAAkAgAkHcAGsOBAIBAQIACyACQSRGDQELIAJBoAFGIAJBgAFJcg0GCwNAIAQvAQIiAUEgckHhAGshCAJAIAFBMGtB//8DcUEKSSAIQf//A3FBGklyDQACQAJAIAFB3ABrDgQCAQECAAsgAUEkRg0BCyABQaABRiABQYABSXINBwtBmAogBEECaiIENgIADAALAAsgByAGQQN0aiIBQQE2AgBBggogBkEBajsBACABIAM2AgQMBAsgAyEECwNAIARBoIsESwRAIARBAmsiBC8BACIFEC1FDQELCyAFQf//A3EQLgRAA0AgBEGgiwRLBEBBhAogBEECayIENgIAIAQvAQAQLg0BCwsgBBAvDQELQYgKQQE6AAAMAgsQMEGICkEAOgAADAELEDELQYQKQZgKKAIAIgE2AgAMAQsQMgtBACEIQeQJLQAADQMCQCABIANGBEAgAEUNAUGCCi8BACALRiAJcUUNAUEBIQkgASEDQZgKKAIALwEAIghBCmsOBAUCAgUCCyACQS9GBEBBiAotAABBAXMhCQwBC0EBIQkgAkEwa0H//wNxQQpJIAJB3/8DcUHBAGtB//8DcUEaSXIgAkEkRiACQd8ARnJyIAJB/wBLcg0AIAEhAwJAAkAgAkEnaw4DAwEDAAsCQCACQd0Aaw4EAwEBAwALIAJBIkYgAkH9AEZyDQELQQAhCQsgASEDC0GYCigCACEFDAELCyACDwsgCAuvBAEHfyABQSJGIAFBJ0ZyRQRAEDIPC0GYCigCACEDIAEQJiAAIANBAmpBmAooAgBBARADIAIEQEHUCSgCAEEEQQYgAkEBRhs2AhwLQZgKQZgKKAIAQQJqNgIAQQAQJSEAQZgKKAIAIQQCQAJAIABB9wBHDQAgBC8BAkHpAEcNACAELwEEQfQARw0AIAQvAQZB6ABGDQELQZgKIARBAms2AgAPC0GYCiAEQQhqNgIAAkBBARAlQfsARwRADAELQewJKAIAIQNB1AkoAgAhBUGYCigCACIGIQBBACECA0AgAyEBQZgKIABBAmo2AgBBARAlIQBBmAooAgAhBwJAAkACQCAAQSJHBEAgAEEnRw0BQScQJgwCC0EiECYMAQsgABA1IQNBmAooAgAhAAwBC0GYCigCAEECaiEAQZgKIAA2AgBBARAlIQMLIANBOkcEQAwCC0GYCkGYCigCAEECajYCAEEBECUiA0EiRiADQSdGckUEQAwCC0GYCigCACEIIAMQJkHsCSABQRRqIgM2AgBBmAooAgAhCSABQQA2AhAgASAINgIIIAEgADYCBCABIAc2AgAgASAJQQJqIgA2AgwCQCACRQRAIAUgATYCIAwBCyACIAE2AhALQZgKIAA2AgACQEEBECUiAEEsRwRAIABB/QBGDQEMAwtBmApBmAooAgBBAmoiADYCACABIQIMAQsLIAUgBjYCECAFQZgKKAIAQQJqNgIMDwtBmAogBDYCAAstAQF/AkAgAC8BAEEuRw0AIABBAmsvAQBBLkcNACAAQQRrLwEAQS5GIQELIAELNQEBfwJAIABBoIsESQ0AIAAvAQAgAUcNACAAQaCLBEYEQEEBDwsgAEECay8BABAtIQILIAILKQEBfyAAQaABRiAAQQlrIgJBF01BAEEBIAJ0IAFxG3JFBEBBAA8LQQELC8cBAQBBgggLvwF4AHAAbwByAHQAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AbABhAHMAcwB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcw==",typeof Buffer<"u"?Buffer.from(e,"base64"):Uint8Array.from(atob(e),t=>t.charCodeAt(0));var e},Xb=WebAssembly.compile(pK()).then(WebAssembly.instantiate).then(({exports:e})=>{_e=e})});import{existsSync as mK,readFileSync as hK}from"fs";import lT from"path";import{fileURLToPath as gK}from"url";function vK(){return"0.5.4"}function uT(){return Zb===null&&(Zb=vK()),Zb}var Zb,wK,bne,dT=x(()=>{"use strict";Zb=null,wK="@rpamis/comet",bne=`https://registry.npmjs.org/${wK}/latest`});function nA(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function yT(e){Ua=e}function hc(e){let t=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=t[n];return i||(i=e(n),t[n]=i),i}}function Ie(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(i,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(fr.caret,"$1"),r=r.replace(i,a),n},getRegex:()=>new RegExp(r,t)};return n}function mi(e,t){if(t){if(fr.escapeTest.test(e))return e.replace(fr.escapeReplace,mT)}else if(fr.escapeTestNoEncode.test(e))return e.replace(fr.escapeReplaceNoEncode,mT);return e}function hT(e){try{e=encodeURI(e).replace(fr.percentDecode,"%")}catch{return null}return e}function gT(e,t){let r=e.replace(fr.findPipe,(o,a,s)=>{let c=!1,l=a;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),n=r.split(fr.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(fr.slashPipe,"|");return n}function qo(e,t,r){let n=e.length;if(n===0)return"";let i=0;for(;i<n;){let o=e.charAt(n-i-1);if(o===t&&!r)i++;else if(o!==t&&r)i++;else break}return e.slice(0,n-i)}function vT(e){let t=e.split(`
216
+ `),r=t.length-1;for(;r>=0&&fr.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
217
+ `)}function dG(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return r>0?-2:-1}function fG(e,t=0){let r=t,n="";for(let i of e)if(i===" "){let o=4-r%4;n+=" ".repeat(o),r+=o}else n+=i,r++;return n}function wT(e,t,r,n,i){let o=t.href,a=t.title||null,s=e[1].replace(i.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";n.state.inLink=!0;let l=n.state.linkEmitted,u=n.state.inRawBlock;n.state.linkEmitted=!1;let f=n.inlineTokens(s),d=n.state.linkEmitted;if(n.state.linkEmitted=l,n.state.inLink=!1,!c){if(d){n.state.inRawBlock=u;return}n.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:o,title:a,text:s,tokens:f}}function pG(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
218
+ `).map(o=>{let a=o.match(r.other.beginningSpace);if(a===null)return o;let[s]=a;return s.length>=i.length?o.slice(i.length):o}).join(`
219
+ `)}function nt(e,t){return Qa.parse(e,t)}function hG(...e){return Qa.use(...e),nt.defaults=Qa.defaults,yT(nt.defaults),nt}var Ua,Ha,yK,fr,kK,bK,AK,Xu,RK,iA,kT,bT,NK,oA,SK,aA,EK,CK,Vm,sA,_K,AT,IK,xK,PK,cA,fT,OK,TK,jK,$K,RT,DK,Fi,gc,Zu,BK,WK,NT,LK,qK,VK,ST,MK,FK,HK,QK,ET,UK,JK,zK,KK,GK,YK,XK,ZK,eG,tG,rG,nG,iG,oG,Wm,aG,CT,_T,sG,pT,lA,cG,eA,lG,Bm,Gu,uG,mT,Lm,Cr,qm,uA,Fn,Yu,mG,Qa,Rne,Nne,IT,Sne,Ene,Cne,dA=x(()=>{"use strict";Ua=nA();Ha={exec:()=>null};yK=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),fr={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:hc(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:hc(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:hc(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:hc(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:hc(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:hc(e=>new RegExp(`^ {0,${e}}>`))},kK=/^(?:[ \t]*(?:\n|$))+/,bK=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,AK=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Xu=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,RK=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,iA=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,kT=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bT=Ie(kT).replace(/bull/g,iA).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),NK=Ie(kT).replace(/bull/g,iA).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),oA=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,SK=/^[^\n]+/,aA=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,EK=Ie(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",aA).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),CK=Ie(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,iA).getRegex(),Vm="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",sA=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,_K=Ie("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",sA).replace("tag",Vm).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),AT=e=>Ie(oA).replace("hr",Xu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Vm).getRegex(),IK=AT(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),xK=AT(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),PK=Ie(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",xK).getRegex(),cA={blockquote:PK,code:bK,def:EK,fences:AK,heading:RK,hr:Xu,html:_K,lheading:bT,list:CK,newline:kK,paragraph:IK,table:Ha,text:SK},fT=Ie("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Xu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Vm).getRegex(),OK={...cA,lheading:NK,table:fT,paragraph:Ie(oA).replace("hr",Xu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",fT).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Vm).getRegex()},TK={...cA,html:Ie(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",sA).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ha,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ie(oA).replace("hr",Xu).replace("heading",` *#{1,6} *[^
220
+ ]`).replace("lheading",bT).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},jK=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,$K=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,RT=/^( {2,}|\\)\n(?!\s*$)/,DK=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Fi=/[\p{P}\p{S}]/u,gc=/[\s\p{P}\p{S}]/u,Zu=/[^\s\p{P}\p{S}]/u,BK=Ie(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,gc).getRegex(),WK=/[\p{Pi}\p{Ps}"']/u,NT=/(?!~)[\p{P}\p{S}]/u,LK=/(?!~)[\s\p{P}\p{S}]/u,qK=/(?:[^\s\p{P}\p{S}]|~)/u,VK=Ie(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",yK?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ST=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,MK=Ie(ST,"u").replace(/punct/g,Fi).getRegex(),FK=Ie(ST,"u").replace(/punct/g,NT).getRegex(),HK=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,QK=Ie(HK,"u").replace(/openQuote/g,WK).replace(/punct/g,Fi).getRegex(),ET="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",UK=Ie(ET,"gu").replace(/notPunctSpace/g,Zu).replace(/punctSpace/g,gc).replace(/punct/g,Fi).getRegex(),JK=Ie(ET,"gu").replace(/notPunctSpace/g,qK).replace(/punctSpace/g,LK).replace(/punct/g,NT).getRegex(),zK="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",KK=Ie(zK,"gu").replace(/notPunctSpace/g,Zu).replace(/punctSpace/g,gc).replace(/punct/g,Fi).getRegex(),GK=Ie("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Zu).replace(/punctSpace/g,gc).replace(/punct/g,Fi).getRegex(),YK="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",XK=Ie(YK,"gu").replace(/notPunctSpace/g,Zu).replace(/punctSpace/g,gc).replace(/punct/g,Fi).getRegex(),ZK=Ie(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Fi).getRegex(),eG="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",tG=Ie(eG,"gu").replace(/notPunctSpace/g,Zu).replace(/punctSpace/g,gc).replace(/punct/g,Fi).getRegex(),rG=Ie(/\\(punct)/,"gu").replace(/punct/g,Fi).getRegex(),nG=Ie(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),iG=Ie(sA).replace("(?:-->|$)","-->").getRegex(),oG=Ie("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",iG).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Wm=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,aG=Ie(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Wm).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),CT=Ie(/^!?\[(label)\]\[(ref)\]/).replace("label",Wm).replace("ref",aA).getRegex(),_T=Ie(/^!?\[(ref)\](?:\[\])?/).replace("ref",aA).getRegex(),sG=Ie("reflink|nolink(?!\\()","g").replace("reflink",CT).replace("nolink",_T).getRegex(),pT=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,lA={_backpedal:Ha,anyPunctuation:rG,autolink:nG,blockSkip:VK,br:RT,code:$K,del:Ha,delLDelim:Ha,delRDelim:Ha,emStrongLDelim:MK,emStrongRDelimAst:UK,emStrongRDelimUnd:GK,escape:jK,link:aG,nolink:_T,punctuation:BK,reflink:CT,reflinkSearch:sG,tag:oG,text:DK,url:Ha},cG={...lA,emStrongLDelim:QK,emStrongRDelimAst:KK,emStrongRDelimUnd:XK,link:Ie(/^!?\[(label)\]\((.*?)\)/).replace("label",Wm).getRegex(),reflink:Ie(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Wm).getRegex()},eA={...lA,emStrongRDelimAst:JK,emStrongLDelim:FK,delLDelim:ZK,delRDelim:tG,url:Ie(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",pT).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Ie(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",pT).getRegex()},lG={...eA,br:Ie(RT).replace("{2,}","*").getRegex(),text:Ie(eA.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Bm={normal:cA,gfm:OK,pedantic:TK},Gu={normal:lA,gfm:eA,breaks:lG,pedantic:cG},uG={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},mT=e=>uG[e];Lm=class{options;rules;lexer;constructor(e){this.options=e||Ua}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:vT(t[0]),n=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],n=pG(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let n=qo(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:qo(t[0],`
221
+ `),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:qo(t[0],`
222
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=qo(t[0],`
223
+ `).split(`
224
+ `),n="",i="",o=[];for(;r.length>0;){let a=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),a=!0;else if(!a)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
225
+ `),u=l.replace(this.rules.other.blockquoteSetextReplace,`
226
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
227
+ ${l}`:l,i=i?`${i}
228
+ ${u}`:u;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=f,r.length===0)break;let d=o.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let m=d,h=r.join(`
229
+ `),p=m.raw+`
230
+ `+h.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(p);o[o.length-1]=g,n=`${n}
231
+ ${h}`,i=i.substring(0,i.length-m.text.length)+g.text;break}else if(d?.type==="list"){let m=d,h=m.raw+`
232
+ `+r.join(`
233
+ `),p=this.list(h);o[o.length-1]=p,n=n.substring(0,n.length-d.raw.length)+p.raw,i=i.substring(0,i.length-m.raw.length)+p.raw,r=h.substring(o.at(-1).raw.length).split(`
234
+ `);continue}}return{type:"blockquote",raw:n,tokens:o,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let o=this.rules.other.listItemRegex(r),a=!1;for(;e;){let c=!1,l="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let f=fG(t[2].split(`
235
+ `,1)[0],t[1].length),d=e.split(`
236
+ `,1)[0],m=!f.trim(),h=0;if(this.options.pedantic?(h=2,u=f.trimStart()):m?h=t[1].length+1:(h=f.search(this.rules.other.nonSpaceChar),h=h>4?1:h,u=f.slice(h),h+=t[1].length),m&&this.rules.other.blankLine.test(d)&&(l+=d+`
237
+ `,e=e.substring(d.length+1),c=!0),!c){let p=this.rules.other.nextBulletRegex(h),g=this.rules.other.hrRegex(h),v=this.rules.other.fencesBeginRegex(h),w=this.rules.other.headingBeginRegex(h),y=this.rules.other.htmlBeginRegex(h),b=this.rules.other.blockquoteBeginRegex(h);for(;e;){let N=e.split(`
238
+ `,1)[0],A;if(d=N,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),A=d):A=d.replace(this.rules.other.tabCharGlobal," "),v.test(d)||w.test(d)||y.test(d)||b.test(d)||p.test(d)||g.test(d))break;if(A.search(this.rules.other.nonSpaceChar)>=h||!d.trim())u+=`
239
+ `+A.slice(h);else{if(m||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||v.test(f)||w.test(f)||g.test(f))break;u+=`
240
+ `+d}m=!d.trim(),l+=N+`
241
+ `,e=e.substring(N.length+1),f=A.slice(h)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(a=!0)),i.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=l}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c of i.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!i.loose){let l=c.tokens.filter(f=>f.type==="space"),u=l.length>0&&l.some(f=>this.rules.other.anyLine.test(f.raw));i.loose=u}for(let c of i.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let f={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=f.checked,i.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=f.raw+c.tokens[0].raw,c.tokens[0].text=f.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(f)):c.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):c.tokens.unshift(f)}}else c.task&&(c.task=!1)}if(i.loose)for(let c of i.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=vT(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:qo(t[0],`
242
+ `),href:n,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=gT(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
243
+ `):[],o={type:"table",raw:qo(t[0],`
244
+ `),header:[],align:[],rows:[]};if(r.length===n.length){for(let a of n)this.rules.other.tableAlignRight.test(a)?o.align.push("right"):this.rules.other.tableAlignCenter.test(a)?o.align.push("center"):this.rules.other.tableAlignLeft.test(a)?o.align.push("left"):o.align.push(null);for(let a=0;a<r.length;a++)o.header.push({text:r[a],tokens:this.lexer.inline(r[a]),header:!0,align:o.align[a]});for(let a of i)o.rows.push(gT(a,o.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:qo(t[0],`
245
+ `),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
246
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let o=qo(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{let o=dG(t[2],"()");if(o===-2)return;if(o>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(n);o&&(n=o[1],i=o[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),wT(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[n.toLowerCase()];if(!i){let o=r[0].charAt(0);return{type:"text",raw:o,text:o}}return wT(r,i,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,o,a,s=i,c=0,l=n[0][0],u=r===l,f=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+i);(n=f.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o)continue;if(a=[...o].length,n[3]||n[4]){s+=a;continue}else if(n[5]||n[6]){if(i%3&&!((i+a)%3)){c+=a;continue}if(u)break}if(s-=a,s>0)continue;a=Math.min(a,a+s+c);let d=[...n[0]][0].length,m=e.slice(0,i+n.index+d+a);if(Math.min(i,a)%2){let p=m.slice(1,-1);return{type:"em",raw:m,text:p,tokens:this.lexer.inlineTokens(p)}}let h=m.slice(2,-2);return{type:"strong",raw:m,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,o,a,s=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(n=c.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o||(a=[...o].length,a!==i))continue;if(n[3]||n[4]){s+=a;continue}if(s-=a,s>0)continue;a=Math.min(a,a+s);let l=[...n[0]][0].length,u=e.slice(0,i+n.index+l+a),f=u.slice(i,-i);return{type:"del",raw:u,text:f,tokens:this.lexer.inlineTokens(f)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,n;return t[2]==="@"?(r=t[1],n="mailto:"+r):(r=t[1],n=r),{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},Cr=class tA{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ua,this.options.tokenizer=this.options.tokenizer||new Lm,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:fr,block:Bm.normal,inline:Gu.normal};this.options.pedantic?(r.block=Bm.pedantic,r.inline=Gu.pedantic):this.options.gfm&&(r.block=Bm.gfm,this.options.breaks?r.inline=Gu.breaks:r.inline=Gu.gfm),this.tokenizer.rules=r}static get rules(){return{block:Bm,inline:Gu}}static lex(t,r){return new tA(r).lex(t)}static lexInline(t,r){return new tA(r).inlineTokens(t)}lex(t){t=t.replace(fr.carriageReturn,`
247
+ `),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(fr.tabCharGlobal," ").replace(fr.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(s=>(o=s.call({lexer:this},t,r))?(t=t.substring(o.raw.length),r.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let s=r.at(-1);o.raw.length===1&&s!==void 0?s.raw+=`
248
+ `:r.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
249
+ `)?"":`
250
+ `)+o.raw,s.text+=`
251
+ `+o.text,this.inlineQueue.at(-1).src=s.text):r.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
252
+ `)?"":`
253
+ `)+o.raw,s.text+=`
254
+ `+o.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},r.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),r.push(o);continue}let a=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(a=t.substring(0,s+1))}if(this.state.top&&(o=this.tokenizer.paragraph(a))){let s=r.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
255
+ `)?"":`
256
+ `)+o.raw,s.text+=`
257
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(o),n=a.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
258
+ `)?"":`
259
+ `)+o.raw,s.text+=`
260
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],o=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(o+1,-1)))&&!(o>1&&this.linkInText(i.slice(1,o-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let n=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let f=l.slice(1,u-1);if(this.linkInText(f))return"["+f.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};n=n.replace(s,c)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,o="",a=1/0;for(;t;){if(t.length<a)a=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(o=""),i=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,n,o)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,n,o)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),f;this.options.extensions.startInline.forEach(d=>{f=d.call({lexer:this},u),typeof f=="number"&&f>=0&&(l=Math.min(l,f))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(o=s.raw.slice(-1)),i=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},qm=class{options;parser;constructor(e){this.options=e||Ua}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(fr.notSpaceStart)?.[0],i=e.replace(fr.endingNewline,"")+`
261
+ `;return n?'<pre><code class="language-'+mi(n)+'">'+(r?i:mi(i,!0))+`</code></pre>
262
+ `:"<pre><code>"+(r?i:mi(i,!0))+`</code></pre>
263
+ `}blockquote({tokens:e}){return`<blockquote>
264
+ ${this.parser.parse(e)}</blockquote>
265
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
266
+ `}hr(e){return`<hr>
267
+ `}list(e){let t=e.ordered,r=e.start,n="";for(let a=0;a<e.items.length;a++){let s=e.items[a];n+=this.listitem(s)}let i=t?"ol":"ul",o=t&&r!==1?' start="'+r+'"':"";return"<"+i+o+`>
268
+ `+n+"</"+i+`>
269
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
270
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
271
+ `}table(e){let t="",r="";for(let i=0;i<e.header.length;i++)r+=this.tablecell(e.header[i]);t+=this.tablerow({text:r});let n="";for(let i=0;i<e.rows.length;i++){let o=e.rows[i];r="";for(let a=0;a<o.length;a++)r+=this.tablecell(o[a]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
272
+ <thead>
273
+ `+t+`</thead>
274
+ `+n+`</table>
275
+ `}tablerow({text:e}){return`<tr>
276
+ ${e}</tr>
277
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
278
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${mi(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let n=this.parser.parseInline(r),i=hT(e);if(i===null)return n;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+mi(t)+'"'),o+=">"+n+"</a>",o}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=hT(e);if(i===null)return mi(r);e=i;let o=`<img src="${e}" alt="${mi(r)}"`;return t&&(o+=` title="${mi(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:mi(e.text)}},uA=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Fn=class rA{options;renderer;textRenderer;constructor(t){this.options=t||Ua,this.options.renderer=this.options.renderer||new qm,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new uA}static parse(t,r){return new rA(r).parse(t)}static parseInline(t,r){return new rA(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let n=0;n<t.length;n++){let i=t[n];if(this.options.extensions?.renderers?.[i.type]){let a=i,s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(a.type)){r+=s||"";continue}}let o=i;switch(o.type){case"space":{r+=this.renderer.space(o);break}case"hr":{r+=this.renderer.hr(o);break}case"heading":{r+=this.renderer.heading(o);break}case"code":{r+=this.renderer.code(o);break}case"table":{r+=this.renderer.table(o);break}case"blockquote":{r+=this.renderer.blockquote(o);break}case"list":{r+=this.renderer.list(o);break}case"checkbox":{r+=this.renderer.checkbox(o);break}case"html":{r+=this.renderer.html(o);break}case"def":{r+=this.renderer.def(o);break}case"paragraph":{r+=this.renderer.paragraph(o);break}case"text":{r+=this.renderer.text(o);break}default:{let a='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<t.length;i++){let o=t[i];if(this.options.extensions?.renderers?.[o.type]){let s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(o.type)){n+=s||"";continue}}let a=o;switch(a.type){case"escape":{n+=r.text(a);break}case"html":{n+=r.html(a);break}case"link":{n+=r.link(a);break}case"image":{n+=r.image(a);break}case"checkbox":{n+=r.checkbox(a);break}case"strong":{n+=r.strong(a);break}case"em":{n+=r.em(a);break}case"codespan":{n+=r.codespan(a);break}case"br":{n+=r.br(a);break}case"del":{n+=r.del(a);break}case"text":{n+=r.text(a);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},Yu=class{options;block;constructor(e){this.options=e||Ua}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Cr.lex:Cr.lexInline}provideParser(e=this.block){return e?Fn.parse:Fn.parseInline}},mG=class{defaults=nA();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fn;Renderer=qm;TextRenderer=uA;Lexer=Cr;Tokenizer=Lm;Hooks=Yu;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let n of e)switch(r=r.concat(t.call(this,n)),n.type){case"table":{let i=n;for(let o of i.header)r=r.concat(this.walkTokens(o.tokens,t));for(let o of i.rows)for(let a of o)r=r.concat(this.walkTokens(a.tokens,t));break}case"list":{let i=n;r=r.concat(this.walkTokens(i.items,t));break}default:{let i=n;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let a=i[o].flat(1/0);r=r.concat(this.walkTokens(a,t))}):i.tokens&&(r=r.concat(this.walkTokens(i.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=t.renderers[i.name];o?t.renderers[i.name]=function(...a){let s=i.renderer.apply(this,a);return s===!1&&(s=o.apply(this,a)),s}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[i.level];o?o.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),n.extensions=t),r.renderer){let i=this.defaults.renderer||new qm(this.defaults);for(let o in r.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let a=o,s=r.renderer[a],c=i[a];i[a]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new Lm(this.defaults);for(let o in r.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let a=o,s=r.tokenizer[a],c=i[a];i[a]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new Yu;for(let o in r.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,s=r.hooks[a],c=i[a];Yu.passThroughHooks.has(o)?i[a]=l=>{if(this.defaults.async&&Yu.passThroughHooksRespectAsync.has(o))return(async()=>{let f=await s.call(i,l);return c.call(i,f)})();let u=s.call(i,l);return c.call(i,u)}:i[a]=(...l)=>{if(this.defaults.async)return(async()=>{let f=await s.apply(i,l);return f===!1&&(f=await c.apply(i,l)),f})();let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,o=r.walkTokens;n.walkTokens=function(a){let s=[];return s.push(o.call(this,a)),i&&(s=s.concat(i.call(this,a))),s}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Cr.lex(e,t??this.defaults)}parser(e,t){return Fn.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},i={...this.defaults,...n},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let a=i.hooks?await i.hooks.preprocess(t):t,s=await(i.hooks?await i.hooks.provideLexer(e):e?Cr.lex:Cr.lexInline)(a,i),c=i.hooks?await i.hooks.processAllTokens(s):s;i.walkTokens&&await Promise.all(this.walkTokens(c,i.walkTokens));let l=await(i.hooks?await i.hooks.provideParser(e):e?Fn.parse:Fn.parseInline)(c,i);return i.hooks?await i.hooks.postprocess(l):l})().catch(o);try{i.hooks&&(t=i.hooks.preprocess(t));let a=(i.hooks?i.hooks.provideLexer(e):e?Cr.lex:Cr.lexInline)(t,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let s=(i.hooks?i.hooks.provideParser(e):e?Fn.parse:Fn.parseInline)(a,i);return i.hooks&&(s=i.hooks.postprocess(s)),s}catch(a){return o(a)}}}onError(e,t){return r=>{if(r.message+=`
279
+ Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+mi(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},Qa=new mG;nt.options=nt.setOptions=function(e){return Qa.setOptions(e),nt.defaults=Qa.defaults,yT(nt.defaults),nt};nt.getDefaults=nA;nt.defaults=Ua;nt.use=hG;nt.walkTokens=function(e,t){return Qa.walkTokens(e,t)};nt.parseInline=Qa.parseInline;nt.Parser=Fn;nt.parser=Fn.parse;nt.Renderer=qm;nt.TextRenderer=uA;nt.Lexer=Cr;nt.lexer=Cr.lex;nt.Tokenizer=Lm;nt.Hooks=Yu;nt.parse=nt;Rne=nt.options,Nne=nt.setOptions,IT=nt.walkTokens,Sne=nt.parseInline,Ene=Fn.parse,Cne=Cr.lex});import{promises as xT}from"node:fs";import vc from"node:path";import{createHash as gG}from"node:crypto";function U(e){throw new R("INVALID_WORKFLOW",`${e};请修正适配契约或恢复已固定的依赖后继续`)}async function Vo(e,t={}){let r={},n=async i=>{let o=await xT.readdir(vc.join(e,i),{withFileTypes:!0});for(let a of o.sort((s,c)=>s.name.localeCompare(c.name,"en"))){let s=i?`${i}/${a.name}`:a.name;if(a.isSymbolicLink()&&U(`依赖不允许符号链接:${s}`),a.isDirectory())await n(s);else if(a.isFile()){let c=await De(e,s,16777216,{label:`应用依赖 ${s}`});r[s]=c.bytes.toString("base64")}else U(`依赖包含非常规文件:${s}`)}};return await n(""),!t.allowEmpty&&Object.keys(r).length===0&&U("依赖目录为空"),r}function Mo(e){return j(Object.fromEntries(Object.entries(e).map(([t,r])=>[t,gG("sha256").update(Buffer.from(r,"base64")).digest("hex")])))}function vG(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Buffer.from(r,"base64").toString("utf8")]))}function wG(e,t){for(let[l,u]of[[e,"输入"],[t,"输出"]])(!l||typeof l!="object"||Array.isArray(l))&&U(`${u} 必须提供可检查的 JSON Schema`),l.$async===!0&&U(`${u} 不支持异步 Schema,请注册实际 SDK 验证器`);let r=JSON.stringify([e,t]),n=ed.get(r);if(n)return n;let[i,o]=JSON.parse(r),a=new PT.Ajv({strict:!0,allErrors:!0}),s=a.compile(i),c={ajv:a,input:s,output:JSON.stringify(i)===JSON.stringify(o)?s:a.compile(o)};return ed.size>=64&&ed.delete(ed.keys().next().value),ed.set(r,c),c}async function yG(e){let t=await xT.realpath(e),r=await Vo(t),n=vG(r);n["SKILL.md"]?.trim()||U(`Skill 缺少真实 SKILL.md:${e}`);for(let[i,o]of Object.entries(n)){if(!i.endsWith(".md"))continue;let a=[];IT(Cr.lex(o),s=>{(s.type==="link"||s.type==="image")&&a.push(s.href)});for(let s of a){if(/^(?:[a-z][a-z\d+.-]*:|#|\/\/)/iu.test(s))continue;let c;try{c=decodeURIComponent(s.split(/[?#]/u)[0])}catch{U(`Skill 引用路径编码无效:${i} -> ${s}`)}if(!c)continue;let l=vc.posix.normalize(vc.posix.join(vc.posix.dirname(i),c));(l===".."||l.startsWith("../")||vc.posix.isAbsolute(c))&&U(`Skill 引用越过依赖目录:${i} -> ${s}`),!Object.hasOwn(n,l)&&!Object.keys(n).some(u=>u.startsWith(`${l}/`))&&U(`Skill 引用资源缺失:${i} -> ${s}`)}}return{root:t,files:n,contentHash:Mo(r)}}async function fA(e,t){(!e||typeof e.id!="string"||!e.id.trim()||typeof e.root!="string")&&U("Skill 依赖缺少身份或目录");let r=await yG(vc.resolve(t,e.root));e.contentHash!==r.contentHash&&U(`Skill 内容发生漂移:${e.id}`);let n=e.adapter;(!n||!["guidance","action","check","subworkflow"].includes(n.kind)||!["read","write","external"].includes(n.sideEffect)||!["none","user"].includes(n.interaction)||!["self-report","machine-check","independent-review"].includes(n.completion)||!["stop","repair","retry"].includes(n.failure)||!["manual","reconcile"].includes(n.recovery)||typeof n.controlsApproval!="boolean")&&U(`Skill 适配契约不完整:${e.id}`),(!Array.isArray(n.scope)||!n.scope.length||n.scope.some(s=>typeof s!="string"||!s.trim())||!Array.isArray(n.requiredCapabilities)||n.requiredCapabilities.some(s=>typeof s!="string"||!s.trim()))&&U(`Skill 缺少范围或宿主能力:${e.id}`),n.kind==="guidance"&&(n.sideEffect!=="read"||n.controlsApproval||n.interaction!=="none")&&U(`有副作用或审批逻辑的 Skill 不能作为普通指导:${e.id}`),n.sideEffect==="external"&&n.recovery!=="reconcile"&&U(`外部操作缺少未知结果核对契约:${e.id}`);let i=n.review;(!i||i.status!=="accepted"||!i.reviewedBy?.trim()||i.contentHash!==r.contentHash||!Array.isArray(i.capabilities)||!i.capabilities.length||!Array.isArray(i.effects)||!i.effects.length)&&U(`Skill 必需能力尚未完成内容适配审查:${e.id}`);for(let s of[...i.capabilities,...i.effects])(!s||!s.excerpt?.trim()||!r.files[s.file]?.includes(s.excerpt))&&U(`Skill 审查证据与真实文件不匹配:${e.id}`);i.capabilities.some(s=>typeof s.id!="string"||!s.id.trim())&&U(`Skill 能力证据缺少身份:${e.id}`);let o=wG(n.inputSchema,n.outputSchema),a=(s,c)=>l=>{s(l)||U(`${e.id} ${c} 不匹配:${o.ajv.errorsText(s.errors)}`)};return{...r,id:e.id,adapter:n,validateInput:a(o.input,"输入"),validateOutput:a(o.output,"输出")}}var PT,ed,wc=x(()=>{"use strict";PT=tr(sm(),1);dA();Me();st();ed=new Map});import Hn from"node:path";import{realpathSync as kG,existsSync as bG}from"node:fs";function pA(e){let t=structuredClone(e),r=n=>{if(!(!n||typeof n!="object"||Object.isFrozen(n))){for(let i of Object.values(n))r(i);Object.freeze(n)}};return r(t),t}function Cn(e){return["running","unknown"].includes(e.status)||e.status==="cancelled"&&e.type!=="invoke_skill"&&!!e.claim&&!e.cancellation&&!e.executionStop}function Mm(e,t){let r=(n,i)=>{let o=Hn.relative(Hn.resolve(n),Hn.resolve(i));return!o||!Hn.isAbsolute(o)&&o!==".."&&!o.startsWith(".."+Hn.sep)};return r(e,t)||r(t,e)}function Fm(e,t,r){return e.manifest.bindings.filter(n=>n.workflowId===t.workflow.id&&n.stepId===r.stepId&&n.usage==="action").flatMap(n=>{let i=e.manifest.skills.find(a=>a.id===n.skillId);if(!i||i.adapter.sideEffect==="read")return[];if(i.adapter.sideEffect!=="write")return i.adapter.scope.map(a=>({ref:a,workspace:!1,write:i.adapter.sideEffect==="write"}));let o=e.projectRoot??process.cwd();if(n.workspaceFrom){o=r.input;for(let a of n.workspaceFrom.split("."))o=o&&typeof o=="object"?o[a]:void 0}if(typeof o!="string"||!Hn.isAbsolute(o))throw new R("COMMAND_REJECTED","Skill 缺少实际写入工作区");return i.adapter.scope.map(a=>{let s=Hn.resolve(o,a),c=s;for(;!bG(c)&&c!==Hn.dirname(c);)c=Hn.dirname(c);return{ref:Hn.resolve(kG(c),Hn.relative(c,s)),workspace:!!n.workspaceFrom,write:!0}})})}function yc(e,t,r,n=[]){let i=(a,s)=>Fm(e,a,s),o=i(t,r);if(o.length){for(let a of[t,...n.filter(s=>s.runId!==t.runId)])for(let s of a.actions)if((a.runId!==t.runId||s.id!==r.id)&&(Cn(s)||a.runId===t.runId&&s.status==="pending")&&i(a,s).some(c=>o.some(l=>{if(a.runId===t.runId&&c.write&&l.write&&c.workspace!==l.workspace)throw new R("COMMAND_REJECTED","并行写入不能混用声明工作区和默认范围;请为两项工作指定实际工作区");return!c.write||!l.write?l.ref===c.ref:Mm(c.ref,l.ref)}))){let c=new R(a.runId===t.runId?"COMMAND_REJECTED":"SCOPE_HELD",`Skill 写入范围存在并行冲突,仍由 Run ${a.runId} 的 ${s.stepId} 占用;请停止原执行或提交真实结果`);throw Object.assign(c,{blockedRunIds:[a.runId]}),c}}}function OT(e,t,r){let n=e.manifest.bindings.filter(a=>a.workflowId===r.workflow.id&&a.stepId===t.stepId&&a.usage==="action"),i=n[0],o=i?e.skills.get(i.skillId):void 0;if(n.length!==1||!i||!o||t.type!=="invoke_skill"||t.ref!==i.skillId)throw new R("EXECUTOR_UNSUPPORTED","Action 未绑定到唯一的真实 Skill");return{binding:i,skill:o}}function kc(e,t,r){let{binding:n,skill:i}=OT(e,t,r);if(i.validateInput(t.input),i.adapter.sideEffect!=="read"){let o=n.authorizationFrom?r.actionContexts[t.id]?.results[n.authorizationFrom]:void 0,a=r.waits.find(s=>s.stepId===n.authorizationFrom&&s.sequence===o?.sequence);if(!o||a?.status!=="resolved"||!a.decision||!(n.authorizationChoices??["approved"]).includes(a.decision.choice)||a.decision.proposalHash!==a.proposalHash||j(o.value)!==j({choice:a.decision.choice,proposal:a.proposal}))throw new R("STALE_PROPOSAL","此工作缺少父流程的当前批准记录")}return{binding:n,skill:i}}function TT(e,t){let r=async(n,i,o)=>{if(!o)throw new R("INVALID_RUN","Skill 执行需要当前 SDK Run");let{binding:a,skill:s}=kc(e,n,o);if(yc(e,o,n),s.adapter.requiredCapabilities.some(c=>!t.capabilities.includes(c)))throw new R("CAPABILITY_REQUIRED","宿主缺少 Skill 必需能力");if(s.adapter.sideEffect==="external"&&!t.reconcile)throw new R("RECONCILIATION_REQUIRED","外部操作没有结果核对适配器,不能执行");if(!await t.authorize({action:n,run:o,binding:a,skill:s,context:i}))throw new R("COMMAND_REJECTED","宿主授权不覆盖此 Skill、范围或副作用")};return{id:t.id,capabilities:t.capabilities,preflight:r,supports:n=>n.type==="invoke_skill"&&e.manifest.bindings.some(i=>i.stepId===n.stepId&&i.skillId===n.ref&&i.usage==="action"),async execute(n,i,o){if(!o)throw new R("INVALID_RUN","Skill 执行需要当前 SDK Run");let{binding:a,skill:s}=OT(e,n,o);return await t.invokeSkill({action:n,run:o,binding:a,skill:s,context:i})}}}var Hm=x(()=>{"use strict";Me()});import{randomUUID as jT}from"node:crypto";import{promises as AG}from"node:fs";import Ja from"node:path";function hA(e){let t=e.rootDir,r=m=>{throw new R("STORE_INDEX_CORRUPT",m)},n=async m=>{let h=Ja.parse(t).root;if(!(await oe(h,Ja.relative(h,t).replaceAll("\\","/"),{label:"应用 Store",expected:"directory"})).exists)return null;let p=`${mA}/${m}.json`;if(!(await oe(t,p,{label:"应用存储索引",expected:"file"})).exists)return null;try{let g=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await De(t,p,Number.MAX_SAFE_INTEGER,{label:"应用存储索引"})).bytes));if(m==="inventory"){let{checksum:v,...w}=g;return v!==j(w)&&r("独立成员清单校验值不一致"),w}return g}catch{return r(`应用存储索引 ${m} 无法读取;请保留现场并显式检查`)}},i=async(m,h)=>{await xt(t,mA,{label:"应用存储索引"}),await Ht(Ja.join(t,mA,`${m}.json`),JSON.stringify(["index","inventory"].includes(m)?{...h,checksum:j(h)}:h)+`
280
+ `,{containedRoot:t,requireAtomicPublication:!0})},o=async()=>JSON.stringify(await Promise.all(["",".runtime-store-v2",".runtime-store-history"].map(async m=>{let h=await oe(m?t:Ja.dirname(t),m||Ja.basename(t),{label:"应用存储分区",expected:"directory"});if(!h.exists)return null;let p=await AG.lstat(h.target);return[p.dev,p.ino,p.mtimeMs,p.ctimeMs]})));async function a(){let m=await n("index");if(!m)return null;let{checksum:h,...p}=m;return h!==j(p)&&r("应用存储索引校验值不一致"),p&&(p.schema!==Qm||typeof p.epoch!="string"||!["building","ready"].includes(p.state)||!Array.isArray(p.holders)||p.holders.some(g=>typeof g!="string")||new Set(p.holders).size!==p.holders.length||!Number.isSafeInteger(p.memberCount)||p.memberCount<0||p.pending!==null&&(!p.pending||typeof p.pending.runId!="string"||typeof p.pending.registering!="boolean"))&&r("应用存储索引格式损坏"),p}async function s(m){let h=await n("inventory");return(!h||h.epoch!==m.epoch||!Array.isArray(h.members)||h.members.some(p=>typeof p!="string")||new Set(h.members).size!==h.members.length||h.aborted!==void 0&&(!Array.isArray(h.aborted)||h.aborted.some(p=>typeof p!="string"||h.members.includes(p))||new Set(h.aborted).size!==h.aborted.length)||h.members.length!==m.memberCount||j(h)!==m.inventoryHash)&&r("应用存储成员清单与 epoch/hash 不一致,不能忽略已登记 Run"),h}async function c(m,h){let p=await db({rootDir:t}),g=[],v=[];for(let w of p){(w.error||!w.runId)&&r(`Run 无法发现:${w.storageKey} (${w.error?.code??"missing identity"})`);let y=w.runId;await e.settle?.(y);let b=await e.read(y);!b&&h?.aborted?.includes(y)&&!h.members.includes(y)||(b||r(`已发现的 Run 正文缺失:${y}`),g.push(y),await e.holds(b)&&v.push(y))}return h?.members.some(w=>!g.includes(w))&&r("已登记 Run 缺失,不能通过重建索引丢弃占用;请恢复原记录"),m.holders=v.sort(),{epoch:m.epoch,members:g.sort(),...h?.aborted?{aborted:h.aborted.filter(w=>!g.includes(w))}:{}}}async function l(){let m=Ja.parse(t).root;await xt(m,Ja.relative(m,t).replaceAll("\\","/"),{label:"应用 Store"});let h=await a();if(h?.state==="ready")return h;h||(await n("inventory")&&r("成员清单存在但索引缺失,请显式检查,不能静默初始化"),h={schema:Qm,epoch:jT(),state:"building",inventoryHash:null,memberCount:0,holders:[],pending:null,stamps:null},await i("index",h));let p=await n("inventory"),g=await n("repair");g&&g.inventory.epoch===h.epoch&&j(g.inventory)===h.inventoryHash&&p&&j(p)===g.previousHash&&(p=g.inventory),p&&(p.epoch!==h.epoch||!Array.isArray(p.members)||p.members.some(w=>typeof w!="string")||new Set(p.members).size!==p.members.length||h.inventoryHash!==null&&(j(p)!==h.inventoryHash||p.members.length!==h.memberCount))&&r("初始化中的成员清单不匹配");let v=await c(h,p??void 0);return!p&&h.inventoryHash!==null&&j(v)!==h.inventoryHash&&r("初始化期间成员清单发生变化,不能重写并丢弃原成员"),h.inventoryHash=j(v),h.memberCount=v.members.length,await i("index",h),await i("inventory",v),h.state="ready",h.stamps=await o(),await i("index",h),h}async function u(m){if(!m.pending)return;let{runId:h,registering:p}=m.pending;await e.settle?.(h);let g=await e.read(h);if(!g&&!p&&r(`未完成写入的 Run 缺失:${h}`),!g&&p){let v=await s(m),w=await n("registration");(v.members.includes(h)||w?.epoch===m.epoch&&w.previousHash===m.inventoryHash&&w.inventory.members.includes(h))&&r(`注册已提交或已观测到提交,但 Run 已缺失:${h}`)}if(p){let v=await s(m),w=!1;g&&!v.members.includes(h)?(v.members.push(h),v.members.sort(),v.aborted&&(v.aborted=v.aborted.filter(y=>y!==h)),w=!0):!g&&!v.aborted?.includes(h)&&(v.aborted=[...v.aborted??[],h].sort(),w=!0),w&&(await i("registration",{epoch:m.epoch,previousHash:m.inventoryHash,inventory:v}),await i("inventory",v),m.inventoryHash=j(v),m.memberCount=v.members.length)}m.holders=m.holders.filter(v=>v!==h),g&&await e.holds(g)&&m.holders.push(h),m.holders.sort(),m.pending=null,m.stamps=await o(),await i("index",m)}async function f(m){if(!m.pending?.registering)return;let h=await n("registration");if(h?.epoch===m.epoch&&h.previousHash===m.inventoryHash){let p=await n("inventory");p&&j(p)===j(h.inventory)&&(m.inventoryHash=j(p),m.memberCount=p.members.length)}}async function d(){let m=await l();return await f(m),m.pending&&await u(m),m.stamps!==await o()&&r("Store 分区身份已变化,必须显式 audit;不能继续使用占用投影"),m}return{async isAbortedRegistration(m){let h=await a();if(!h||h.state!=="ready"||h.pending)return!1;let p=await s(h);return!p.members.includes(m)&&!!p.aborted?.includes(m)&&await e.read(m)===null},async holders(){let m=await d(),h=[];for(let p of m.holders){await e.settle?.(p);let g=await e.read(p);g||r(`占用 Run 缺失:${p}`),await e.holds(g)&&h.push(g)}return h},async begin(m,h){let p=await d();h&&(await s(p)).members.includes(m)&&r(`已登记 Run 不能作为新记录重建:${m}`),p.pending={runId:m,registering:h},await i("index",p)},async finish(){let m=await a();(!m||m.state!=="ready")&&r("应用存储索引未就绪"),await f(m),await u(m)},async inspect(){try{let m=await a();return!m&&await n("inventory")&&r("成员清单存在但索引缺失"),m}catch(m){let h=await n("inventory");if(!h||typeof h.epoch!="string")throw m;return{schema:Qm,epoch:h.epoch,state:"corrupt",error:{code:"STORE_INDEX_CORRUPT",message:m instanceof Error?m.message:String(m)}}}},async repair(m,h){let p;try{p=await a()}catch(w){if(m!=="rebuild")throw w;p=null}if(!p&&m==="rebuild"){let w=await n("inventory");w&&w.epoch===h&&Array.isArray(w.members)&&w.members.every(y=>typeof y=="string")&&new Set(w.members).size===w.members.length&&(p={schema:Qm,epoch:w.epoch,state:"building",inventoryHash:j(w),memberCount:w.members.length,holders:[],pending:null,stamps:null})}if(!p||p.epoch!==h)throw new R("STORE_INDEX_EPOCH_CHANGED","索引 epoch 已变化,请重新 inspect");await f(p),p.pending&&await u(p);let g=await s(p),v=await c(p,g);return m==="rebuild"&&(p.epoch=jT(),v.epoch=p.epoch),await i("repair",{previousHash:p.inventoryHash,inventory:v}),p.inventoryHash=j(v),p.memberCount=v.members.length,p.state="building",await i("index",p),await i("inventory",v),p.state="ready",p.stamps=await o(),await i("index",p),p}}}var mA,Qm,$T=x(()=>{"use strict";ci();st();Me();mA=".runtime-store-coordination",Qm="comet.application-holder-index.v1"});import RG from"node:os";import NG from"node:path";function DT(e,t,r=RG.homedir()){return NG.join(t==="project"?e:r,".comet/applications")}var BT=x(()=>{"use strict"});import _n from"node:path";function SG(e){return/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e)||U("应用身份无效"),e}function WT(e,t){let r=_n.resolve(e,t),n=_n.parse(r).root;return{volume:n,ref:_n.relative(n,r).replaceAll("\\","/")}}async function LT(e,t,r){let n=WT(e,t);return oe(n.volume,n.ref,{expected:r,label:"SDK application installation"})}async function EG(e,t){let r=`${SG(t)}/current.json`;if(!(await LT(e,r,"file")).exists)return null;let n=WT(e,r),{bytes:i}=await De(n.volume,n.ref,1024*1024,{label:"SDK application installation"}),o=JSON.parse(i.toString("utf8"));if((o.schema!=="comet.workflow.application.install.v1"||o.id!==t||!o.version?.trim()||!/^[a-f\d]{64}$/u.test(o.contentHash)||o.packageRef!==`${t}/versions/${o.contentHash}`)&&U("安装记录无效;保留文件并重新预览"),o.entry){let a=_n.dirname(_n.dirname(e)),s=_n.dirname(o.entry.root??"");(!_n.isAbsolute(o.entry.root)||![_n.join(a,".claude/skills"),_n.join(a,".agents/skills")].includes(s)||!/^[a-f\d]{64}$/u.test(o.entry.contentHash)||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(_n.basename(o.entry.root)))&&U("宿主入口安装记录无效;保留文件并核对原安装")}return o}async function gA(e,t){let r=DT(e.projectRoot,e.scope,e.userRoot),n=await EG(r,t);if(!n)return null;let i=`${n.packageRef}/application.json`;return await LT(r,i,"file"),Mo(await Vo(_n.join(r,n.packageRef)))!==n.contentHash&&U("已安装版本内容发生漂移;恢复原包后继续"),_n.join(r,i)}var qT=x(()=>{"use strict";st();BT();wc()});var VT=x(()=>{"use strict";Hm()});import Wt from"node:path";function Hi(e,t){let r=Wt.relative(e,t);return!r||!Wt.isAbsolute(r)&&r!==".."&&!r.startsWith(".."+Wt.sep)}function CG(e,t,r){if(!t.workspaceFrom)return e.projectRoot;let n=r?.input;for(let i of t.workspaceFrom.split("."))n=n&&typeof n=="object"?n[i]:void 0;if(typeof n!="string"||!Wt.isAbsolute(n))throw new Error("当前 Action 缺少已声明的实际写入工作区");return n}function MT(e){let t=Wt.resolve(e.projectRoot),r=[".git","node_modules",".claude",".agents",".codex",".cursor",".comet/runtime",".comet/applications",".comet/creator"].map(s=>Wt.resolve(t,s)),n={manifest:e.manifest,skills:e.skills,projectRoot:t},i=["AGENTS.md","AGENTS.override.md","CLAUDE.md"].map(s=>Wt.join(t,s)),o=e.manifest.bindings.filter(s=>s.usage==="action"&&e.skills.get(s.skillId)?.adapter.sideEffect==="write"),a=e.manifest.bindings.some(s=>s.usage==="action");return async(s,c)=>{if(c.intent!=="write")return{allowed:!0,reason:"此请求没有可归属的 SDK 应用写入"};try{if(!c.targets.length)throw new Error("SDK 应用写入必须声明实际文件");let l=[];for(let b of c.targets){let N=Wt.resolve(t,b),A=Wt.relative(t,N);if(!A||!Hi(t,N))throw new Error("写入目标必须位于当前项目内");if(await oe(t,A.replaceAll("\\","/"),{expected:"file",label:"SDK 应用写入"}),Hi(Wt.resolve(e.packageRoot),N)||r.some(S=>Hi(S,N))||i.some(S=>!Wt.relative(S,N))||!Wt.relative(Wt.join(t,".comet/current-change.json"),N))throw new Error("固定应用、SDK 状态与宿主配置只能由正式 Runtime 或安装入口维护");l.push(N)}let u=Wt.join(t,".comet/requests");if(l.every(b=>Hi(u,b)&&b.endsWith(".json")))return{allowed:!0,reason:"临时协议请求不是推进状态;Runtime 仍核对身份与批准"};let f=[],d=new Set,m=0,h=async b=>{if(d.has(b.runId))throw new Error("子流程归属循环");if((["running","waiting"].includes(b.status)||b.actions.some(A=>A.status==="pending"||Cn(A))||b.ready.length>0||b.waits.some(A=>A.status==="pending")||(b.evidenceWaits??[]).some(A=>A.status==="pending"))&&++m>128)throw new Error("活跃子流程超出安全读取范围");d.add(b.runId),f.push(b);for(let A of b.children){let S=b.actions.find(Q=>Q.id===A.actionId);if(!S||S.type!=="child_workflow")throw new Error("子流程与 SDK Action 归属不一致");if(!S.claim)continue;let _=await e.readChild(A.runId);if(_.runId!==A.runId||_.workflow.id!==A.workflow.id||_.workflow.version!==A.workflow.version||_.lineage.length!==b.lineage.length+1||_.lineage.at(-1)!==b.runId||b.lineage.some((Q,F)=>_.lineage[F]!==Q))throw new Error("子流程没有当前 SDK Run 的有效归属");await h(_)}};await h(s);let p=["completed","cancelled","failed"].includes(s.status),g=[],v=[];for(let b of f)for(let N of o.filter(A=>A.workflowId===b.workflow.id)){let A=e.skills.get(N.skillId),S=b.actions.filter(_=>_.stepId===N.stepId);for(let _ of S){let Q=CG(e,N,_);v.push(...A.adapter.scope.map(F=>Wt.resolve(Q,F))),!(p||["cancelled","failed"].includes(b.status)||_.status!=="running")&&(kc(n,_,b),yc(n,b,_,f),g.push(...A.adapter.scope.map(F=>Wt.resolve(Q,F))))}!N.workspaceFrom&&!S.length&&v.push(...A.adapter.scope.map(_=>Wt.resolve(t,_)))}let w=Wt.join(t,".comet/evidence",e.manifest.id),y=!p&&f.some(b=>b.actions.some(N=>["running","unknown"].includes(N.status)));for(let b of l)if(!(Hi(u,b)&&b.endsWith(".json"))&&!(y&&Hi(w,b))){if(p){if(v.some(N=>Hi(N,b))||Hi(Wt.join(t,".comet"),b))throw new Error("已结束 Run 的声明产物保持固定;继续修改应启动新的 Run")}else if((!e.custom||a)&&!g.some(N=>Hi(N,b)))throw new Error("当前 SDK Action 没有此写入权限;先确认当前提案并领取允许写入的 Action")}return e.custom?await e.custom(s,c):{allowed:!0,reason:p?"目标不属于已结束应用或控制资源":"写入属于当前已批准且已领取的 SDK Action"}}catch(l){return{allowed:!1,reason:l instanceof Error?l.message:"无法安全核对 SDK 应用写入"}}}}var FT=x(()=>{"use strict";st();Hm()});function td(e,t,r){return(!e||typeof e!="object"||Array.isArray(e))&&U(`${r} 必须是 JSON 对象`),Object.keys(e).some(n=>!t.includes(n))&&U(`${r} 含未声明字段`),e}function Qn(e,t,r=256){(typeof e!="string"||!e.trim()||e.length>r)&&U(`${t} 必须是长度不超过 ${r} 的非空文本`)}function xG(e,t){let r=td(e,["title","description","steps"],"应用展示信息");if(r.title!==void 0&&Qn(r.title,"应用展示名称"),r.description!==void 0&&Qn(r.description,"应用展示说明",4e3),r.steps===void 0)return;(!Array.isArray(r.steps)||r.steps.length>HT)&&U("步骤展示信息必须是有界数组");let n=new Set;for(let i of r.steps){let o=td(i,["workflowId","stepId","title","phase","description","outputFields"],"步骤展示信息");Qn(o.workflowId,"展示流程 ID"),Qn(o.stepId,"展示步骤 ID"),Qn(o.title,"步骤展示名称"),o.phase!==void 0&&Qn(o.phase,"步骤阶段名称"),o.description!==void 0&&Qn(o.description,"步骤展示说明",4e3);let a=JSON.stringify([o.workflowId,o.stepId]);if(n.has(a)&&U(`重复步骤展示信息:${o.workflowId}/${o.stepId}`),n.add(a),t){let c=t.filter(l=>l.id===o.workflowId);(!c.length||c.some(l=>!Object.hasOwn(l.steps,o.stepId)))&&U(`展示信息引用不存在的步骤:${o.workflowId}/${o.stepId}`)}if(o.outputFields===void 0)continue;(!Array.isArray(o.outputFields)||o.outputFields.length>32)&&U("步骤展示输出字段必须是有界数组");let s=new Set;for(let c of o.outputFields){let l=td(c,["path","label"],"步骤展示输出字段");Qn(l.path,"展示输出路径",512),Qn(l.label,"展示输出名称"),(!/^[A-Za-z_][A-Za-z_0-9]*(?:\.(?:[A-Za-z_][A-Za-z_0-9]*|0|[1-9][0-9]*))*$/u.test(l.path)||l.path.split(".").some(u=>["__proto__","constructor","prototype"].includes(u)))&&U(`展示输出字段路径无效:${l.path}`),s.has(l.path)&&U(`重复展示输出字段:${l.path}`),s.add(l.path)}}}function vA(e){(typeof e!="string"||e.length>1024||!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\.json$/u.test(e)||["application.json","installation.json"].includes(e))&&U("应用流程定义必须声明固定包内的 JSON 相对路径")}function PG(e,t){let r=typeof e=="string"?e:ri(e),n=td(JSON.parse(r),["schema","application","workflows","presentation"],"应用流程定义");n.schema!=="comet.workflow.application.definition.v1"&&U("应用流程定义格式不受支持");let i=td(n.application,["id","version"],"流程定义应用身份");Qn(i.id,"流程定义应用 ID"),Qn(i.version,"流程定义应用版本"),t&&(t.id!==i.id||t.version!==i.version)&&U("流程定义与应用固定身份不匹配"),(!Array.isArray(n.workflows)||!n.workflows.length||n.workflows.length>_G)&&U("应用流程定义必须包含有界的完整流程数组");let o=0,a=0,s=n.workflows.map(l=>((!l||typeof l!="object"||!l.steps||typeof l.steps!="object")&&U("应用流程定义缺少步骤"),o+=Object.keys(l.steps).length,a+=Array.isArray(l.transitions)?l.transitions.length:0,(o>HT||a>IG)&&U("应用流程定义超过步骤或转移数量限制"),An(l))),c=new Set;for(let l of s){let u=JSON.stringify([l.id,l.version]);c.has(u)&&U(`重复流程身份:${l.id}@${l.version}`),c.add(u)}for(let l of s)for(let[u,f]of Object.entries(l.steps))f.type==="child_workflow"&&!c.has(JSON.stringify([f.workflow.id,f.workflow.version]))&&U(`子流程定义不存在:${l.id}/${u}`);return n.presentation!==void 0&&xG(n.presentation,s),{schema:"comet.workflow.application.definition.v1",application:{id:i.id,version:i.version},workflows:s,...n.presentation===void 0?{}:{presentation:n.presentation}}}function QT(e,t){if(t.definition!==void 0)return vA(t.definition),Object.hasOwn(e,t.definition)||U("固定包缺少声明的应用流程定义"),PG(Buffer.from(e[t.definition],"base64").toString("utf8"),t)}function UT(e,t){let r=n=>n.map(i=>{let o=An(i);return[o.id,o.version,j(o)]}).sort((i,o)=>JSON.stringify(i).localeCompare(JSON.stringify(o),"en"));j(r(e.workflows))!==j(r(t))&&U("实际工厂的流程与固定流程定义不匹配,请同步确认方案")}function wA(e,t){let r=new Map(e.workflows.map(i=>[JSON.stringify([i.id,i.version]),j(i)])),n=JSON.stringify([t.workflow.id,t.workflow.version]);return r.get(n)===t.workflow.hash&&t.definitionHashes[n]===t.workflow.hash&&Object.entries(t.definitionHashes).every(([i,o])=>r.get(i)===o)}var _G,HT,IG,JT=x(()=>{"use strict";Me();kr();wc();_G=256,HT=4096,IG=16384});import{createHash as OG}from"node:crypto";async function KT(e,t){let r={},n={},i=new zT.Ajv({strict:!0,allErrors:!0});for(let o of t){let a=await De(e,o.ref,16777216,{label:`必需产物 ${o.ref}`}),s=a.bytes.toString("utf8");if(o.nonEmpty&&!s.trim())throw new Error(`必需产物不能为空:${o.ref}`);if(o.requiredText?.some(c=>!s.includes(c)))throw new Error(`实际工件不满足内容要求:${o.ref}`);if(o.requiredHeadings?.length){let c=new Set,l,u="";for(let d of s.split(/\r?\n/u)){let m=/^ {0,3}(`{3,}|~{3,})/u.exec(d);if(m){let p=m[1];l?l.char===p[0]&&p.length>=l.length&&d.slice(m[0].length).trim()===""&&(l=void 0):l={char:p[0],length:p.length},u="";continue}if(l)continue;let h=/^ {0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$/u.exec(d);h?c.add(h[1].trim()):u.trim()&&/^ {0,3}(?:=+|-+)\s*$/u.test(d)&&c.add(u.trim()),u=/^ {0,3}\S/u.test(d)?d:""}let f=o.requiredHeadings.filter(d=>!c.has(d));if(f.length)throw new Error(`必需产物缺少章节:${o.ref},${f.join("、")}`)}if(o.schema!==void 0){let c=o.schema;if(typeof c!="boolean"&&(c===null||Array.isArray(c)||typeof c!="object"||c.$async===!0))throw new Error(`工件需要同步 JSON Schema:${o.ref}`);let l=i.compile(c);if(!l(JSON.parse(s)))throw new Error(`实际工件结构无效:${o.ref},${i.errorsText(l.errors)}`)}r[o.ref]=s,n[o.ref]=OG("sha256").update(a.bytes).digest("hex")}return{files:r,artifactHashes:n}}var zT,GT=x(()=>{"use strict";zT=tr(sm(),1);Me();st();wc()});import XT from"node:path";function yA(e,t,r,n){let i=t.bindings.find(a=>a.usage==="action"&&a.workflowId===r.workflow.id&&a.stepId===n.stepId);if(!i?.workspaceFrom)return e;let o=kA(n.input,i.workspaceFrom);if(typeof o!="string"||!XT.isAbsolute(o))throw new Error("产物检查缺少当前 Action 已声明的实际工作区");return o}function ZT(e){(typeof e!="string"||!e||e.length>4096||e.includes("\\")||e.includes(":")||e.includes("\0")||XT.posix.isAbsolute(e)||e.split("/").some(r=>!r||r==="."||r===".."||/[ .]$/u.test(r)))&&U("产物引用必须是项目内安全相对路径"),([".git","node_modules",".agents",".claude",".codex",".cursor",".comet/runtime",".comet/applications",".comet/creator"].some(r=>e.toLowerCase()===r||e.toLowerCase().startsWith(r+"/"))||["agents.md","agents.override.md","claude.md",".comet/current-change.json"].includes(e.toLowerCase()))&&U(`产物引用不能指向控制资源:${e}`)}function YT(e){(typeof e!="string"||!/^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/u.test(e)||e.split(".").some(t=>["__proto__","constructor","prototype"].includes(t)))&&U("产物字段选择器无效")}function bA(e){(!Array.isArray(e)||e.length>256)&&U("阶段产物契约必须是有界数组");let t=new Set;for(let r of e){(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(o=>!["workflowId","stepId","artifacts","noArtifactsReason","replaces"].includes(o)))&&U("阶段产物契约含未声明字段");let n=r;(typeof n.workflowId!="string"||!n.workflowId.trim()||typeof n.stepId!="string"||!n.stepId.trim()||t.has(Um(n.workflowId,n.stepId))||!Array.isArray(n.artifacts)||n.artifacts.length>64)&&U("阶段产物契约缺少唯一流程、步骤或产物列表"),t.add(Um(n.workflowId,n.stepId)),!n.artifacts.length&&(typeof n.noArtifactsReason!="string"||!n.noArtifactsReason.trim())&&U(`无强制产物的阶段需要说明原因:${Um(n.workflowId,n.stepId)}`),n.artifacts.length&&n.noArtifactsReason!==void 0&&U("必需产物与无产物声明不能同时存在"),n.replaces&&(!Array.isArray(n.replaces)||n.replaces.some(o=>typeof o!="string"||!o.trim())||new Set(n.replaces).size!==n.replaces.length)&&U("替代产物的步骤声明无效");let i=new Set;for(let o of n.artifacts){(!o||typeof o!="object"||Object.keys(o).some(s=>!["ref","refFrom","sha256From","nonEmpty","schema","requiredText","requiredHeadings"].includes(s))||!!o.ref==!!o.refFrom)&&U("必需产物需要唯一的 ref 或 refFrom"),o.ref!==void 0&&ZT(o.ref),o.refFrom!==void 0&&YT(o.refFrom),o.sha256From!==void 0&&YT(o.sha256From);let a=o.ref??`output:${o.refFrom}`;i.has(a)&&U("阶段产物引用重复"),i.add(a),o.nonEmpty!==void 0&&typeof o.nonEmpty!="boolean"&&U("nonEmpty 必须是布尔值");for(let s of[o.requiredText,o.requiredHeadings])s!==void 0&&(!Array.isArray(s)||!s.length||s.length>64||s.some(c=>typeof c!="string"||!c.trim()))&&U("产物内容检查必须是非空文本数组")}}}function TG(e,t){for(let r of t){let n=e.workflows.find(i=>i.id===r.workflowId);n?.steps[r.stepId]||U(`阶段产物契约引用不存在的步骤:${Um(r.workflowId,r.stepId)}`);for(let i of r.replaces??[])n.steps[i]||U(`替代产物的步骤不存在:${i}`);r.artifacts.length&&!["handoff","invoke_skill","call_tool","child_workflow"].includes(n.steps[r.stepId].type)&&U("必需产物必须绑定可回传结果的执行步骤"),n.steps[r.stepId].type==="child_workflow"&&r.artifacts.some(i=>!i.sha256From)&&U("子流程产物需要 sha256From,读取子流程结果中的实际摘要")}}async function e0(e,t,r){let n=t.artifacts.map(o=>{let a=o.ref??kA(r,o.refFrom);return ZT(a),{...o,ref:a,nonEmpty:o.nonEmpty!==!1}}),i=await KT(e,n);return{...i,artifacts:n.map(({ref:o})=>({uri:o,sha256:i.artifactHashes[o]}))}}async function t0(e,t,r){if(r.status!=="succeeded"||!t.artifacts.length)return;let n=await e0(e,t,r.output);for(let i=0;i<n.artifacts.length;i++){let o=n.artifacts[i],a=t.artifacts[i];if((a.sha256From?kA(r.output,a.sha256From):r.artifacts?.find(c=>c.uri===o.uri)?.sha256)!==o.sha256)throw new Error(`必需产物缺少当前结果的实际摘要或内容已变化:${o.uri}`)}}async function rd(e,t,r,n,i,o){let a=t.filter(c=>c.workflowId===r.workflow.id),s=new Set(a.find(c=>c.stepId===n)?.replaces??[]);for(let c of a)if(i[c.stepId])for(let l of c.replaces??[])i[c.stepId].sequence>(i[l]?.sequence??-1)&&s.add(l);for(let c of a){let l=i[c.stepId];if(!l||!c.artifacts.length||s.has(c.stepId))continue;let u=r.actions.find(f=>f.stepId===c.stepId&&["succeeded","failed"].includes(f.status)&&r.actionContexts[f.id]?.sequence===l.sequence);if(!u?.outcome||j(u.outcome.output)!==j(l.value))throw new Error(`依赖产物没有对应的原 Action 证据:${c.stepId}`);await t0(o?yA(e,o,r,u):e,c,u.outcome)}}function r0(e,t){let r=t.manifest.artifactContracts;if(r===void 0)return e;bA(r),TG(e,r);let n=(o,a)=>r.find(s=>s.workflowId===o.workflow.id&&s.stepId===a),i=async o=>{o.outcome.status==="succeeded"&&await rd(t.projectRoot,r,o.run,o.action.stepId,o.run.actionContexts[o.action.id]?.results??{},t.manifest);let a=n(o.run,o.action.stepId);a&&await t0(yA(t.projectRoot,t.manifest,o.run,o.action),a,o.outcome)};return{...e,executors:e.executors?.map(o=>({...o,...o.preflight?{async preflight(a,s,c){c&&await rd(t.projectRoot,r,c,a.stepId,c.actionContexts[a.id]?.results??{},t.manifest),await o.preflight?.(a,s,c)}}:{},async execute(a,s,c){let l=await o.execute(a,s,c),u=c?n(c,a.stepId):void 0;if(!u?.artifacts.length||l.status!=="succeeded")return l;try{let f=await e0(yA(t.projectRoot,t.manifest,c,a),u,l.output);return{...l,artifacts:[...(l.artifacts??[]).filter(d=>!f.artifacts.some(m=>m.uri===d.uri)),...f.artifacts]}}catch{return l}}})),validators:e.validators?.map(o=>({...o,async validate(a){let s=await o.validate(a);if(!s.accepted)return s;try{return await i(a),s}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}})),async validateOutcome(o){try{await i(o);let a=await e.validateOutcome?.(o)??{accepted:!0};return a.accepted&&await i(o),a}catch(a){return{accepted:!1,reason:a instanceof Error?a.message:String(a)}}}}}var kA,Um,n0=x(()=>{"use strict";Me();GT();wc();kA=(e,t)=>t.split(".").reduce((r,n)=>r&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Um=(e,t)=>`${e}/${t}`});import{promises as AA}from"node:fs";import _r from"node:path";import{createRequire as $G,isBuiltin as DG}from"node:module";function l0(e){return["completed","cancelled"].includes(e.status)&&!e.actions.some(t=>t.status==="pending"||Cn(t))&&e.children.length===0&&!e.ready.length&&!e.waits.some(t=>t.status==="pending")&&!(e.evidenceWaits??[]).some(t=>t.status==="pending")}function bc(e){return(typeof e!="string"||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e))&&U("应用身份必须是小写名称"),e}function u0(e,t){return _r.join(e,"applications",bc(t))}async function RA(e,t,r=!1,n=!1){let i=Ue(e),o=()=>{if(Ue(e)!==i)throw new R("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime")},a=async()=>{if(o(),!r){if(await Ei(e)!==i)throw new R("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime");o()}},s=vt({rootDir:u0(i,t),mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...n?{singleWriter:!0}:{}}),c=(u,f,d)=>{let m=s.prepareCompareAndSwap(u,f,d);return async()=>{if(o(),r)throw new R("READ_ONLY_OPERATION","应用诊断不能推进 Run");await a();let h=await s.settleRun(u);if(["closing","closed","reopening"].includes(h)){let g=await s.read(u);if(!g||g.revision!==f)return!1;h==="closing"&&await s.closeRun(u,g.revision),await s.reopenRun(u,g.revision)}let p=await m();return p&&d.application.base==="standalone"&&l0(d.run)&&await s.closeRun(u,d.revision),p}},l=async(u,f)=>(await a(),await s[f?"readProjection":"read"](u));return{queryScope:s.queryScope,read:u=>l(u,!1),readProjection:u=>l(u,!0),compareAndSwap:async(u,f,d)=>c(u,f,d)(),prepareCompareAndSwap:c,restoreCheckpoint:async(u,f,d)=>{if(o(),r)throw new R("READ_ONLY_OPERATION","应用诊断不能恢复 Run");if(await a(),await s.settleRun(u)==="closed"){let h=await s.read(u);if(!h||h.revision!==f)return!1;await s.reopenRun(u,h.revision)}return s.restoreCheckpoint(u,f,d)}}}async function d0(e,t,r){return vt({rootDir:u0(Ue(e),t),mirroredRevisionPaths:["run.revision"]}).readPartitionMetadata(r)}async function o0(e){let t=await Vo(e.application.packageRoot),r=SA(JSON.parse(Buffer.from(t["application.json"],"base64").toString("utf8")));if(r.id!==e.application.id||r.version!==e.application.version||r.base!==e.application.base||j({package:Mo(t),skills:r.skills.map(n=>({id:n.id,contentHash:n.contentHash}))})!==e.application.contentHash)throw new R("SCOPE_HELD",`固定占用应用定义无法验证:${e.application.id} / ${e.runId}`);return r}function a0(e,t,r){return e.actions.filter(n=>n.type==="invoke_skill"&&Cn(n)&&t.bindings.some(i=>{let o=t.skills.find(a=>a.id===i.skillId);return i.workflowId===e.workflow.id&&i.stepId===n.stepId&&i.usage==="action"&&o&&o.adapter.sideEffect!=="read"&&o.adapter.scope.length>0})).map(n=>({runId:e.runId,applicationContentHash:r,actionId:n.id,attempt:n.attempt,inputHash:n.inputHash,claimToken:n.claim?vm(n.claim.token):null}))}async function f0(e){let t=vn(e.run,e.runId),r=t.actions.filter(n=>n.type==="invoke_skill"&&Cn(n));if(!r.length)return!1;try{let n=await Vo(e.application.packageRoot),i=SA(JSON.parse(Buffer.from(n["application.json"],"base64").toString("utf8")));return j({package:Mo(n),skills:i.skills.map(o=>({id:o.id,contentHash:o.contentHash}))})!==e.application.contentHash?!0:r.some(o=>i.bindings.some(a=>{let s=i.skills.find(c=>c.id===a.skillId);return a.workflowId===t.workflow.id&&a.stepId===o.stepId&&a.usage==="action"&&s&&s.adapter.sideEffect!=="read"&&s.adapter.scope.length>0}))}catch{return!0}}function s0(e,t,r=!1){let n=_r.join(Ue(e),"applications",bc(t)),i=vt({rootDir:n,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...r?{singleWriter:!0}:{}});return hA({rootDir:n,read:o=>i.read(o),settle:o=>i.settleRun(o),holds:f0})}async function NA(e,t,r){return(await BG(e,t,r))?.run??null}async function BG(e,t,r){let n=await(await RA(e,t,!0)).read(r);if(!n)return null;if(n.application.id!==t||n.runId!==n.run.runId||n.revision!==n.run.revision)throw new R("INVALID_RUN","应用归属与 SDK Run 不一致");return n.run=vn(n.run,r),n}function SA(e){(!e||typeof e!="object"||Array.isArray(e))&&U("应用文件必须是 JSON 对象");let t=e;return t.artifactContracts!==void 0&&bA(t.artifactContracts),t.schema!=="comet.workflow.application.v1"&&U("应用格式不受支持,请重新生成 SDK 应用;原文件会保留"),t.definition!==void 0&&vA(t.definition),t.rule!==void 0&&(typeof t.rule!="string"||!t.rule.endsWith(".md")||_r.isAbsolute(t.rule)||t.rule.includes("\\")||t.rule.includes(":")||t.rule.split("/").some(r=>!r||r==="."||r===".."))&&U("应用规则 Rule 必须声明固定包内的 Markdown 相对路径"),bc(t.id),Db.includes(t.id)&&U(`应用身份 ${t.id} 与内置应用冲突,请使用独立名称`),(!t.version?.trim()||!["standalone","native","classic-full","classic-hotfix","classic-tweak"].includes(t.base)||!t.runtimeVersion?.trim()||!t.entrySkill?.trim()||!t.module?.endsWith(".mjs")||!Array.isArray(t.skills)||!Array.isArray(t.bindings))&&U("应用定义缺少版本、基础流程、入口或绑定"),t}async function EA(e,t,r){let n=await(await RA(await AA.realpath(e),t,!0)).readProjection(r);return n?_r.join(n.application.packageRoot,"application.json"):await gA({projectRoot:e,scope:"project"},bc(t))??await gA({projectRoot:e,scope:"user"},bc(t))??_r.join(e,".comet/applications",bc(t),"application.json")}function LG(e,t,r){return e.runtimeVersion!==t&&WG.includes(e.runtimeVersion)&&!!r&&(e.base==="native"||e.base.startsWith("classic-"))}async function Jm(e){let t=await AA.realpath(e.projectRoot),r=_r.resolve(e.file);_r.basename(r)!=="application.json"&&U("应用入口文件必须命名为 application.json");let n=await AA.realpath(_r.dirname(r));n===t&&U("应用包须放在独立目录,不能包含项目的运行状态");let i=await Vo(n),o=SA(JSON.parse(Buffer.from(i["application.json"]??"","base64").toString("utf8"))),a=QT(i,o);o.rule&&(!o.rule.endsWith(".md")||!i[o.rule]||!Buffer.from(i[o.rule],"base64").toString("utf8").trim())&&U("应用规则 Rule 必须是固定包内的非空 Markdown 文件");let s=uT(),c=LG(o,s,e.runId);o.runtimeVersion!==s&&!c&&U(`应用要求 Runtime ${o.runtimeVersion},当前是 ${s}`),(!i[o.entrySkill]||!i[o.module])&&U("应用入口 Skill 或执行模块缺失");let l=new Map;for(let E of o.skills)l.has(E.id)&&U(`重复 Skill 身份:${E.id}`),l.set(E.id,await fA(E,n));let u={id:o.id,version:o.version,base:o.base,runtimeVersion:o.runtimeVersion,projectRoot:t,packageRoot:n,contentHash:j({package:Mo(i),skills:[...l.values()].map(E=>({id:E.id,contentHash:E.contentHash}))})},f=async()=>{let E=await Vo(n),P=await Promise.all(o.skills.map(M=>fA(M,n)));if(j({package:Mo(E),skills:P.map(M=>({id:M.id,contentHash:M.contentHash}))})!==u.contentHash)throw new R("WORKFLOW_CHANGED","运行中的应用或依赖发生漂移;恢复原内容后继续原 Action")};if(e.expectedIdentity&&j(u)!==j(e.expectedIdentity))throw new R("WORKFLOW_CHANGED","恢复需要原固定应用包、依赖和工作区");let d=o.base!=="standalone",m=await RA(t,o.id,e.readOnly,d),h=E=>{if(j(E.application)!==j(u))throw new R("WORKFLOW_CHANGED","应用定义、执行/验证绑定、Skill 或工作区归属发生变化;请恢复原应用包和依赖后继续原 Run");if(E.revision!==E.run.revision||E.runId!==E.run.runId)throw new R("INVALID_RUN","应用归属与 SDK Run 不一致")},p;if(e.runId){let E=await m.readProjection(e.runId);E&&(h(E),p=(await va({...m,readProjection:async()=>E},e.runId)).run)}await Xb;for(let[E,P]of Object.entries(i)){if(!E.endsWith(".mjs"))continue;let W=Buffer.from(P,"base64").toString("utf8");for(let M of Yb(W)[0]){if(M.d===-2)continue;let H=M.n;if(H||U(`应用模块不能动态选择未固定的导入:${E}`),DG(H)||H==="@rpamis/comet/runtime"||H==="@rpamis/comet/applications"||H==="@rpamis/comet/applications/compiler"||H==="@rpamis/comet/applications/native"||H==="@rpamis/comet/applications/classic")continue;H.startsWith(".")||U(`应用模块依赖未固定:${E} -> ${H},请 bundle 后再加载`);let J=_r.posix.normalize(_r.posix.join(_r.posix.dirname(E),H));(!i[J]||J.startsWith("../"))&&U(`应用模块依赖缺失或越过包目录:${E} -> ${H}`),!J.endsWith(".mjs")&&!J.endsWith(".json")&&U(`执行依赖必须是可检查的 .mjs 或 JSON:${E} -> ${H},请先 bundle`)}}let g=i0.get(n);g&&g!==u.contentHash&&U("当前进程已加载不同的应用实现,请在新进程加载新版本"),i0.set(n,u.contentHash);let v=$G(r)(_r.join(n,o.module));typeof v.createApplication!="function"&&U("应用模块必须导出 createApplication");let w={manifest:structuredClone(o),skills:l,projectRoot:t,packageRoot:n,identity:u,createSkillExecutor:E=>TT({manifest:o,skills:l,projectRoot:t},E)};if(p&&!e.useLatestDefinition){let E;Object.defineProperty(w,"existingRun",{enumerable:!0,get:()=>E??=br(p)})}let y=await v.createApplication(w);(!y||!Array.isArray(y.workflows)||!y.workflows.length)&&U("应用模块必须提供完整 SDK 工作流"),y=r0(y,{manifest:o,projectRoot:t});let b=y.workflows.map(An);a&&(c?p&&!wA(a,p)&&!wA({...a,workflows:b},p)&&U("旧固定应用 Run 不匹配原定义或当前业务定义"):UT(a,b));let N=new Set;for(let E of o.bindings){let P=`${E.workflowId}/${E.stepId}/${E.usage}${E.usage==="guidance"?`/${E.skillId}`:""}`;E.workspaceFrom!==void 0&&!/^[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)*$/u.test(E.workspaceFrom)&&U(`工作区输入路径无效:${P}`),N.has(P)&&U(`重复 Skill 绑定:${P}`),N.add(P);let W=b.find(J=>J.id===E.workflowId),M=W?.steps[E.stepId],H=l.get(E.skillId);if((!M||!H)&&U(`绑定的工作或 Skill 不存在:${P}`),(!E.capability?.trim()||!H.adapter.review.capabilities.some(J=>J.id===E.capability))&&U(`真实 Skill 没有已审查的所需能力:${P}`),E.usage==="guidance"){H.adapter.kind!=="guidance"&&U("只有只读指导 Skill 可附加为 guidance");continue}if(E.usage==="subworkflow"){(H.adapter.kind!=="subworkflow"||M.type!=="child_workflow")&&U("完整流程必须绑定显式 child_workflow");continue}if((E.usage!=="action"||!["action","check"].includes(H.adapter.kind)||M.type!=="invoke_skill"||M.ref!==E.skillId)&&U(`Skill 工作类型或引用不匹配:${P}`),H.adapter.controlsApproval&&U("接管审批的 Skill 必须适配为隔离的子流程"),(M.outputSchema===void 0||j(M.outputSchema)!==j(H.adapter.outputSchema))&&U(`Skill 输出与工作流契约不匹配:${P}`),H.adapter.completion!=="self-report"&&!(H.adapter.completion==="machine-check"&&o.artifactContracts?.some(J=>J.workflowId===E.workflowId&&J.stepId===E.stepId&&J.artifacts.length))&&(!M.validator||!y.validators?.some(J=>J.id===M.validator?.id&&J.version===M.validator.version))&&U(`机器检查或独立评审需要真实验证器:${P}`),H.adapter.requiredCapabilities.some(J=>!M.requiredCapabilities?.includes(J))&&U(`Skill 必需宿主能力未传到 Action:${P}`),H.adapter.sideEffect!=="read"){let J=E.authorizationFrom?W.steps[E.authorizationFrom]:void 0,ce=E.authorizationChoices??["approved"];(J?.type!=="ask_user"||!Array.isArray(ce)||!ce.length||ce.some(ne=>typeof ne!="string"||!J.choices.includes(ne)))&&U(`有副作用的 Skill 缺少有效父流程审批:${P}`)}H.adapter.sideEffect==="external"&&M.retry!=="reconcile"&&U(`外部 Skill 必须先核对再重试:${P}`)}for(let E of b){let P=(H,J,ce)=>{H&&!J?.some(ne=>ne.id===H.id&&ne.version===H.version)&&U(`${ce} 未注册固定实现:${H.id}@${H.version}`)};P(E.transitionHandler,y.transitionHandlers,"转移处理器"),P(E.stateValidator,y.stateValidators,"状态验证器");for(let H of Object.values(E.commands??{}))P(H.validator,y.commandValidators,"命令验证器");for(let[H,J]of Object.entries(E.steps))J.type==="await_evidence"?P(J.validator,y.evidenceValidators,"证据验证器"):P(J.validator,y.validators,"工作验证器"),J.type==="invoke_skill"&&!o.bindings.some(ce=>ce.workflowId===E.id&&ce.stepId===H&&ce.usage==="action")&&U(`Skill Action 缺少适配绑定:${E.id}/${H}`);let W=o.bindings.filter(H=>H.workflowId===E.id&&H.usage==="action"&&l.get(H.skillId).adapter.sideEffect!=="read"),M=(H,J,ce=new Set)=>H===J?!0:ce.has(H)?!1:(ce.add(H),E.transitions.some(ne=>ne.from===H&&M(ne.to,J,ce)));for(let H=0;H<W.length;H++)for(let J of W.slice(H+1)){let ce=W[H];l.get(ce.skillId).adapter.sideEffect==="write"&&l.get(J.skillId).adapter.sideEffect==="write"&&!!ce.workspaceFrom!=!!J.workspaceFrom&&!M(ce.stepId,J.stepId)&&!M(J.stepId,ce.stepId)&&U(`并行写入不能混用声明工作区和默认范围:${ce.stepId} / ${J.stepId}`),!ce.workspaceFrom&&!J.workspaceFrom&&l.get(ce.skillId).adapter.scope.some(ne=>l.get(J.skillId).adapter.scope.some(me=>l.get(ce.skillId).adapter.sideEffect==="write"&&l.get(J.skillId).adapter.sideEffect==="write"?Mm(_r.resolve(t,ne),_r.resolve(t,me)):me===ne))&&!M(ce.stepId,J.stepId)&&!M(J.stepId,ce.stepId)&&U(`并行 Skill 的写入范围冲突:${ce.stepId} / ${J.stepId},请声明隔离或执行顺序`)}}let A=()=>{if(e.readOnly)throw new R("READ_ONLY_OPERATION","应用诊断不能恢复或推进 Run")},S=Ue(t),_=async E=>{if(Ue(t)!==S)throw new R("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime");return await Ei(t),E()},Q=_r.join(S,"applications",o.id),F=vt({rootDir:Q,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...d?{singleWriter:!0}:{}}),K=(E,P)=>P.type==="invoke_skill"&&o.bindings.some(W=>{let M=l.get(W.skillId);return W.workflowId===E.workflow.id&&W.stepId===P.stepId&&W.usage==="action"&&M&&M.adapter.sideEffect!=="read"&&M.adapter.scope.length>0}),Z=hA({rootDir:Q,read:E=>F.read(E),settle:E=>F.settleRun(E),holds:E=>E.application.contentHash!==u.contentHash?f0(E):vn(E.run,E.runId).actions.some(P=>Cn(P)&&K(E.run,P))}),re=E=>JSON.stringify(E?.actions.filter(P=>K(E,P)&&Cn(P)).map(P=>[P.id,P.status,P.claim?.token,P.inputHash]).sort()??[]),X=E=>a0(E,o,u.contentHash),Oe=async E=>{let P=await s0(t,E,E===o.id&&d).holders(),W=[];for(let M of P){let H=M.application.id===u.id&&M.application.contentHash===u.contentHash?o:await o0(M);W.push(...a0(vn(M.run,M.runId),H,M.application.contentHash))}return W},Be=(E=!1)=>iT(S,o.id,Oe,E),B=async(E,P,W=!1)=>{if(!o.bindings.some(ne=>{if(ne.workflowId!==E.workflow.id||ne.stepId!==P.stepId||ne.usage!=="action")return!1;let me=l.get(ne.skillId);return me&&me.adapter.sideEffect!=="read"&&me.adapter.scope.length>0}))return[];let H=Fm({manifest:o,projectRoot:t},E,P);for(let ne of await Be(W)){if(ne===o.id||W&&!await aT(S,ne))continue;let me=await s0(t,ne).holders();for(let fe of me){let k=vn(fe.run,fe.runId);if(fe.application.id!==ne||fe.application.projectRoot!==t)throw new R("SCOPE_HELD",`应用 ${ne} 的固定占用身份无法验证:${k.runId}`);let C=await o0(fe);for(let $ of k.actions.filter(Cn))if(Fm({manifest:C,projectRoot:t},k,$).some(T=>H.some(z=>T.write&&z.write?Mm(T.ref,z.ref):T.ref===z.ref))){let T=new R("SCOPE_HELD",`写入范围仍由应用 ${ne} 的 Run ${k.runId} / Action ${$.id} 占用;请停止原执行或提交真实结果`);throw Object.assign(T,{blockedRunIds:[k.runId],blockedApplicationIds:[ne]}),T}}}let J=await Z.holders(),ce=[];for(let ne of J){if(ne.runId===E.runId)continue;let me=vn(ne.run,ne.runId);if(ne.application.contentHash!==u.contentHash)throw new R("SCOPE_HELD",`其他固定版本仍占用应用工作区:${me.runId}`);ce.push(me)}return ce},ie={queryScope:m.queryScope,async readProjection(E){await f();let P=await m.readProjection(E);return P?(h(P),P.run):null},async read(E){await f();let P=await m.read(E);return P?(h(P),P.run):null},async restoreCheckpoint(E,P,W){return W=structuredClone(W),A(),await f(),_(async()=>{await f();let H=await m.read(E);if(H&&h(H),W.runId!==E||W.actions.some(ne=>ne.status==="running"))throw new R("INVALID_RUN","应用恢复必须使用同一 Run 的 portable checkpoint,活跃领取须先转为 unknown");let J=o.base==="native"?"native":o.base.startsWith("classic-")?"classic":null;if(J){let ne=await Mi(t,J,E);if(!ne||ne.format!=="sdk"||ne.application!==u.id||ne.runId!==E)throw new R("INVALID_RUN","恢复 Run 前须验证相同的固定应用和 change 归属")}let ce={runId:E,revision:W.revision,application:u,run:W};h(ce),await oT(S,o.id,E,X(W)),await Be(!0);for(let ne of W.actions.filter(me=>Cn(me)&&me.type==="invoke_skill"))yc({manifest:o,skills:l,projectRoot:t},W,ne,await B(W,ne,!0));await Kb(S,o.id,X(W),!0);try{return await Z.begin(E,!H),await m.restoreCheckpoint(E,P,ce)}finally{await Z.finish(),await Gb(S,o.id,Oe,!0)}})},async compareAndSwap(E,P,W){A(),await f(),W=structuredClone(W);let M=m.prepareCompareAndSwap(E,P,{runId:E,revision:W.revision,application:u,run:W}),H=await m.read(E),J=(await Z.inspect())?.state!=="ready"||!H||re(H.run)!==re(W)||l0(W),ce=async()=>{await f();let ne=await m.read(E);if(ne&&h(ne),ne||await Be(),(ne?.revision??null)!==P)return!1;for(let me of W.actions)if(me.status==="running"&&!ne?.run.actions.some(fe=>fe.id===me.id&&fe.status==="running"&&fe.claim?.token===me.claim?.token)&&(yc({manifest:o,skills:l,projectRoot:t},W,me,await B(W,me)),o.artifactContracts&&await rd(t,o.artifactContracts,W,me.stepId,W.actionContexts[me.id]?.results??{},o),me.type==="invoke_skill")){kc({manifest:o,skills:l},me,W);let fe=y.executors?.find(k=>k.id===me.claim?.executorId);if(!fe)throw new R("EXECUTOR_UNAVAILABLE","Skill 必须由应用已配置的执行端口领取");if(fe.supports(pA(me))!==!0||!fe.preflight)throw new R("EXECUTOR_UNSUPPORTED","Skill 执行端口缺少对应的领取预检");if(me.requiredCapabilities.some(k=>!fe.capabilities.includes(k)))throw new R("CAPABILITY_REQUIRED","已配置执行端口缺少 Skill 所需能力")}if(o.artifactContracts)for(let me of W.waits)me.status==="resolved"&&me.decision?.choice==="approved"&&ne?.run.waits.some(fe=>fe.id===me.id&&fe.status==="pending")&&await rd(t,o.artifactContracts,W,me.stepId,me.results,o);if((ne?.revision??null)!==P||!J&&re(ne?.run)!==re(W))return!1;if(J){let me=new Set(ne?X(ne.run).map(j):[]),fe=X(W).filter(k=>!me.has(j(k)));fe.length&&(await Be(),await Kb(S,o.id,fe))}try{return J&&await Z.begin(E,!ne),await M()}finally{J&&(await Z.finish(),await Gb(S,o.id,Oe))}};return J?_(ce):ce()}},pe=y.wrapStore?y.wrapStore(ie,u,{readOnly:e.readOnly}):ie;if(e.runId&&!p&&!e.readOnly&&y.wrapStore){let P=await pe.read(e.runId)?await m.read(e.runId):null;if(P)return h(P),Jm(e)}let it={...y,...o.base==="standalone"?{inspectHook:MT({projectRoot:t,packageRoot:n,manifest:o,skills:l,custom:y.inspectHook,readChild:async E=>(await cr({...y,store:pe}).inspectProjection(E)).run})}:{},async validateOutcome(E){if(E.action.type==="invoke_skill")try{kc({manifest:o,skills:l},E.action,E.run)}catch(P){return{accepted:!1,reason:P instanceof Error?P.message:"Skill 结果不满足应用契约"}}return y.validateOutcome?.(E)??{accepted:!0}}},I=cr({...it,store:pe});return c&&await I.inspect(e.runId),{manifest:o,definition:a,identity:u,implementation:it,skills:l,store:pe}}var i0,WG,Ac=x(()=>{"use strict";ga();yr();sT();cT();Me();Ou();dT();Bo();Xt();wc();Hm();$T();qT();VT();FT();JT();n0();i0=new Map;WG=["0.5.2","0.5.3"]});import qG from"node:path";async function nd(e){let t=[],r=new Set,n=e.ownerObservation===void 0?await qe(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,i=vt({singleWriter:!0,rootDir:qG.join(Ue(e.projectRoot),"sdk-runs/native")}),o=new Set;async function a(s){if(!o.has(s.runId)){o.add(s.runId);for(let c of s.actions)["pending","running","unknown"].includes(c.status)&&(r.add(s.runId),t.push({runId:s.runId,actionId:c.id,stepId:c.stepId,attempt:c.attempt,inputHash:c.inputHash,reason:"原业务任务仍待完成或由 Agent 核对结果"}));for(let c of s.children){let l=n&&n.application!=="native"?await NA(e.projectRoot,n.application,c.runId):await i.read(c.runId);if(l)["cancelled","completed"].includes(l.status)?await a(l):r.add(c.runId);else{let u=s.actions.find(d=>d.id===c.actionId);u?.type==="child_workflow"&&u.status==="cancelled"&&u.attempt===1&&!u.claim&&!u.outcome&&u.receipts.length===0&&u.reconciliations.length===0||r.add(c.runId)}}}}return await a(e.run),{quiescent:t.length===0&&r.size===0,outstandingActions:t,outstandingRuns:[...r]}}async function Qi(e){if(e.run.status!=="cancelled")return null;let{quiescent:t,outstandingActions:r,outstandingRuns:n}=await nd(e),i=e.ownerObservation===void 0?await qe(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,o=t?await Ur(e.projectRoot):null,a=!!(o?.status==="selected"&&o.selection.change===e.run.runId&&(i?.application==="native"?o.selection.workflow==="native":i&&o.selection.workflow==="application"&&o.selection.applicationId===i.application)),s=null;return a&&(s={reason:"业务调度已取消,当前选择尚未释放;请核对工作区事务并重试清理。",inspectionCommand:"comet native doctor --json",repairCommand:"comet native doctor --repair --json",finishCommand:`comet native doctor ${e.run.runId} --repair --json`}),{status:t&&!a?"cancelled":"cancelling",reason:e.run.reason??null,quiescent:t,cleanupRequired:a,cleanup:s,outstandingActions:r,outstandingRuns:n}}async function p0(e){let t=e.cancellationObservation===void 0?await Qi(e):e.cancellationObservation;if(!t)return null;let r=e.state.language==="zh-CN";return{continuation:{...e.base,status:t.status,disposition:t.status==="cancelled"?"done":"blocked",mode:t.status==="cancelled"?"done":"reconcile",requiresUserDecision:!1,action:"none",commandArgs:t.status==="cancelled"?null:t.cleanupRequired?["comet","native","doctor","--json"]:["comet","native","doctor",e.state.name,"--repair"],requiredInputs:t.quiescent?[]:["original-platform-task-result"],inputOptions:[],commandAlternatives:[],runnerAction:{...e.base.runnerAction,kind:"none"},userCommunication:{required:!1,message:null,suggestedReply:null,agentInstruction:t.cleanupRequired?r?"业务调度已取消,但当前选择尚未释放,清理仍未完成。先运行全局 Native doctor 查看根变更锁的原持有者、锁龄和待恢复事务;确认原持有者已停止且达到现有接管条件后再显式修复,最后重试此任务的 doctor --repair。不得删锁或跳过原有保护。":"Scheduling is cancelled, but current selection release is still pending. Inspect global Native doctor for the root mutation lock owner, age, and unfinished transactions. Confirm the owner stopped and existing takeover conditions are met before explicit repair, then retry this change’s doctor --repair. Do not delete locks or bypass their protections.":t.quiescent?r?"业务任务已取消,代码与历史保留。原平台任务的取消和进程清理由 Agent 通过平台工具核对;Comet 不声明原进程已经停止。":"Business scheduling is cancelled; code and history are retained. The Agent must verify original task cancellation and process cleanup through the platform. Comet does not certify process termination.":r?"任务已停止派发。通过原 Agent 平台核对尚未完成的任务、实际副作用、取消及清理结果;沿用原业务任务记录,不按历史 PID 杀进程,不生成停止回执。":"Scheduling is cancelled. Inspect unfinished tasks, actual side effects, cancellation, and cleanup through their original Agent platform. Keep the original business task records; do not kill historical PIDs or create stop receipts."}},cancellation:t}}var Ui=x(()=>{"use strict";yr();Me();Ou();Ac();Xt();Bo();Ae()});function h0(e,t){return CA[e][t]}function y0(e,t){return g0[e][t]??v0[e][t]}function _A(e){return w0.get(e.trim().toLocaleLowerCase("en-US"))??null}function FG(e){return zm[e].section}function id(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact===!1&&r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(n=>{if(n!=="scope")return`# ${h0(e,n)}
281
+ `;let i=[`# ${h0(e,n)}
282
+ `];return i.push(`## ${FG(e)}
283
+ `),i.push(Jr(e,`<!-- Add only needed level-three categories (Created, Modified, Deleted, Not created), with paths and responsibilities. Omit unused categories. -->
284
+ `,`<!-- 按实际改动添加三级标题(新建、修改、删除、明确不建),写明路径与职责;无内容的类别可省略。 -->
285
+ `)),i.join(`
286
+ `)}).join(`
287
+ `)}function Jr(e,t,r){return e==="zh-CN"?r:t}var CA,g0,v0,w0,m0,VG,MG,zm,Rc=x(()=>{"use strict";CA={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},g0={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},v0={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},w0=new Map,m0=new Map,VG=new Set,MG=new Map,zm={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(CA)){for(let[t,r]of Object.entries(CA[e]))w0.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(g0[e]))m0.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(v0[e]))m0.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(zm)){VG.add(zm[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(zm[e].subsections))MG.set(r.toLocaleLowerCase("en-US"),t)}});import{createHash as HG}from"node:crypto";function za(e){return e.replaceAll(`\r
288
+ `,`
289
+ `).replaceAll("\r",`
290
+ `)}function UG(e){return HG("sha256").update(za(e)).digest("hex")}function N0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new St(`${t} must be an object`);return e}function S0(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new St(`${r} has unknown field(s): ${n.join(", ")}`)}function E0(e,t){if(typeof e!="string"||e.trim().length===0)throw new St(`${t} must be a non-empty string`);return e.trim()}function k0(e,t){if(e!==void 0){if(typeof e!="string")throw new St(`${t} must be text`);return za(e).replace(/^\n+|\n+$/gu,"")}}function b0(e,t){let r=E0(e,t);if(!R0.test(r))throw new St(`${t} is not a valid stable requirement ID`);return r}function JG(e,t){let r=E0(e,t);if(!QG.test(r))throw new St(`${t} is not a valid capability ID`);return r}function zG(e,t){let r=`Native delta operations[${t}]`,n=N0(e,r);S0(n,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let i=b0(n.id,`${r}.id`),o=n.operation;if(!["add","modify","remove","rename"].includes(String(o)))throw new St(`${r}.operation is invalid`);let a=o,s=n.to_id===void 0?void 0:b0(n.to_id,`${r}.to_id`),c=k0(n.title,`${r}.title`),l=k0(n.body,`${r}.body`);if(a==="add"){if(s!==void 0||!l?.trim())throw new St(`${r} add requires body and forbids to_id`)}else if(a==="modify"){if(s!==void 0||!l?.trim())throw new St(`${r} modify requires body and forbids to_id`)}else if(a==="remove"){if(s!==void 0||c!==void 0||l!==void 0)throw new St(`${r} remove forbids to_id, title, and body`)}else if(s===void 0||s===i||l==="")throw new St(`${r} rename requires a different to_id`);return{id:i,operation:a,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l}}}function KG(e){let t=N0(e,"Native delta");if(S0(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==IA)throw new St(`Native delta schema must be ${IA}`);let r=JG(t.capability,"Native delta capability");if(!Array.isArray(t.operations))throw new St("Native delta operations must be an array");let n=t.operations.map(zG),i=new Set;for(let[o,a]of n.entries()){let s=[a.id,...a.to_id===void 0?[]:[a.to_id]];for(let c of s){if(i.has(c))throw new St(`Native delta operations contain duplicate or overlapping requirement ID ${c} at ${o}`);i.add(c)}}return{schema:IA,capability:r,base_version:Number.isSafeInteger(t.base_version)&&Number(t.base_version)>0?Number(t.base_version):1,operations:n}}function GG(e){let t=(0,PA.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new St(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function zr(e){return KG(typeof e=="string"?GG(e):e)}function YG(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function XG(e){let t=[],r=null;for(let[n,i]of e.entries()){let o=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(i.trimEnd());if(o){r?o[1][0]===r.marker&&o[1].length>=r.length&&o[2].trim().length===0&&(r=null):r={marker:o[1][0],length:o[1].length};continue}if(r)continue;let a=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(i);if(!a)continue;let s=a[3];if(!R0.test(s))throw new St(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:n,level:a[2].length,id:s,title:a[4]?.trim()??""})}return t}function Km(e){let t=za(e),r=t.split(`
291
+ `),n=XG(r),i=[],o=new Set;for(let l of n){if(o.has(l.id))throw new St(`Native total Spec contains duplicate requirement ID ${l.id}`);o.add(l.id);let u=r.length;for(let f=l.line+1;f<r.length;f+=1){if(n.some(m=>m.line===f)){u=f;break}let d=YG(r[f]);if(d!==null&&d<=l.level){u=f;break}}i.push({start:l.line,end:u,marker:l})}let a=new Map;for(let l of i){let u=`${r.slice(l.start,l.end).join(`
292
+ `)}${l.end<r.length?`
293
+ `:""}`,f=r.slice(l.start+1,l.end).join(`
294
+ `).replace(/^\n/u,"").replace(/\n+$/u,"");a.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:f,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of i)s.push(r.slice(c,l.start).join(`
295
+ `)),c=l.end;return s.push(r.slice(c).join(`
296
+ `)),{text:t,lines:r,requirements:a,legacyText:s.join(`
297
+ `)}}function C0(e){return UG(e)}function Gm(e,t,r,n){let i=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,o=za(n).replace(/\n+$/u,"");return[i,"",...o.split(`
298
+ `),"",""].join(`
299
+ `)}function xA(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function Ym(e,t){if(e.operation==="rename"){if(!t)throw new St(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function ZG(e,t,r){let n=Km(e),i=[...n.lines],o=n.requirements.get(t.id);if(!o)throw new St(`Requirement target disappeared: ${t.id}`);return i.splice(o.startLine,o.endLine-o.startLine,...r.split(`
300
+ `)),i.join(`
301
+ `)}function eY(e,t){let r=za(e),n=r.length===0||r.endsWith(`
302
+
303
+ `)?"":`
304
+ `,i=`${r}${n}`;return`${i.endsWith(`
305
+ `)||i.length===0?i:`${i}
306
+ `}${t}`}function tY(e,t){if(e.operation==="add"||e.operation==="modify"){let o=t.requirements.get(e.id);if(!o)return!1;let a=Ym(e,e.operation==="modify"?o:void 0);return o.raw===Gm(a.level,a.id,a.title,a.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),n=t.requirements.get(e.id);if(!r||n)return!1;let i=Ym(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===Gm(i.level,i.id,i.title,i.body)}function _0(e){let t=za(e.baselineMarkdown),r=[],n=[];for(let o of e.delta.operations){let a=Km(t),s=a.requirements.get(o.id);if(e.allowAlreadyApplied&&tY(o,a)){n.push({id:o.id,operation:o.operation,status:"already-applied",targetIds:xA(o)});continue}if(o.operation==="add"){if(s)throw new od([o.id],`Native delta add conflicts with existing requirement ${o.id}`);let c=Ym(o,void 0);t=eY(t,Gm(c.level,c.id,c.title,c.body))}else{if(!s)throw new od([o.id],`Native delta ${o.operation} target does not exist: ${o.id}`);let c=Ym(o,s);if(o.operation==="rename"&&Km(t).requirements.has(o.to_id))throw new od([o.id,o.to_id],`Native delta rename destination already exists: ${o.to_id}`);if(o.operation==="remove"){let l=[...Km(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
307
+ `)}else t=ZG(t,s,Gm(c.level,c.id,c.title,c.body))}r.push(...xA(o)),n.push({id:o.id,operation:o.operation,status:"changed",targetIds:xA(o)})}return{markdown:za(t),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:n}}function I0(e){return _0({baselineMarkdown:e.baselineMarkdown,delta:zr(e.delta),allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}function ad(e){return _0({baselineMarkdown:e.currentMarkdown,delta:zr(e.delta),allowAlreadyApplied:!0,rebased:!1})}var PA,IA,A0,QG,R0,St,od,Ka=x(()=>{"use strict";PA=tr(jr(),1),IA="comet.native.delta.v1",A0="delta.yaml",QG=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,R0=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,St=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},od=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Xm,OA,TA,Zm=x(()=>{"use strict";Xm="comet.native.v3",OA="comet.native.v2",TA="comet.native.v1"});function sd(e){if(!P0.test(e))throw new Error(`Invalid Native change name: ${e}`)}function jA(e){if(!P0.test(e))throw new Error(`Invalid Native capability id: ${e}`)}var x0,loe,nY,uoe,P0,cd=x(()=>{"use strict";Zm();x0=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],loe=new Set(x0),nY=new Set([...x0,"minimum_runtime_version","revision"]),uoe=new Set([...nY,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),P0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as iY}from"crypto";function Un(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function oY(e,t){t.has(e)&&Un("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||Un("sparse arrays are not supported");return(r.length!==e.length||r.some((n,i)=>n!==String(i)))&&Un("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Un("symbol properties are not supported"),`[${e.map(n=>$A(n,t)).join(",")}]`}finally{t.delete(e)}}function aY(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Un("only plain objects are supported"),t.has(e)&&Un("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Un("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(a=>{let s=n[a];return(!s||!("value"in s))&&Un("accessor properties are not supported"),`${JSON.stringify(a)}:${$A(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function $A(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Un("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?oY(e,t):aY(e,t);case"bigint":case"function":case"symbol":case"undefined":return Un(`${typeof e} values are not supported`)}return Un("unsupported value type")}function sY(e){return $A(e,new Set)}function ld(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return iY("sha256").update(`${e}
308
+ ${sY(t)}`).digest("hex")}var eh=x(()=>{"use strict"});function j0(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function O0(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let n=r[1][0];return t===null?{marker:n,length:r[1].length}:n===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function T0(e){return e.includes("-->")||e.includes("--!>")}function*th(e){let t=null,r=!1,n=null,i=new Set(["code","pre","script","style","svg","template"]),o=e.replace(/\r\n?/gu,`
309
+ `),a=0,s=0;for(;a<=o.length;){let c=o.indexOf(`
310
+ `,a),l=c===-1?o.slice(a):o.slice(a,c);if(yield{line:l,body:t===null&&!r&&n===null,index:s},s+=1,t!==null)t=O0(l,t);else if(r)T0(l)&&(r=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=O0(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!T0(d))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);m&&i.has(m[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(d)&&(n=m[1])}}}if(c===-1)break;a=c+1}}function ud(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function BA(e,t,r,n=[],i="content-hash"){let o=ud(r),a=t.replaceAll("\\","/").trim(),s=n.map(ud);if(o.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:i==="content-hash"?`acceptance-${ld(cY,{kind:e,source:a,context:s,text:o})}`:"",kind:e,source:a,context:s,text:o}}function WA(e,t,r="content-hash"){let n=new Set;for(let i of e){let o=r==="content-hash"?i.id:JSON.stringify([i.kind,i.source,i.context,i.text]);if(n.has(o))throw new Error(`${t} contains duplicate acceptance criteria`);n.add(o)}return e}function lY(e){let t=null,r=null,n=0,i=0;for(let{line:o,body:a,index:s}of th(e)){i=s+1;let c=a?j0(o):null;c?.level===1&&(_A(c.text)==="acceptanceExamples"?(n+=1,n===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(n===0||t===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??i}}function $0(e,t="brief.md",r=DA.maxCriteria,n="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let i=lY(e);if(i===null)return[];let o=null;for(let{line:l,body:u,index:f}of th(e)){if(f<i.start||f>=i.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let m=d[1].length;o=o===null?m:Math.min(o,m)}let a=[],s=null,c=()=>{if(s!==null){if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);a.push(s)}};for(let{line:l,body:u,index:f}of th(e)){if(f<i.start||f>=i.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===o?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),WA(a.map(l=>BA("brief-example",t,l.join(`
311
+ `),[],n)),"Brief",n)}function D0(e,t="brief.md",r=DA.maxCriteria,n="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let i=new Cr().blockTokens(e.replace(/\r\n?/gu,`
312
+ `)),o=i.flatMap((c,l)=>c.type==="heading"&&_A(c.text)==="acceptanceExamples"?[{index:l,depth:c.depth}]:[]);if(o.length===0)return[];if(o.length!==1)throw new Error("Brief must contain exactly one Acceptance examples section");let a=o[0],s=[];for(let c of i.slice(a.index+1)){if(c.type==="heading"&&c.depth<=a.depth)break;if(c.type==="list")for(let l of c.items){if(s.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let u=l.raw.replace(/^ {0,3}(?:[-*+]|\d{1,9}[.)])[ \t]*/u,"");s.push(BA("brief-example",t,u,[],n))}}return WA(s,"Brief",n)}function B0(e,t="spec.md",r=DA.maxCriteria,n="content-hash",i={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let o=[],a=[],s=null,c=()=>{if(s===null)return;if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(i.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");o.push({...BA("spec-scenario",t,[s.title,...s.body].join(`
313
+ `),s.context,n),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of th(e)){let f=u?j0(l):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(c();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let m=ud(d[1]);if(m.length===0)throw new Error("Scenario title must not be empty");s={level:f.level,title:m,body:[],context:a.map(h=>h.text)}}else if(f){for(s!==null&&f.level<=s.level?c():s!==null&&s.body.push(l);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else s!==null&&u&&s.body.push(l)}return c(),WA(o,"Specification",n)}var cY,voe,DA,W0=x(()=>{"use strict";dA();Rc();eh();cY="comet.native.acceptance.v1",voe=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),DA=Object.freeze({maxCriteria:1024})});import L0 from"node:path";function q0(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||L0.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||L0.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function uY(e,t){return e.localeCompare(t,"en")}function V0(e){let t=q0(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((s,c)=>uY(s.capability,c.capability));if(new Set(r.map(s=>s.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=(e.legacyBriefBoundaries?$0:D0)(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:s,text:c})=>({source:s,text:c})),o=i.length;for(let s of r){let c=q0(s.source,`Native spec source for ${s.capability}`);for(let l of B0(s.markdown,c,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(l.briefAcceptanceRef!==void 0){let u=Number(l.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(u)||u<0||u>=o)throw new Error(`Native Spec references unknown brief acceptance ${l.briefAcceptanceRef}: ${c}`);continue}i.push({source:c,text:l.text})}}let a=new Set;for(let s of i){s.text=ud(s.text);let c=s.text;if(a.has(c))throw new Error(`Native acceptance contains a duplicate criterion: ${s.text}`);a.add(c)}if(i.length===0)throw new Error(`Native change must define at least one acceptance criterion. In ${t}, write each criterion as a top-level Markdown list item under Acceptance examples, for example: "- Input hello prints Words: 1." Keep requested tables; a table alone does not create formal acceptance items. Alternatively use complete Scenario: blocks in the target Specs. Add the explicit criteria without changing their meaning, then retry the same Shape step; do not recreate the change.`);return i.map((s,c)=>({id:`A${c+1}`,source:s.source,text:s.text}))}var rh=x(()=>{"use strict";W0()});function wY(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yY(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function H0(e){let t=wY(e,"Native portable migration transaction"),r=Object.keys(t).filter(n=>!pY.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==M0)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!hY.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!mY.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!vY.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!gY.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:M0,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:yY(t.createdAt,"Native portable migration transaction createdAt")}}var M0,pY,mY,hY,gY,vY,Q0=x(()=>{"use strict";cd();rh();Ae();Ii();Zs();Zm();M0="comet.native.portable-migration.v1",pY=new Set(["schema","id","change","fromSchema","status","createdAt"]),mY=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hY=/^[a-z0-9][a-z0-9-]{7,127}$/u,gY=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),vY=new Set([TA,OA,Xm])});import qA from"node:path";function K0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function G0(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function LA(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function U0(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function CY(e,t){let r=`Native portable Archive spec_changes[${t}]`,n=K0(e,r);if(G0(n,EY,r),typeof n.capability!="string"||!z0.test(n.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(n.operation)))throw new Error(`${r}.operation is invalid`);let i=n.operation,o=n.delta_source;if(o!==void 0&&(typeof o!="string"||o.length===0||o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||o.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let a=LA(n.base_hash,`${r}.base_hash`),s=U0(n.delta_content,`${r}.delta_content`),c=U0(n.source_content,`${r}.source_content`),l=LA(n.expected_target_hash,`${r}.expected_target_hash`),u=LA(n.result_hash,`${r}.result_hash`),f=o!==void 0;if(f&&(s==null||c===void 0||c===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!f&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(f&&zr(s).capability!==n.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(i==="remove"){if(n.source!==null||n.content!==null||o!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null,...a===void 0?{}:{base_hash:a},...l===void 0?{}:{expected_target_hash:l}}}if(typeof n.source!="string"||n.source.length===0||n.source.includes("\\")||n.source.startsWith("/")||/^[A-Za-z]:/u.test(n.source)||n.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);return{capability:n.capability,operation:i,source:n.source,content:n.content,...o===void 0?{}:{delta_source:o},...a===void 0?{}:{base_hash:a},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function _Y(e){let t=K0(e,"Native portable Archive transaction");if(G0(t,SY,"Native portable Archive transaction"),t.schema!==nh)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!AY.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!z0.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!RY.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!NY.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(CY);if(new Set(r.map(({capability:i})=>i)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let n=new Date(t.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:nh,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function ih(e){let t=kY.exec(e);if(t)return{kind:"archive",change:t[1]};let r=bY.exec(e);return r?{kind:"migration",change:r[1]}:null}function oh(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,n=ih(r);if(!n||n.kind!==t.kind||n.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return qA.join(e.transactionsDir,r)}async function VA(e,t){let r=ih(t);if(!r)return null;let n=await Qe({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),o=qA.join(e.transactionsDir,t);if(r.kind==="archive"){let s=_Y(i);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:o,journal:s}}let a=H0(i);if(a.change!==r.change)throw new Error(`Native portable transaction filename does not match ${a.change}`);return{kind:"migration",change:r.change,file:o,journal:a}}async function Lt(e,t){let r=oh(e,t);try{return await VA(e,qA.basename(r))}catch(n){if(n.code==="ENOENT")return null;throw n}}function Y0(e){return e.kind==="archive"||e.journal.status!=="committed"}var nh,J0,kY,bY,AY,RY,NY,SY,EY,z0,Fo=x(()=>{"use strict";Xr();Ka();Q0();nh="comet.native.archive-transaction.v4",J0="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",kY=new RegExp(`^portable-archive-(${J0})\\.json$`,"u"),bY=new RegExp(`^portable-migration-(${J0})\\.json$`,"u"),AY=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,RY=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NY=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),SY=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),EY=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),z0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as IY}from"node:crypto";import{constants as ah,promises as qt}from"node:fs";import yt from"node:path";function In(e,t){let r=yt.relative(e,t);return r===""||!yt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${yt.sep}`)}function xY(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function MA(e,t){return ht({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function PY(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function sh(e,t){return ht({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Nc(e,t){let r=await qt.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await qt.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function FA(e,t,r){let n=yt.resolve(e),i=yt.resolve(t);if(!In(n,i))throw new Error(`${r} is outside its managed root`);let o=[await Nc(n,r)],a=n;for(let s of yt.relative(n,i).split(yt.sep).filter(Boolean)){await rn(o,r),a=yt.join(a,s);let c=await Nc(a,r);if(!In(o[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${a}`);o.push(c)}return await rn(o,r),o}async function rn(e,t){for(let r of e){let n=await qt.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!MA(r,n)||await qt.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function OY(e,t,r){let n=[],i=0,o=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let a=t===null?o.length:t+1-i,{bytesRead:s}=await e.read(o,0,Math.min(o.length,a),null);if(s===0)break;if(i+=s,t!==null&&i>t)throw new Error(`${r} exceeds ${t} bytes`);n.push(Buffer.from(o.subarray(0,s)))}return Buffer.concat(n,i)}async function X0(e){let t=e.maxBytes===null?null:xY(e.maxBytes),r=yt.resolve(e.file),n=await FA(e.root,yt.dirname(r),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(u=>Nc(yt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await rn(n,e.label);let o=await qt.lstat(r);if(!o.isFile()||o.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&o.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let a=PY(o),s=await qt.realpath(r);if(!In(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(u=>In(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ah.O_RDONLY:ah.O_RDONLY|ah.O_NOFOLLOW|ah.O_NONBLOCK,l=await qt.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([qt.lstat(r),qt.realpath(r)]);if(await rn(n,e.label),await rn(i,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!sh(a,u)||!sh(a,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await OY(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[h,p,g]=await Promise.all([l.stat(),qt.lstat(r),qt.realpath(r)]);if(await rn(n,e.label),await rn(i,e.label),!p.isFile()||p.isSymbolicLink()||g!==s||!sh(a,h)||!sh(a,p))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:IY("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function Z0(e){let t=yt.resolve(e.root),r=yt.resolve(e.directory);if(!In(t,r))throw new Error(`${e.label} is outside its managed root`);let n=[await Nc(t,e.label)],i=t;for(let o of yt.relative(t,r).split(yt.sep).filter(Boolean)){await rn(n,e.label),i=yt.join(i,o);try{await qt.mkdir(i)}catch(s){if(s.code!=="EEXIST")throw s}let a=await Nc(i,e.label);if(!In(n[0].realPath,a.realPath))throw new Error(`${e.label} resolves outside its managed root: ${i}`);n.push(a)}await rn(n,e.label)}async function ej(e){let t=yt.resolve(e.root),r=yt.resolve(e.source),n=yt.resolve(e.target);if(r===n||!In(t,r)||!In(t,n)||In(r,n)||In(n,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Z0({root:t,directory:yt.dirname(n),label:`${e.label} target parent`});let i=await FA(t,yt.dirname(r),e.label),o=await FA(t,yt.dirname(n),e.label),a=await Nc(r,e.label);if(!In(i[0].realPath,a.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await qt.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([rn(i,e.label),rn(o,e.label)]);let s=await qt.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!MA(a,s)||await qt.realpath(r)!==a.realPath)throw new Error(`${e.label} source changed before move`);await qt.rename(r,n),await Promise.all([rn(i,e.label),rn(o,e.label)]);let c=await qt.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!MA(a,c)||!In(i[0].realPath,await qt.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await qt.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}var HA=x(()=>{"use strict";bt();ol()});import{lstatSync as jY,promises as Qoe}from"fs";import xn from"path";import{TextDecoder as $Y}from"util";function lh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function uh(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function ij(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function QA(e,t){if(typeof e!="string"||e.length===0||xn.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ch(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function tj(e,t){if(QA(e,t),e.includes("\\")||e!==xn.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function VY(e,t){let r=lh(e,`transaction operations[${t}]`);if(uh(r,BY,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);QA(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&QA(r[n],`transaction operation ${r.id} ${n}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function MY(e){let t=lh(e,"Native Archive transaction journal");if(uh(t,WY,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!nj.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!ij(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ch(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=lh(s,`Archive transaction operations[${c}]`);if(uh(l,LY,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);tj(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&tj(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&ch(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(ch(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);ch(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=r.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let i=`runtime/transactions/${t.id}`,o=r.filter(s=>s.type==="move");if(o.length!==1||o[0].id!=="archive-change"||o[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(o[0].target)||r.at(-1)!==o[0])throw new Error("Native Archive transaction must end with its exact change move");let a=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||a.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(a.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${i}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${i}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function FY(e){let t=lh(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return MY(t);if(uh(t,DY,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!nj.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!xn.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!xn.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!ij(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(VY),n=r.map(i=>i.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function oj(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);let r=xn.join(e.transactionsDir,t),n=xn.join(e.runtimeDir,"transaction-history",t),i=o=>{try{return jY(o),!0}catch(a){if(a.code==="ENOENT")return!1;throw a}};if(!i(n))return r;if(i(r))throw new Error(`Conflicting active and historical Native transaction: ${t}`);return n}async function aj(e,t){let r=await UA(e,t);if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${t} is unfinished`);let n=oj(e,t),i=xn.join(e.runtimeDir,"transaction-history",t);n!==i&&(await ej({root:e.runtimeDir,source:n,target:i,label:"Native completed transaction"}),await al(xn.dirname(i)),await al(e.transactionsDir),await al(e.runtimeDir))}function HY(e,t){let r=oj(e,t);return{directory:r,journal:xn.join(r,"transaction.json"),events:xn.join(r,"events.jsonl"),staged:xn.join(r,"staged"),backups:xn.join(r,"backups")}}async function QY(e,t){let r=HY(e,t);return await Promise.all(Object.values(r).map(n=>_i(e.runtimeDir,n))),r}async function UA(e,t,r={}){let n=await QY(e,t),i=await X0({root:e.runtimeDir,file:n.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),o=JSON.parse(qY.decode(i.bytes)),a=FY(o);if(a.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return a}var DY,BY,WY,LY,nj,qY,sj=x(()=>{"use strict";bt();Ke();HA();DY=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),BY=new Set(["id","type","source","target","staged","backup"]),WY=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),LY=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),nj=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),qY=new $Y("utf-8",{fatal:!0})});import{promises as UY}from"fs";async function JY(e,t,r){let n;try{n=await UY.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of n)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let o=await UA(e,i.name);if(o.id!==t&&o.status!=="committed"&&o.status!=="rolled-back")return!0;(o.status==="committed"||o.status==="rolled-back")&&await aj(e,o.id)}catch{return!0}for(let i of n)if(ih(i.name))try{let o=await VA(e,i.name);if(!o||r?.kind===o.kind&&r.change===o.change)continue;if(Y0(o))return!0}catch{return!0}return!1}async function Ve(e,t,r){if(await Qu(e.projectRoot),await JY(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return t()}var Vt=x(()=>{"use strict";Dt();Fo();sj()});var cj=x(()=>{"use strict"});var dh=x(()=>{"use strict"});var fh=x(()=>{"use strict"});var lj=x(()=>{"use strict"});var JA=x(()=>{"use strict";fh()});var uj=x(()=>{"use strict";fh();JA()});var ZY,dj=x(()=>{"use strict";ZY=tr(jr(),1);ci();Ci();st()});var wae,fj=x(()=>{"use strict";ci();st();wae=Number.MAX_SAFE_INTEGER});var zA=x(()=>{"use strict"});var pj=x(()=>{"use strict"});var mj=x(()=>{"use strict";zA();pj()});var hj=x(()=>{"use strict";mj()});var jae,gj=x(()=>{"use strict";ti();cc();hj();jae=fn("hookWritePolicy",async e=>(await Cb(e))?.hook??{allow_paths:[]})});var vj=x(()=>{"use strict";fh();ci();lj();uj();Ci();dj();st();cc();xb();fj();gj();Bo();_b();JA()});var wj=x(()=>{"use strict";vj();vs()});var xse,yj=x(()=>{"use strict";wj();xse=Number.MAX_SAFE_INTEGER});var kj=x(()=>{"use strict";yj();dh()});var Fse,bj=x(()=>{"use strict";dh();kj();bt();ol();Fse={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER}});var Rj=x(()=>{"use strict";dh();Vt();Ke();bj()});var nce,ice,KA=x(()=>{"use strict";Ze();bt();Xr();Vt();Ke();nce=Number.MAX_SAFE_INTEGER,ice=process.platform});import l9 from"path";function dd(e,t){sd(t);let r=l9.join(e.changesDir,t);if(!Br(e.changesDir,r))throw new Error("Native change path escaped");return r}var Nj,Bce,Sc=x(()=>{"use strict";pc();sc();sc();tT();ti();Nj=tr(jr(),1);Ze();Me();Xt();Ac();Ui();Hb();Xr();bt();Rc();Dt();Vt();Ae();Ke();HA();cj();Rj();KA();Zm();cd();cd();Bce=id("en")});import d9 from"node:path";async function ph(e){let t=wt(e.parent),r=ye(e.paths.projectRoot,t);if(!r)return null;let n=ye(e.paths.projectRoot,e.targetBranch);if(!n)return null;let i=Mt(e.paths.projectRoot).map(a=>d9.resolve(a)).find(a=>de(a).currentBranch===t);if(!i)return null;let o=zd({parent:e.parent,targetBranch:e.targetBranch,targetCommit:n,integrationBranch:t,integrationWorktree:i,contract:e.contract});if(r!==n){for(let a of o.children)a.status=a.dependsOn.length===0?"blocked":"pending",a.blocker=a.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;o.integration.headCommit=r}return Qg(o,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),o}var fd=x(()=>{"use strict";Ze();rr();Dt();Vt();Yn();Wi();Sr()});var GA=x(()=>{"use strict";Yn();Wi();Sr();fd()});import{promises as Cj}from"node:fs";import nn from"node:path";function YA(e,t){let r=nn.normalize(nn.resolve(e)),n=nn.normalize(nn.resolve(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}async function Ij(e){let t=Mt(e.projectRoot);t.some(n=>YA(n,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let n of[...new Set(t.map(i=>nn.resolve(i)))]){let i=await Fe(n);i&&r.push({projectRoot:n,paths:await he(n,i.native.artifact_root),parent:YA(n,e.projectRoot)})}return r.some(({parent:n})=>n)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function xj(e){let t=await Ij(e.paths),r=[],n=[],i=new Map;for(let o of t){let a;try{a=await Cj.readdir(o.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of a){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=nn.join(o.paths.changesDir,s.name),l;try{l=await Gt(nn.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await dn({changeDir:c,validation:un(l),...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:f})=>f)}:{}});!u||u.contract.schema!==mo||u.contract.children.some(({name:f})=>f===e.childName)&&i.set(l.name,[...i.get(l.name)??[],{source:o,state:l}])}}for(let[o,a]of i){let s=e.targetBranch===null?[]:a.filter(({state:m})=>m.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){n.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${o}`);continue}let c=s.find(({source:m,state:h})=>de(m.projectRoot).currentBranch===h.workspace.change_branch);if(!c){let m=a.find(({state:h})=>h.workspace.target_branch!==e.targetBranch);if(m)n.push(`Native Supervisor parent ${o} targets ${m.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let h=s[0]?.state??a[0].state;n.push(`Native Supervisor parent ${o} is not bound to branch ${h.workspace.change_branch}`)}continue}let{source:l,state:u}=c,f=l.paths,d=await mh({paths:f,state:u});if(!d)n.push(`Native Supervisor parent ${o} has no readable Child inspection`);else if(!d.confirmed)n.push(`Native Supervisor parent ${o} requires Shape confirmation`);else if(d.allDone)r.push({paths:f,state:u,inspection:d});else{let m=d.children.filter(({status:h})=>h!=="done").map(({name:h,status:p,message:g})=>`${h}=${p}${g?` (${g})`:""}`).join(", ");n.push(`Native Supervisor parent ${o} is not ready to advance: ${m||"Child facts are incomplete"}`)}}return i.size===0&&n.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),i.size>1&&n.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...i.keys()].join(", ")}`),r.length===1&&n.length===0?{candidate:r[0],blockers:n}:(r.length>1&&n.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:o})=>o.name).join(", ")}`),{candidate:null,blockers:n})}async function p9(e,t){let r=nn.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Gt(r)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function m9(e,t){let r;try{r=await Cj.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let n=[];for(let i of r)if(!(!i.isDirectory()||i.isSymbolicLink()||![...t].some(a=>i.name.endsWith(`-${a}`))))try{let a=nn.join(e.paths.archiveDir,i.name,"comet-state.yaml"),s=await Gt(a);t.has(s.name)&&n.push({file:a,state:s})}catch{}return n}function h9(e,t,r){let n=nn.relative(e.projectRoot,t);if(!n||n===".."||n.startsWith(`..${nn.sep}`))return null;let i=n.split(nn.sep).join("/");try{let o=(0,_j.parseDocument)(q(e.projectRoot,["show",`${r}:${i}`]),{uniqueKeys:!0});return o.errors.length>0?null:L(o.toJS({mapAsMap:!1}))}catch{return null}}function g9(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Ej(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function mh(e){let t=nn.join(e.paths.changesDir,e.state.name),r=!1,n=null,i;try{i=e.state.children_contract?{contract:e.state.children_contract,size:0,drift:null}:await dn({changeDir:t,validation:un(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){n=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,i=null}if(!i){let v=await En(e.paths,e.state.name,{diagnostics:!0});if(v){let w=Kd(v);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,message:n??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(n)throw new Error(n);return e.state.children_contract_ref?{...r?{coordinationChoiceRequired:!0}:{},contractRef:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractRef:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let o=e.state.children_contract_ref??null,a=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&!!e.state.children_contract_ref;if(i.contract.schema===ho){let v=await En(e.paths,e.state.name,{diagnostics:!0});if(!v){let b=e.state.workspace.change_branch??e.state.workspace.target_branch;if(b){let N=await ph({paths:e.paths,parent:e.state.name,targetBranch:b,contract:i.contract});N&&(v=N,await La(e.paths,N))}}if(v){let b=Kd(v);return s?{...b,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:s&&b.confirmed}:{...b,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(N=>({...N,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}}let w=new Map(i.contract.children.map(b=>[b.name,b])),y=i.contract.children.map(b=>({name:b.name,summary:b.summary,dependsOn:[...b.depends_on],covers:[],status:s&&b.depends_on.every(N=>i.contract.children.filter(({name:A})=>A!==b.name).every(({name:A})=>A!==N))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let b of y){if(b.status!=="ready")continue;w.get(b.name).depends_on.length>0&&(b.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:s,parentBranch:a,children:y,readyChildren:y.filter(({status:b})=>b==="ready").map(({name:b})=>b),allDone:!1}}let c=await Ij(e.paths),l=new Set(i.contract.children.map(({name:v})=>v)),u=new Map,f=new Map;for(let v of c){let w=v.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await m9(v,l)){let b={...y,source:v,committedState:h9(v,y.file,w)};u.set(y.state.name,[...u.get(y.state.name)??[],b])}for(let y of l){let b=await p9(v,y);b&&f.set(y,[...f.get(y)??[],{source:v,state:b}])}}let d=new Map;for(let v of i.contract.children){let w=(u.get(v.name)??[]).find(({source:N,committedState:A})=>N.parent&&A?.name===v.name&&Ej(A,a));if(w){d.set(v.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=u.get(v.name)?.[0];if(y){d.set(v.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let b=f.get(v.name)??[];b.length>1?d.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):b[0]&&d.set(v.name,g9(b[0].state,b[0].source,a))}let m=new Map(i.contract.children.map(v=>[v.name,v])),h=new Map,p=v=>{let w=h.get(v);if(w)return w;let y=m.get(v),N=y.depends_on.map(p).every(({status:K})=>K==="done"),A=d.get(v),S=A?.kind==="active"&&N?y.depends_on.filter(K=>!(u.get(K)??[]).some(({source:Z,committedState:re})=>YA(Z.projectRoot,A.projectRoot)&&re?.name===K&&Ej(re,a))):[],_,Q=A?.message??null;A?.kind==="done"?(_=N?"done":"blocked",N||(Q=`Native child ${v} was merged before its dependencies`)):A?.kind==="active"?(_=N&&S.length===0?"active":"blocked",N?S.length>0&&(Q=`Native child ${v} does not include merged dependencies: ${S.join(", ")}`):Q=`Native child ${v} started before its dependencies merged`):A?.kind==="blocked"?_="blocked":(_=s&&N?"ready":"pending",s||(Q="Parent Shape confirmation is required"));let F={name:v,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:_,phase:A?.phase??null,projectRoot:A?.projectRoot??null,message:Q};return h.set(v,F),F},g=i.contract.children.map(({name:v})=>p(v));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:s,parentBranch:a,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}var _j,Ho=x(()=>{"use strict";_j=tr(jr(),1);Ze();rr();vr();Dt();Ke();Ae();GA();vr()});async function Pj(e){let t=await ur(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let n=await mh({paths:e.paths,state:t});if(!n||!n.confirmed||!n.allDone)return{state:t,parentAdvance:{...r,blocker:n&&!n.confirmed?"Supervisor child declarations require Shape confirmation":null}};let i=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:i}}}async function XA(e){let t=await xj({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await Pj({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}var Oj=x(()=>{"use strict";Ho();Yt()});var Tj=x(()=>{"use strict"});import v9 from"path";function ZA(e){return{valid:e.length===0,findings:e}}function jj(e,t){return ZA(e.trim()?[]:[{code:"spec-document-empty",message:"Native target Spec is empty: "+t,path:t}])}function w9(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let n of e.split(/\r?\n/u)){if(y9(n,r)!==null||r.marker!==null)continue;let i=n.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(i)||i.includes("|")&&i.split("|").some(a=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(a)))return!0;let o=i.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let a=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(a)||/[./_-]/u.test(a))return!0}}return!1}function y9(e,t){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(e);if(r===null)return null;let n=r[1]??"",i=n[0];return t.marker===null?(t.marker=i,t.length=n.length,"opened"):i===t.marker&&n.length>=t.length&&e.trim()===n?(t.marker=null,t.length=0,"closed"):null}async function $j(e,t,r={}){let n;try{n=(await Qe({root:e,ref:t,maxBytes:r.maxBytes??null,includeHash:!1})).text}catch(o){return ZA([{code:"brief-missing",message:o.message,path:t}])}let i=[];return n.trim()||i.push({code:"brief-empty",message:"Native brief is empty: "+t,path:t}),w9(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),ZA(i)}function hh(e,t){return v9.join(e.specsDir,t,"spec.md")}var Ec,gh=x(()=>{"use strict";Xr();Sc();Tj();Ke();Ec=class extends Error{constructor(r,n,i){super(r);this.findings=n;this.change=i;this.name="NativeDocumentConstraintError"}findings;change}});function Dj(e){return e.replace(k9,"$1 [REDACTED]").replace(b9,"[REDACTED PRIVATE KEY]").replace(A9,"$1[REDACTED]@").replace(R9,"[REDACTED TOKEN]").replace(N9,'$1"[REDACTED]"').replace(S9,"$1$2$1$3$4[REDACTED]$4").replace(E9,"$1$2[REDACTED]")}var k9,b9,A9,R9,N9,S9,E9,Bj=x(()=>{"use strict";k9=/\b(Bearer|Basic)\s+[^\s"']+/giu,b9=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,A9=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,R9=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,N9=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,S9=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,E9=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{randomUUID as C9}from"node:crypto";function Kr(e){return Ct(Dj(e))}function on(e){return e.state_version+1}function I9(e,t,r){let n=[...e];if(new Set(n).size!==n.length)throw new Error(`${r} contains duplicate IDs`);let i=new Set(t.map(({id:a})=>a)),o=n.filter(a=>!i.has(a));if(o.length>0)throw new Error(`${r} contains unknown IDs: ${o.join(", ")}`);return n}function Wj(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Lj(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function x9(e){return(e??[]).map(t=>({name:Kr(t.name),result:t.result,note:t.note?Kr(t.note):null}))}function Cc(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:Kr(e.summary),completed_at:e.completedAt}}function eR(e){let t=L(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:n})=>n);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return L({...t,phase:"build",status:"active",state_version:on(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(n=>({...n,result:"pending",reason:null}))})}function tR(e){let t=L(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:n})=>n);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return L({...t,status:"await-user",state_version:on(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(n=>({...n,result:"pending",reason:null}))})}function rR(e){let t=L(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!UN(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let n=I9(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),i=[],o,a;if(r.acceptanceReview!==void 0)try{a=dp(r.acceptanceReview,t.acceptance,"acceptanceReview")}catch(l){o=l,i.push(l instanceof Error?l.message:String(l))}else if(e.requireAcceptanceReview!==!1)try{Ul(t.acceptance,void 0)}catch(l){o=l,i.push(l instanceof Error?l.message:String(l))}for(let[l,u]of(r.checks??[]).entries())(!u||typeof u.name!="string")&&i.push("Native Builder checks["+l+"].name must be a string"),(!u||!["passed","failed","not-run"].includes(String(u.result)))&&i.push("Native Builder checks["+l+"].result must be passed, failed, or not-run; received "+JSON.stringify(u?.result)),u?.note!=null&&typeof u.note!="string"&&i.push("Native Builder checks["+l+"].note must be a string or null");if(i.length===1&&o instanceof Ro)throw o;if(i.length)throw new Error(i.join(`
314
+ `)+`
315
+ Correct the reported business fields and submit a new outcomeId using the original claim.`);let s=Wj(t.acceptance),c=(r.now??new Date).toISOString();return L({...t,phase:"verify",state_version:on(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:s,builder_handoff:{candidate_id:r.candidateId??C9(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:Kr(r.summary),addressed_acceptance_ids:n,acceptance_review:a,checks:x9(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(l=>Kr(l)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:Kr(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:c},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function hi(e){let t=L(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return L({...t,state_version:on(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function P9(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.verifierExecutionRef===e.state.builder_handoff?.builder_execution_ref?"self-reviewed":e.envelope.identityProvider===hr?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:[],summary:Kr(e.response.result.summary),risks:e.response.result.risks.map(t=>Kr(t)),risks_truncated:!1,completed_at:e.completedAt}}function nR(e){let t=L(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Lj(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let n=KN({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,requireIndependentSession:e.requireIndependentSession,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:d})=>d),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:d})=>d==="passed").map(({id:d})=>d),requiredChecksPassed:(e.reportedChecks??[]).every(({result:d})=>d==="passed")}});if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let i=(e.now??new Date).toISOString(),o=new Map(n.result.acceptance.map(d=>[d.id,d])),a=t.acceptance.map(d=>{let m=o.get(d.id);return m?{...d,result:m.result,reason:Kr(m.reason)}:d}),s=a.filter(({result:d})=>d==="failed"||d==="blocked").map(({id:d})=>d),c=P9({state:t,envelope:e.envelope,response:n,completedAt:i});if(e.reportedChecks&&(c.reported_checks=e.reportedChecks),n.result.verdict==="pass"){let d=tn({...t,acceptance:a,verification:c},Cc({state:t,outcome:"pass",summary:n.result.summary,completedAt:i})),m=t.builder_handoff.identity_provider===hr;return{response:n,state:L({...d,phase:m?"verify":"archive",status:m?"await-user":"active",state_version:on(t),verification_result:"pass",verification_report:"verification.md",blockers:m?[{owner:"user",reason:Kr(e.requireIndependentSession===!1?"Verification passed; user acceptance is required before Archive.":"The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:m?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:m?"confirm-skill-coordinated-pass":"archive"}})}}if(n.result.verdict==="blocked"){let d=tn({...t,acceptance:a,verification:c},Cc({state:t,outcome:"blocked",unresolvedIds:s,summary:n.result.summary,completedAt:i}));return{response:n,state:L({...d,status:"await-user",state_version:on(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:Kr(n.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=l>=e.maxVerifyFailures,f=tn({...t,acceptance:a,verification:c},Cc({state:t,outcome:"fail",unresolvedIds:s,summary:n.result.summary,completedAt:i}));return{response:n,state:L({...f,phase:u?"verify":"build",status:u?"await-user":"active",state_version:on(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:u?[{owner:"user",reason:Kr("Native verification reached the configured failed iteration limit."),acceptance_ids:s,resolution_action:"await-user"}]:[],loop:{...t.loop,stage:u?"await-user":"repairing",iteration:u?t.loop.iteration:t.loop.iteration+1,attempt:u?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:0,stop_reason:u?"budget":void 0,execution_failure_count:0,previous_unresolved_ids:s,next_action:u?"await-user":"repair-failed-acceptance"}})}}function iR(e){let t=L(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==hr||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return L({...t,phase:"archive",status:"active",state_version:on(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function oR(e,t){let r=L(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let n=tn(r,Cc({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return L({...n,status:"active",state_version:on(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(i=>i.result==="failed"||i.result==="blocked"?{...i,result:"pending",reason:null}:i),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function aR(e){let t=L(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),n=t.loop.execution_failure_count+1,i=n>=_9,o=tn(t,Cc({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return L({...o,status:i?"blocked":"active",state_version:on(t),blockers:i?[{owner:"runtime",reason:Kr(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:i?"blocked":"verify-ready",execution_failure_count:n,next_action:i?"retry-verifier":"dispatch-new-verifier"}})}function sR(e){let t=L(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:s})=>s==="retry-verifier"),n=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:s})=>s==="confirm-verifier-unavailable"),i=t.status==="await-user"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass";if(t.phase!=="verify"||!r&&!n&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let o=Lj(t),a=t.acceptance.some(({result:s})=>s==="passed");return L({...t,status:"active",state_version:on(t),...n||i?{verification_result:"pending",verification_report:null,verification:null,...i?{acceptance:t.acceptance.map(s=>({...s,result:"pending",reason:null}))}:{}}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...n?{previous_unresolved_ids:a?o:[]}:{},next_action:"dispatch-new-verifier"}})}function _c(e){let t=L(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,n=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,i=r!==void 0&&n>=r.maxVerifyFailures,o=(e.now??new Date).toISOString(),a=tn(t,Cc({state:t,outcome:"recovery",summary:e.reason,completedAt:o})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?Wj(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return i?L({...a,phase:"verify",status:"await-user",state_version:on(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:Kr(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:n,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):L({...a,phase:"build",status:"active",state_version:on(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:n,stop_reason:void 0,next_action:"submit-builder-candidate"}})}var _9,Ga=x(()=>{"use strict";fp();Ae();Ii();na();tl();Bj();_9=3});import qj from"node:path";async function cR(e){let{paths:t,state:r}=e;if(r.phase!=="shape"||r.status!=="active")return;let n=qj.join(t.changesDir,r.name);for(let i of e.specChanges){if(i.operation!=="modify"||!i.delta_source||!i.source)continue;let o=await Qe({root:t.specsDir,ref:i.capability+"/spec.md",maxBytes:null,includeHash:!1}),a=await Qe({root:n,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=zr(a.text);if(s.capability!==i.capability)throw new Error("Native Delta capability does not match its target");let c=I0({baselineMarkdown:o.text,delta:s,allowAlreadyApplied:!0}),l=await Qe({root:n,ref:i.source,maxBytes:null,includeHash:!1});if(l.text!==c.markdown){if(l.text!==o.text)throw new Error("Native target has independent edits: "+i.source+". Reconcile the target and Delta before preparing Shape.");await et(qj.join(n,...i.source.split("/")),c.markdown,{containedRoot:t.nativeRoot})}}}var lR=x(()=>{"use strict";bt();Xr();Ka()});import{promises as O9}from"node:fs";function Vj(e){if(!e.builder_handoff||!e.verification)throw new Error("Native verification result requires a candidate and accepted evidence");return ld("comet.native.verification-result.v1",{candidateId:e.builder_handoff.candidate_id,acceptance:e.acceptance,verification:e.verification})}function an(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
316
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Jn(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function T9(e){return e.archived?Jr(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Jr(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Jr(e.language,"Verification passed; ready to archive","验收通过,可归档"):Jr(e.language,"Verification passed","验收通过")}function j9(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Jr(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?T9(e):e.verification_result==="blocked"?Jr(t,"Blocked","已阻塞"):e.verification_result==="fail"?Jr(t,"Failed","未通过"):Jr(t,"Pending","待处理")}function $9(e){if(e.verification?.assurance==="semantic-verification-unavailable")return Jr(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return Jr(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return Jr(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===hr?hr:"host-attested"),r=t===hr&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","self-reviewed":"Acceptance reviewed in the implementation session","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","self-reviewed":"已在实现会话中完成验收","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function pd(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,n=d=>y0(r,d),i=(d,m)=>Jr(r,d,m),o=e.acceptance.map(d=>`| ${Jn(d.id)} | ${Jn(d.result)} | ${Jn(d.source)} | ${Jn(d.text)} | ${Jn(an(d.reason))} |`).join(`
317
+ `),a=e.verification.reported_checks?[`| ${i("Agent-reported check","Agent 报告的检查")} | ${i("Result","结果")} | ${i("Execution and evidence","执行与证据")} |`,"| --- | --- | --- |",...e.verification.reported_checks.map(d=>`| ${Jn(an(d.name))} | ${d.result} | ${Jn(an(d.note))} |`)].join(`
318
+ `):e.verification.checks.length===0?`_${i("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${i("Check","检查")} | ${i("Command","命令")} | ${i("Working directory","工作目录")} | ${i("Status","状态")} | ${i("Exit","退出码")} | ${i("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let m=d.argv_display.map(an).join(" ");return`| ${Jn(an(d.name))} | ${Jn(m||"—")} | ${Jn(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
319
+ `),s=e.builder_handoff?[`### ${i("Builder-reported evidence","Builder 报告的证据")}`,"",i("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(d=>`- ${an(d.name)}: ${d.result} — ${an(d.note)}`),...e.builder_handoff.checks_truncated?[i("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(d=>`- ${i("Known limitation","已知限制")}: ${an(d)}`),...e.builder_handoff.known_limits_truncated?[i("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
320
+ `):"",c=e.blockers.length===0?`_${i("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${an(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
321
+ `),l=e.verification.risks.length===0?`_${i("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${an(d)}`).join(`
322
+ `),u=e.history.length===0?`_${i("No previous iterations.","没有之前的迭代。")}_`:[`| ${i("Goal cycle","目标周期")} | ${i("Iteration","迭代")} | ${i("Attempt","尝试")} | ${i("Outcome","结果")} | ${i("Unresolved","未解决项")} | ${i("Summary","摘要")} | ${i("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Jn(an(d.summary))} | ${d.completed_at} |`)].join(`
323
+ `),f=t?.finalVerification.layers?`
324
+ ## ${i("Supervisor evidence layers","Supervisor 分层证据")}
325
+
326
+ - ${i("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
327
+ - ${i("Parent integration","父级集成")}: ${t.finalVerification.layers.parentIntegration}
328
+ - ${i("Parent checks","父级检查")}: ${t.finalVerification.layers.parentChecks.join(", ")||"—"}
329
+ - ${i("Not rerun","未重跑")}: ${t.finalVerification.layers.notRerun.join(", ")||"—"}
330
+ - ${i("Incomplete","未完成")}: ${t.finalVerification.layers.incomplete.join(", ")||"—"}
331
+ `:"";return`---
332
+ generated_from_state_version: ${e.state_version}
333
+ ---
334
+
335
+ # ${n("verification")}
336
+
337
+ ## ${n("currentResult")}
338
+
339
+ - ${i("Result","结果")}: **${j9(e)}**
340
+ - ${i("Verification status","验证情况")}: **${$9(e)}**
341
+ - ${i("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
342
+ - ${i("Iteration","迭代")}: ${e.verification.iteration}
343
+ - ${i("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
344
+ - ${i("Completed","完成时间")}: ${e.verification.completed_at}
345
+ - ${i("Summary","摘要")}: ${an(e.verification.summary)}
346
+
347
+ ## ${n("acceptance")}
348
+
349
+ | ${i("ID","编号")} | ${i("Result","结果")} | ${i("Source","来源")} | ${i("Criterion","验收项")} | ${i("Reason","原因")} |
350
+ | --- | --- | --- | --- | --- |
351
+ ${o}
352
+
353
+ ## ${n("checks")}
354
+
355
+ ${a}
356
+
357
+ ${s}
358
+
359
+ ## ${n("blockers")}
360
+
361
+ ${c}
362
+
363
+ ## ${n("risks")}
364
+
365
+ ${l}
366
+
367
+ ## ${n("previousIterations")}
368
+
369
+ ${u}
370
+
371
+ ${f}
372
+
373
+ ${e.history_overflow.dropped_entries>0?`${i("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
374
+
375
+ `:""}## ${n("conclusion")}
376
+
377
+ ${an(e.verification.summary)}
378
+ `}function D9(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function md(e){let t;try{t=await O9.readFile(e.file,"utf8")}catch(n){if(n.code==="ENOENT")return"missing";throw n}let r=D9(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function vh(e){await et(e.file,pd(e.state,e.supervisor),{beforeCommit:e.beforeCommit})}var Ic=x(()=>{"use strict";Ae();Rc();bt();eh();na()});import{randomUUID as B9}from"node:crypto";import{promises as W9}from"node:fs";import hd from"node:path";function Ya(e){return"native/preserved-verification/"+encodeURIComponent(e)}function wh(e,t){if(!e.builder_handoff||!e.verification)throw new Error("Native report requires its accepted Verifier result");return{candidateId:e.builder_handoff.candidate_id,reportRef:hd.posix.join(t.replaceAll("\\","/"),"comet","changes",e.name,"verification.md"),stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt}}async function xc(e){let{state:t,paths:r,file:n}=e,i=hd.relative(r.projectRoot,n).replaceAll("\\","/"),o=await De(r.projectRoot,i,Number.MAX_SAFE_INTEGER,{label:"Native verification view"}).catch(c=>{if(c.code==="ENOENT")return null;throw c}),a=pd(t);if(o?.bytes.equals(Buffer.from(a)))return{};let s;if(o){await Ei(r.projectRoot);let c=Ya(e.runId);await xt(r.workspaceRuntimeRoot,c,{label:"Native preserved report"}),s=c+"/"+B9()+".md",await W9.writeFile(hd.join(r.workspaceRuntimeRoot,...s.split("/")),o.bytes,{flag:"wx"})}return await et(n,a,{containedRoot:r.projectRoot}),s?{preservedReportRef:s}:{}}async function Mj(e,t){if(!L(t.state).archived)return;let n=await he(e,t.input.artifactRootRef,{readOnly:!0}),i=t.outputs["archive.finalize"]?.value;if(!i?.archiveRef)return;let o=hd.relative(e,hd.join(n.archiveDir,i.archiveRef,"verification.md")).replaceAll("\\","/"),a=!1;try{a=(await oe(e,o,{label:"Native archived verification view",expected:"file"})).exists}catch{}return a?void 0:{code:"NATIVE_REPORT_PENDING",message:"归档已完成,验证报告阅读视图尚不可用;实际验收结果和归档进度已保存。",reportRef:o}}var Ji=x(()=>{"use strict";st();yr();bt();Ke();Ae();Ic()});import{promises as yh}from"node:fs";import gd from"node:path";function Fj(e,t){let r=e.map(({code:n,message:i,path:o})=>`- ${n}${o?` (${o})`:""}: ${i}`).join(`
379
+ `);return[`Native ${t.phase} document checks failed for ${t.change}.`,r,"Recovery: edit the reported formal file in the configured Native change directory, then rerun the latest continuation command. The current state and existing work are preserved; do not edit comet-state.yaml or bypass the Hook."].join(`
380
+ `)}async function kh(e){let t=Nt(e.paths,e.state.name),r=e.state.document_constraints_version,n=r===2||r===3,i=r===3,o=[...(await $j(t,e.state.brief,{strict:!0,compact:n,structure:i,maxBytes:null})).findings],a=e.specChanges??e.state.spec_changes,s=a.filter(({operation:d})=>d!=="remove"),c=e.state.spec_changes.filter(({operation:d})=>d!=="remove"),l=new Set(s.map(({capability:d})=>d)),u=e.state.phase==="shape",f=new Set(a.filter(({operation:d})=>d==="remove").map(({capability:d})=>d));if(e.specChanges!==void 0&&!(u&&s.length>0))for(let d of c)l.has(d.capability)||u&&f.has(d.capability)||o.push({code:"spec-document-missing",message:u?`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file, stage the replacement target Spec under specs/<capability>/spec.md, or record the intended capability deletion as a formal remove entry.`:`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${d.capability}/spec.md`});for(let d of s){let m=`specs/${d.capability}/spec.md`;if(d.source!==m){o.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${m}.`,path:d.source??m});continue}try{let h=(await Qe({root:t,ref:m,maxBytes:null,includeHash:!1})).text;o.push(...jj(h,m).findings)}catch(h){o.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${h.message}. Restore the complete file at ${m}.`,path:m})}}return{valid:o.length===0,findings:o}}async function uR(e){let t=await kh(e);if(!t.valid)throw new Ec(Fj(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}async function bh(e){let t=Nt(e.paths,e.state.name),r=gd.join(t,"specs"),n=new Map(e.state.spec_changes.filter(({operation:a})=>a==="remove").map(a=>[a.capability,a])),i;try{i=await yh.readdir(r,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")i=[];else throw a}let o=[];for(let a of i.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(a.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${a.name}`);if(!a.isDirectory())continue;if(!Om.test(a.name))throw new Error(`Invalid Native capability: ${a.name}`);if(n.has(a.name))throw new Error(`Capability ${a.name} cannot be proposed and removed together`);let s=`specs/${a.name}/spec.md`,c=gd.join(t,...s.split("/")),l=await yh.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=gd.join(e.paths.specsDir,a.name,"spec.md"),f="create";try{let p=await yh.lstat(u);if(!p.isFile()||p.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${a.name}`);f="modify"}catch(p){if(p.code!=="ENOENT")throw p}let d=`specs/${a.name}/${A0}`,m=gd.join(t,...d.split("/")),h={};try{let p=await yh.lstat(m);if(!p.isFile()||p.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${d}`);let g=await Qe({root:t,ref:d,maxBytes:null,includeHash:!1}),v=zr(g.text);if(v.capability!==a.name)throw new Error(`Native delta capability ${v.capability} does not match directory ${a.name}`);h={delta_source:d}}catch(p){if(p.code!=="ENOENT")throw p}o.push({capability:a.name,operation:f,source:s,...h})}return o.push(...n.values()),o.sort((a,s)=>a.capability.localeCompare(s.capability,"en"))}async function Ah(e){let t=Nt(e.paths,e.state.name),r=async o=>{let a=e.artifactTexts?.get(o);return a!==void 0?a:(await Qe({root:t,ref:o,maxBytes:null,includeHash:!1})).text},n=await r("brief.md"),i=[];for(let o of e.specChanges)o.source!==null&&i.push({capability:o.capability,source:o.source,markdown:await r(o.source)});return{acceptance:V0({briefMarkdown:n,specs:i,legacyBriefBoundaries:e.legacyBriefBoundaries,resolveBriefReferences:e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1})}}async function Rh(e){return Ve(e.paths,async()=>{let t=await ur(e.paths,e.name);if(e.expectedStateVersion!==void 0&&(t.state_version!==e.expectedStateVersion||t.phase!=="archive"||t.status!=="active"||t.loop.stage!=="archive-ready"||t.workspace.finish!==null))throw new Error("Native workspace finish decision is stale; read the current continuation and confirm the finish again");if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},n=await qi({paths:e.paths,previous:t,next:r});return n.verification!==null&&await xc({paths:e.paths,runId:t.name,file:gd.join(Nt(e.paths,t.name),"verification.md"),state:n}),n})}var H9,Qo=x(()=>{"use strict";Xt();Rc();gh();bt();Xr();Sc();Ho();Dt();Ka();Ga();Vt();Ke();rh();Ae();Yt();Ii();lR();Wi();Ji();H9=id("en",{compact:!0})});var Qj=x(()=>{"use strict";Ze();Ho();Dt();Ga();Vt();Qo();Ae();Yt();Ii();fd();Yn();Wi();Sr()});var Nh=x(()=>{"use strict";Ae();Ii();Yt()});var Uj=x(()=>{"use strict";fd();Wi();Ga();Vt();Qo();Yt();na();Ic();Ji();$u();tl()});var zj=x(()=>{"use strict";Ga();Vt();Qo();Yt();Nh();fd();Wi();Ji()});var Kj=x(()=>{"use strict";bt();Xr();Ho();Ka();Vt();rh();Qo();Yt();Nh()});var dR=x(()=>{"use strict";Oj();Qo();Qj();Yt();Nh();Uj();zj();Kj()});async function U9(e){let t=await Ur(e.projectRoot);if(t.status==="missing")return null;if(t.selection.workflow!=="native"){if(t.selection.workflow!=="application")return null;let r=await qe(e.projectRoot,"native",t.selection.change,{readOnly:!0});if(!r||r.application!==t.selection.applicationId)return null}return sd(t.selection.change),t.selection}function fR(e){return fc(e.projectRoot)}async function Gj(e,t){await Qu(e.projectRoot);let r=await U9(e);return r?.change===t?Ma(e.projectRoot,r.workflow,t):!1}var _fe,pR=x(()=>{"use strict";Bo();Xt();Sc();Dt();Vt();Ae();dR();Me();Ac();_fe=Number.MAX_SAFE_INTEGER});import{createHash as J9,randomUUID as z9}from"node:crypto";import{promises as kt}from"node:fs";import Zt from"node:path";function Eh(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function zi(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=Zt.join(e.archiveDir,t);if(!Br(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}function Yj(e,t){return zi(e,Eh(t))}async function gi(e){try{return await kt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Xj(e,t){let r;try{r=await kt.readdir(e.archiveDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return null;throw i}let n=[];for(let i of r){if(!i.isDirectory()||i.isSymbolicLink())continue;let o=Zt.join(e.archiveDir,i.name);try{let a=await Gt(Zt.join(o,"comet-state.yaml"));a.name===t&&n.push({dir:o,state:a})}catch{}}if(n.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return n[0]??null}async function Xa(e,t){let r=await Lt(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Zj(e,t){return await Xa(e,t)!==null||await Xj(e,t)!==null}async function vd(e,t){await kt.mkdir(e.transactionsDir,{recursive:!0}),await Pr(oh(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function hR(e,t){let r=Zt.join(e.specsDir,t),n=Zt.join(r,"spec.md");if(!Br(e.specsDir,n))throw new Error("Native canonical spec path escaped");let i;try{i=await kt.lstat(e.specsDir)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let o;try{o=await kt.lstat(r)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let[a,s]=await Promise.all([kt.realpath(e.specsDir),kt.realpath(r)]);if(!Br(a,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let c;try{c=await kt.lstat(n)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${t}`);if(!Br(s,await kt.realpath(n)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{return{text:(await Qe({root:e.specsDir,ref:`${t}/spec.md`,maxBytes:null,includeHash:!1})).text,exists:!0}}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}}async function K9(e){let t=Zt.join(e.paths.specsDir,e.change.capability),r=Zt.join(t,"spec.md");if(!Br(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let s;try{s=await kt.lstat(e.paths.specsDir)}catch(f){if(f.code==="ENOENT")return;throw f}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let c;try{c=await kt.lstat(t)}catch(f){if(f.code==="ENOENT")return;throw f}if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[l,u]=await Promise.all([kt.realpath(e.paths.specsDir),kt.realpath(t)]);if(!Br(l,u))throw new Error("Native canonical capability path escaped");try{let f=await kt.lstat(r);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await kt.unlink(r)}catch(f){if(f.code!=="ENOENT")throw f}await kt.rmdir(t).catch(f=>{if(f.code!=="ENOENT"&&f.code!=="ENOTEMPTY")throw f});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let n=await hR(e.paths,e.change.capability),i=e.change.delta_content?ad({currentMarkdown:n.text,delta:zr(e.change.delta_content)}).markdown:e.change.content,o=n.exists&&n.text===i;if(e.change.operation==="create"&&n.exists&&!o)throw new Error(`Canonical Native spec conflicts with the pending create: ${e.change.capability}`);let a=Zt.join(Nt(e.paths,e.state.name),e.change.source);await et(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),!o&&(await kt.mkdir(t,{recursive:!0}),await et(r,i,{containedRoot:e.paths.nativeRoot}))}function gR(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function G9(e,t){let r=Nt(e,t.name),n=[];for(let i of t.spec_changes){if(i.source===null){n.push({...i,content:null});continue}let o=await Qe({root:r,ref:i.source,maxBytes:null,includeHash:!1});if(i.delta_source){let a=await Qe({root:r,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=zr(a.text);if(s.capability!==i.capability)throw new Error(`Native delta capability ${s.capability} does not match ${i.capability}`);let c=await hR(e,i.capability),l=ad({currentMarkdown:c.text,delta:s});n.push({...i,content:l.markdown,delta_content:a.text,source_content:o.text});continue}n.push({...i,content:o.text})}return n}function vR(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(gR(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Y9(e){let t=[],r=[];for(let n of e.state.spec_changes)try{let i=Nt(e.paths,e.state.name);n.source&&await Qe({root:i,ref:n.source,maxBytes:null,includeHash:!1});let o;if(n.delta_source){let a=await Qe({root:i,ref:n.delta_source,maxBytes:null,includeHash:!1}),s=zr(a.text);if(s.capability!==n.capability)throw new Error("Native delta capability does not match its target");let c=await hR(e.paths,n.capability);o=[...ad({currentMarkdown:c.text,delta:s}).operationResults]}r.push({capability:n.capability,operation:n.operation,source:n.source,...n.delta_source?{delta_source:n.delta_source,delta_operations:o}:{}})}catch(i){t.push(i.message)}return{blockers:t,requiresReverification:!1,specPreview:r}}async function wd(e){let t=e.state??await ur(e.paths,e.name);if(t.name!==e.name)throw new Error("Native Archive state belongs to another change");let r=[];if(e.state===void 0)try{let s=await dc(e.paths,t);s&&!Li(s)&&lc(s)}catch(s){r.push(s.message)}let n=!1,i;if(t.document_constraints_version===1){let s=await kh({paths:e.paths,state:t});r.push(...s.findings.map(({message:c})=>c))}try{gR(t)}catch(s){r.push(s.message)}let o=await Xa(e.paths,e.name);if(o===null){let s=zi(e.paths,Eh(t));await gi(s)&&r.push(`Native Archive target already exists: ${s}`);let c=await Y9({paths:e.paths,state:t});r.push(...c.blockers),n=c.requiresReverification,i=c.specPreview}else i=o.spec_changes.map(s=>({capability:s.capability,operation:s.operation,source:s.source,...s.delta_source===void 0?{}:{delta_source:s.delta_source},...s.delta_content?{delta_operations:zr(s.delta_content).operations.map(c=>({id:c.id,operation:c.operation,status:"changed",targetIds:c.operation==="rename"?[c.id,c.to_id]:[c.id]}))}:{}}));let a=e.derivedReport?"aligned":t.verification===null?"missing":await md({file:Zt.join(Nt(e.paths,t.name),"verification.md"),stateVersion:e.verificationReportStateVersion??t.state_version});return a!=="aligned"&&r.push(`verification.md is ${a}`),{ready:r.length===0,blockers:r,requiresReverification:n,specPreview:i,capabilityPeers:[],archiveDir:zi(e.paths,Eh(t)),stateVersion:t.state_version}}async function Ch(e){let{paths:t,state:r}=e;return Ve(t,async()=>{gR(r);let n=await Xa(t,r.name);if(n)vR(n,r);else{let i=await wd({paths:t,name:r.name,state:r,verificationReportStateVersion:e.verificationReportStateVersion,derivedReport:e.derivedReport});if(!i.ready)throw new Error(`Native SDK Archive preflight is blocked: ${i.blockers.join("; ")}`);n={schema:nh,id:z9(),change:r.name,start_state_version:r.state_version,archive_ref:Eh(r),status:"prepared",next_spec_index:0,spec_changes:await G9(t,r),created_at:new Date().toISOString()},await vd(t,n)}if(n.status==="prepared"){for(let i=n.next_spec_index;i<n.spec_changes.length;i+=1)await K9({paths:t,state:r,change:n.spec_changes[i]}),n={...n,next_spec_index:i+1},await vd(t,n);n={...n,status:"specs-applied"},await vd(t,n)}return n},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function _h(e){let t=await Xa(e.paths,e.state.name);if(!t||t.status!=="specs-applied")throw new Error("Native SDK Archive Specs have not been applied");if(vR(t,e.state),t.next_spec_index!==t.spec_changes.length)throw new Error("Native SDK Archive Spec transaction is incomplete");return{transactionId:t.id,archiveRef:t.archive_ref,stateVersion:t.start_state_version,specCount:t.spec_changes.length}}async function X9(e,t,r){let n=Zt.join(zi(e,t),"comet-state.yaml"),i;try{i=await kt.readFile(n,"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}if(!Ba(i))return;let o=(0,mR.parseDocument)(i,{uniqueKeys:!0});if(o.errors.length>0)throw new Error("Native SDK Archive state is invalid");o.set(e$,r),await et(n,o.toString(),{containedRoot:e.nativeRoot})}async function Z9(e,t){let r=Zt.join(zi(e,t),"comet-state.yaml"),n=await Qe({root:e.nativeRoot,ref:Zt.relative(e.nativeRoot,r).replaceAll("\\","/"),maxBytes:null});if(!Ba(n.text))throw new Error("Native SDK Archive portable receipt has no managed Run");let i=(0,mR.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error("Native SDK Archive state is invalid");return i.toJS()[e$]}function t$(e,t){if(!t.trim())throw new Error("Native SDK Archive Run ID is missing");let r=J9("sha256").update(t).digest("hex");return Zt.join(e.runtimeDir,"sdk-archive-receipts",`${r}.json`)}async function yd(e){let{paths:t,state:r,runId:n}=e;return Ve(t,async()=>{if(r.phase!=="archive"||r.status!=="done"||!r.archived||r.loop.stage!=="done")throw new Error("Native SDK Archive finalization requires committed done state");let i=await Xa(t,r.name);if(!i){let l=await vi({paths:t,state:r,runId:n,archiveRef:e.archiveRef});if(l.transactionId!==e.transactionId)throw new Error("Native Archive recovery belongs to another transaction");return l}if(vR(i,r),i.id!==e.transactionId||i.archive_ref!==e.archiveRef||i.next_spec_index!==i.spec_changes.length||i.spec_changes.length!==r.spec_changes.length||i.spec_changes.some((l,u)=>l.capability!==r.spec_changes[u]?.capability||l.operation!==r.spec_changes[u]?.operation||l.source!==r.spec_changes[u]?.source)||!["specs-applied","report-aligned","moved"].includes(i.status))throw new Error("Native SDK Archive recovery does not match its completed Spec operations");let o=Nt(t,r.name),a=zi(t,i.archive_ref);if(i.status==="specs-applied"){if(!await gi(o)||await gi(a))throw new Error("Native Archive layout contradicts its transaction");let l=Zt.join(o,"verification.md");if(!await gi(l))try{e.derivedReport?await e.derivedReport.write(l):await vh({file:l,state:r})}catch(u){if(!e.derivedReport?.optionalView)throw u}i={...i,status:"report-aligned"},await vd(t,i)}if(i.status==="report-aligned"){let l=await gi(o),u=await gi(a);if(l===u)throw new Error("Native Archive layout contradicts its transaction");l&&(await kt.mkdir(t.archiveDir,{recursive:!0}),await ia(o,a)),i={...i,status:"moved"},await vd(t,i)}if(i.status!=="moved"||await gi(o)||!await gi(a))throw new Error("Native SDK Archive has not moved the change");let s={runId:n,change:r.name,archiveRef:i.archive_ref,transactionId:i.id,stateVersion:r.state_version,specs:i.spec_changes.map(l=>({capability:l.capability,operation:l.operation}))};await X9(t,i.archive_ref,s);let c=t$(t,n);return await kt.mkdir(Zt.dirname(c),{recursive:!0}),await Pr(c,s,{containedRoot:t.runtimeDir}),await kt.rm(oh(t,{kind:"archive",change:r.name}),{force:!0}),s},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function vi(e){let{paths:t,state:r,runId:n}=e,i;try{i=JSON.parse(await kt.readFile(t$(t,n),"utf8"))}catch(o){if(o.code!=="ENOENT"||!e.archiveRef)throw o;i=await Z9(t,e.archiveRef)}if(!i||i.runId!==n||i.change!==r.name||i.stateVersion!==r.state_version||e.archiveRef!==void 0&&i.archiveRef!==e.archiveRef||typeof i.transactionId!="string"||!Array.isArray(i.specs)||i.specs.length!==r.spec_changes.length||i.specs.some((o,a)=>o?.capability!==r.spec_changes[a]?.capability||o.operation!==void 0&&o.operation!==r.spec_changes[a]?.operation)||await Xa(t,r.name)||await gi(Nt(t,r.name)))throw new Error("Native SDK Archive completion record does not match its Run or transaction");if(!await gi(zi(t,i.archiveRef)))throw new Error("Native SDK Archive destination is missing");return i}async function wR(e){let{paths:t,name:r}=e,n=await Xa(t,r),i;try{i=await ur(t,r)}catch(a){if(a.code!=="ENOENT")throw a;if(n){if(i=await Gt(Zt.join(zi(t,n.archive_ref),"comet-state.yaml")),i.name!==r||!i.archived||i.status!=="done")throw new Error("Moved Archive does not match its original transaction",{cause:a})}else{let s=await Xj(t,r);if(!s)throw a;i=s.state;let c=await vi({paths:t,state:i,runId:r,archiveRef:Zt.basename(s.dir),history:!0}),l=await dc(t,i);return l&&await uc(l),{change:r,state:i,transactionId:c.transactionId,archiveDir:s.dir}}}let o=await dc(t,i);if(o&&!Li(o)&&lc(o),i.archived||(n=await Ch({paths:t,state:i}),i=await Ve(t,async()=>{let a=await ur(t,r);if(a.state_version!==i.state_version)throw new Error("Archive state changed; retain the original transaction and retry");return qi({paths:t,previous:a,next:{...a,status:"done",archived:!0,state_version:a.state_version+1,blockers:[],loop:{...a.loop,stage:"done",next_action:null}}})},{allowedPortableTransaction:{kind:"archive",change:r}})),!n)throw new Error("Original Archive transaction is unavailable; inspect its retained receipt before continuing");return await yd({paths:t,state:i,runId:r,transactionId:n.id,archiveRef:n.archive_ref}),o&&await uc(o),await Ve(t,()=>Gj(t,r)),{change:r,state:i,transactionId:n.id,archiveDir:zi(t,n.archive_ref)}}async function r$(e){let{projectRoot:t,store:r,runId:n,expectedRevision:i,next:o,actionId:a,state:s}=e,c=await he(t,o.input.artifactRootRef);return Ve(c,async()=>{let l=await r.read(n);if(l?.revision!==i)return!1;if(l.actions.find(f=>f.id===a)?.status==="unknown"&&await Lt(c,{kind:"archive",change:s.name}))throw new Error("Native Archive has a transaction; recover its actual progress with archive --recover");return r.compareAndSwap(n,i,o)},{allowedPortableTransaction:{kind:"archive",change:s.name}})}var mR,Sh,e$,Pc=x(()=>{"use strict";Sr();Yt();pR();mR=tr(jr(),1);Gd();ju();bt();Xr();Ka();Vt();Ke();Qo();Yt();Ae();Fo();Ic();Sh=class extends Error{state;constructor(t){super("Native canonical Spec changed independently; the merged delta requires fresh verification"),this.name="NativePortableArchiveRequiresReverificationError",this.state=t}};e$="archive_receipt"});function ns(e,t,r){if(e.phase!=="verify")return[];let n=[];return e.status==="await-user"&&(t.stepId==="verify.stop"&&["await-user","resolve-verifier-blocker"].includes(e.loop.next_action??"")?(e.loop.next_action==="resolve-verifier-blocker"&&n.push({action:"resolve-verifier-blocker",choice:"retry"}),n.push({action:"revise-implementation",choice:"repair"})):t.stepId==="verify.confirm"&&e.loop.next_action==="confirm-skill-coordinated-pass"&&(n.push({action:"accept-result",choice:"approved"},{action:"revise-implementation",choice:"rejected"}),t.choices.includes("reverify")&&n.push({action:"retry-verifier",choice:"reverify"}))),t.stepId==="verify.retry"&&e.status==="blocked"&&e.loop.next_action==="retry-verifier"&&n.push({action:"retry-verifier",choice:"retry"}),n.filter(({choice:i})=>t.choices.includes(i))}function CR(e,t){return["failed","cancelled","completed"].includes(e.status)?[]:e.waits.filter(r=>r.status==="pending").flatMap(r=>ns(t,r,e).map(n=>({...n,wait:r})))}var _R=x(()=>{"use strict"});import Dh from"node:path";import{isDeepStrictEqual as j4}from"node:util";function Bh(e){let t=e.actions.at(-1);return e.status==="failed"&&e.reason==="ACTION_FAILED: archive.prepare"&&t?.stepId==="archive.prepare"&&t.ref==="native-archive-preflight"&&t.type==="call_tool"&&t.status==="failed"&&t.retry==="idempotent"&&!t.rejectedOutcomes?.some(r=>r.outcome.attempt===t.attempt)&&!e.actions.some(r=>["running","unknown","pending"].includes(r.status))&&!e.waits.some(r=>r.status==="pending")&&!e.evidenceWaits?.some(r=>r.status==="pending")?t:void 0}function Wh(e){let t=e.actions.at(-1);return e.status==="failed"&&t?.stepId==="archive.finalize"&&t.status==="failed"&&t.claim?.executorId===Uo.id&&t.outcome?.output?.reason==="candidate-drift"&&!t.rejectedOutcomes?.some(r=>r.outcome.attempt===t.attempt)&&!e.actions.some(r=>["running","unknown","pending"].includes(r.status))&&!e.waits.some(r=>r.status==="pending")&&!e.evidenceWaits?.some(r=>r.status==="pending")?t:void 0}async function $4(e,t,r){let n=L(e.state),i=e.input,o=e.waits.some(u=>u.stepId==="verify.confirm"&&u.status==="resolved"&&u.decision?.choice==="approved");if(n.phase!=="archive"||n.status!=="active"||n.loop.stage!=="archive-ready"||!n.builder_handoff||!n.verification||n.verification_result!=="pass"||i.name!==n.name||typeof i.artifactRootRef!="string"||t.stepId!=="archive.prepare"||t.ref!=="native-archive-preflight"||!o)throw new Error("Native Archive preflight lacks a confirmed SDK result");let a=await Fe(r);if(!a||a.native.artifact_root!==i.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let s=await he(r,i.artifactRootRef,{readOnly:!0}),c=Dh.join(s.changesDir,n.name,"verification.md"),l=Dh.relative(r,c).replaceAll("\\","/");return{state:n,paths:s,reportFile:c,reportRef:l,reportStateVersion:n.state_version-1}}async function D4(e,t,r){let n=await $4(e,t,r),i=await wd({paths:n.paths,name:n.state.name,state:n.state,requireCurrentAcceptance:!1,verificationReportStateVersion:n.reportStateVersion,derivedReport:!0}),o=Dh.relative(r,i.archiveDir).replaceAll("\\","/");if(o.startsWith("../")||Dh.isAbsolute(o))throw new Error("Native Archive destination is outside the project");return{candidateId:n.state.builder_handoff.candidate_id,stateVersion:n.state.state_version,reportRef:n.reportRef,reportStateVersion:n.reportStateVersion,archiveDirRef:o,ready:i.ready,blockers:i.blockers,requiresReverification:i.requiresReverification,capabilityPeers:i.capabilityPeers,specPreview:i.specPreview}}async function Lh(e,t,r){return D4(e,t,r)}function b$(e,t,r){return JSON.stringify([r,e.runId,e.revision,t.id,t.attempt,t.claim?.token])}async function Rd(e,t,r,n=!1){let i=L(e.state),o=e.input,a=e.outputs["archive.prepare"]?.value;if(i.phase!=="archive"||i.status!=="active"||!i.builder_handoff||o.name!==i.name||typeof o.artifactRootRef!="string"||t.stepId!=="archive.execute"||t.ref!=="native-archive"||!a||a.ready!==!0||a.candidateId!==i.builder_handoff.candidate_id||a.stateVersion!==i.state_version)throw new Error("Native SDK Archive apply lacks a successful preflight for its current step");let s=await Fe(r);if(!s||s.native.artifact_root!==o.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let c=await he(r,o.artifactRootRef,{readOnly:!0});if(n){let l=await Lt(c,{kind:"archive",change:i.name});if(l?.kind!=="archive"||l.journal.spec_changes.length!==i.spec_changes.length||l.journal.spec_changes.some((u,f)=>u.capability!==i.spec_changes[f]?.capability||u.operation!==i.spec_changes[f]?.operation))throw new Error("Native Archive recovery belongs to different Spec operations");await _h({paths:c,state:i})}return{state:i,paths:c,verificationReportStateVersion:a.reportStateVersion,derivedReport:!0}}async function A$(e){let{run:t,action:r,projectRoot:n}=e;if(r.stepId==="archive.finalize")await Mh(t,r,n);else if(r.stepId==="archive.prepare"){let i=await Lh(t,r,n);if(!i.ready)throw new Error(i.blockers.join(`
381
+ `))}else r.stepId==="archive.execute"&&await Rd(t,r,n);return null}function R$(e){if(e.status==="unknown")return e.rejectedOutcomes?.find(({outcome:t})=>{let r=t.output;return t.actionId===e.id&&t.attempt===e.attempt&&t.inputHash===e.inputHash&&t.claimToken===e.claim?.token&&t.outcomeId===`${e.id}:${e.attempt}:executor-result`&&t.status==="failed"&&t.event===void 0&&r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.ready===!1&&r.reason==="candidate-drift"&&typeof r.message=="string"&&r.message.trim().length>0&&Object.keys(r).length===3})?.outcome.output}async function N$(e,t,r){let n=L(e.state),i=e.input,o=e.outputs["archive.execute"]?.value;if(n.phase!=="archive"||n.status!=="done"||!n.archived||i.name!==n.name||typeof i.artifactRootRef!="string"||t.stepId!=="archive.finalize"||t.ref!=="native-archive-finalize"||!o||o.stateVersion!==n.state_version-1||typeof o.transactionId!="string"||typeof o.archiveRef!="string")throw new Error("Native SDK Archive finalization lacks its completed Spec transaction");let a=await he(r,i.artifactRootRef,{readOnly:!0});return{state:n,paths:a,applied:o}}async function Mh(e,t,r,n=!1){return N$(e,t,r)}function xR(e,t){return{optionalView:!0,preservedReportsRef:Ya(e.runId),write:r=>xc({state:t.state,paths:t.paths,runId:e.runId,file:r})}}async function S$(e){let t=await e.runtime.inspect(e.runId),r=[...t.actions].reverse().find(o=>o.status==="unknown"&&["archive.prepare","archive.execute","archive.finalize"].includes(o.stepId));if(!r||r.status!=="unknown"||!r.claim)throw new Error("Native SDK Archive has no lost Action to recover");let n,i="succeeded";if(r.stepId==="archive.prepare"){if(r.claim.executorId!==Dc.id)throw new Error("Native SDK Archive recovery belongs to another executor");let o=await Lh(t,r,e.projectRoot);n=o,i=o.ready?"succeeded":"failed"}else if(r.stepId==="archive.execute"){if(r.claim.executorId!==Bc.id)throw new Error("Native SDK Archive recovery belongs to another executor");let o=await he(e.projectRoot,t.input.artifactRootRef,{readOnly:!0}),a=await Lt(o,{kind:"archive",change:L(t.state).name}),s=R$(r);if(!a&&s)n=s,i="failed";else{let c=a?.kind==="archive"&&a.journal.status==="specs-applied",l=await Rd(t,r,e.projectRoot,c),{state:u,paths:f}=l,d=await Lt(f,{kind:"archive",change:u.name});if(d?.kind!=="archive")throw new Error("Native SDK Archive recovery has no frozen Spec transaction");d.journal.status==="prepared"&&await Ch(l),n={...await _h({paths:f,state:u})}}}else{if(r.claim.executorId!==Uo.id)throw new Error("Native SDK Archive recovery belongs to another executor");let o=await Mh(t,r,e.projectRoot,!0),{state:a,paths:s,applied:c}=o,u=await Lt(s,{kind:"archive",change:a.name})?await yd({paths:s,state:a,runId:t.runId,transactionId:c.transactionId,archiveRef:c.archiveRef,derivedReport:xR(t,o)}):await vi({paths:s,state:a,runId:t.runId,archiveRef:c.archiveRef,allowMissingReport:!0,history:!0});if(u.transactionId!==c.transactionId||u.archiveRef!==c.archiveRef)throw new Error("Native SDK Archive recovery receipt belongs to another transaction");n=u}return e.runtime.recordOutcome({runId:t.runId,context:{requestId:`native-sdk-archive-recovery:${t.runId}:${r.id}`,projectRoot:e.projectRoot},outcome:{actionId:r.id,attempt:r.attempt,inputHash:r.inputHash,claimToken:r.claim.token,outcomeId:r.rejectedOutcomes?.length?`${r.id}:${r.attempt}:archive-recovery:${r.rejectedOutcomes.length}:${j(n)}`:`${r.id}:${r.attempt}:executor-result`,status:i,output:n}})}async function Hh(e){let{run:t,projectRoot:r}=e,n=t.actions.at(-1),i=[...t.actions].reverse().find(u=>u.stepId==="archive.execute");if(t.status!=="cancelled"||n?.stepId!=="archive.finalize"||n.status!=="cancelled"||n.claim&&n.claim.executorId!==Uo.id||i?.status!=="succeeded"||!(await nd({projectRoot:r,run:t,...e.readOnly?{}:{}})).quiescent)throw new Error("Cancelled Native Archive recovery requires applied Specs and proof that all original executions stopped");let o=t.input,a=await he(r,o.artifactRootRef,{readOnly:!0}),s=await Lt(a,{kind:"archive",change:L(t.state).name});if(s&&e.readOnly)throw new Error("取消归档仍有待收尾事务;只读诊断不能代替显式恢复");let c=await Mh(t,n,r,s===null),l=s?await yd({paths:c.paths,state:c.state,runId:t.runId,transactionId:c.applied.transactionId,archiveRef:c.applied.archiveRef,derivedReport:xR(t,c)}):await vi({paths:a,state:c.state,runId:t.runId,archiveRef:c.applied.archiveRef,allowMissingReport:!0,history:!0});if(l.transactionId!==c.applied.transactionId)throw new Error("Native SDK Archive recovery receipt belongs to another transaction");return l}var Gi,IR,Dc,qh,Bc,Vh,Uo,Fh,Nd=x(()=>{"use strict";Ui();Ji();Me();Dt();Ke();Pc();Ae();Fo();Gi=[["supervisor.parent.deliver","native-supervisor-parent-deliver"],["archive.prepare","native-archive-preflight"],["archive.execute","native-archive"],["archive.finalize","native-archive-finalize"],["supervisor.cleanup","native-supervisor-cleanup"]];IR=new Map;Dc={id:"comet-native-archive-preflight",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive-preflight",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive preflight requires a bound SDK Run");let n=await Lh(r,e,t.projectRoot);return IR.set(b$(r,e,t.projectRoot),n),{status:n.ready?"succeeded":"failed",output:n}}},qh={id:"comet-native-archive-preflight-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Dc.id)return{accepted:!1,reason:"Native Archive preflight was not run by the Runtime"};let i=r.output;if(r.status==="failed"&&i?.ready===!1&&r.event===void 0)return{accepted:!0};try{let o=b$(e,t,n.projectRoot),a=IR.get(o);IR.delete(o);let s=a??await Lh(e,t,n.projectRoot);return j(r.output)!==j(s)||r.status==="succeeded"!==s.ready||r.event!==void 0?{accepted:!1,reason:"Native Archive preflight changed after execution"}:{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}};Bc={id:"comet-native-archive-apply",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive requires a bound SDK Run");let n=await Rd(r,e,t.projectRoot),i=await Ch(n);return{status:"succeeded",output:{transactionId:i.id,archiveRef:i.archive_ref,stateVersion:i.start_state_version,specCount:i.spec_changes.length}}}};Vh={id:"comet-native-archive-apply-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Bc.id||r.event!==void 0)return{accepted:!1,reason:"Native Archive Specs were not applied by the Runtime"};try{if(r.status==="failed"){let c=R$(t);if(!c||!j4(r.output,c))return{accepted:!1,reason:"Native Archive lacks a matching rejected prewrite failure"};let{state:l,paths:u}=await Rd(e,t,n.projectRoot);return await Lt(u,{kind:"archive",change:l.name})?{accepted:!1,reason:"Native Archive has a transaction; recover its actual progress"}:{accepted:!0}}let i=t.status==="unknown",{state:o,paths:a}=await Rd(e,t,n.projectRoot,i);if(r.status!=="succeeded")return{accepted:!1,reason:"Unexpected Native Archive apply event"};let s={...await _h({paths:a,state:o})};return j(r.output)===j(s)?{accepted:!0}:{accepted:!1,reason:"Native Archive Spec application changed before commit"}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};Uo={id:"comet-native-archive-finalize",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive-finalize",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive finalization requires a bound SDK Run");let n=await N$(r,e,t.projectRoot),{state:i,paths:o,applied:a}=n,s=await yd({paths:o,state:i,runId:r.runId,transactionId:a.transactionId,archiveRef:a.archiveRef,derivedReport:xR(r,n)});if(s.transactionId!==a.transactionId||s.archiveRef!==a.archiveRef)throw new Error("Native SDK Archive receipt does not match applied Specs");return{status:"succeeded",output:s}}},Fh={id:"comet-native-archive-finalize-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Uo.id||r.event!==void 0)return{accepted:!1,reason:"Native Archive was not finalized by the Runtime"};try{let{state:i,paths:o,applied:a}=await Mh(e,t,n.projectRoot,r.status==="succeeded");if(r.status!=="succeeded")return{accepted:!1,reason:"Native Archive finalization did not succeed"};let s=await vi({paths:o,state:i,runId:e.runId,archiveRef:a.archiveRef,history:t.status==="unknown",allowMissingReport:!0});return s.transactionId!==a.transactionId||s.archiveRef!==a.archiveRef||j(r.output)!==j(s)?{accepted:!1,reason:"Native Archive receipt changed before commit"}:{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function E$(e){return["archive.prepare","archive.execute","supervisor.child.verifier","supervisor.child.integration-repair"].some(t=>e==="ACTION_FAILED: "+t)}function Qh(e,t){return t?.workflow.hash===j(An(e))}var Uh=x(()=>{"use strict";Me()});import{promises as B4}from"node:fs";import C$ from"node:path";async function Jh(e,t){let r=L(e.state),n=e.input,i=await Fe(t);if(r.phase!=="shape"||r.archived||n.name!==r.name||typeof n.artifactRootRef!="string"||i?.native.artifact_root!==n.artifactRootRef)throw new Error("Native SDK capability association is not bound to the current Shape");let o=await he(t,n.artifactRootRef),a=C$.join(o.changesDir,r.name,"capability-association.yaml"),s=C$.relative(t,a),c=await oe(t,s,{label:"Native capability association",expected:"file"});return{paths:o,file:a,inspected:c}}var _$,zh,Kh,I$=x(()=>{"use strict";st();Dt();Vt();Ke();Ae();_$={id:"comet-native-disassociate",capabilities:[],supports(e){return e.stepId==="shape.disassociate"&&e.ref==="native-disassociate"},async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native SDK project context is required");let n=e.input.activation,i=L(r.state);if(n?.expectedStateVersion!==i.state_version)throw new Error("Native SDK capability revocation references a stale Shape");let o=await Jh(r,t.projectRoot);return await Ve(o.paths,async()=>{let a=await Jh(r,t.projectRoot);a.inspected.exists&&await B4.rm(a.file)}),{status:"succeeded",output:{removed:!0}}}},zh={id:"comet-native-disassociate-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=L(e.state);if(t!=="disassociate-capability"||i.phase!=="shape"||!["active","await-user"].includes(i.status)||i.archived||r===null||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!=="expectedStateVersion"||r.expectedStateVersion!==i.state_version||!n?.projectRoot)return{accepted:!1,reason:"Native capability revocation is stale or outside Shape"};try{return(await Jh(e,n.projectRoot)).inspected.exists?{accepted:!0}:{accepted:!1,reason:"Native capability association does not exist"}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},Kh={id:"comet-native-disassociate-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status!=="succeeded"||t.stepId!=="shape.disassociate"||!n?.projectRoot||r.output?.removed!==!0)return{accepted:!1,reason:"Native capability revocation has no successful receipt"};try{return(await Jh(e,n.projectRoot)).inspected.exists?{accepted:!1,reason:"Native capability association still exists"}:{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});import Gh from"node:path";async function PR(e,t,r){jA(r);let n=L(e.state),i=e.input,o=await Fe(t);if(n.archived||n.status==="done"||i.name!==n.name||typeof i.artifactRootRef!="string"||o?.native.artifact_root!==i.artifactRootRef)throw new Error("Native SDK capability removal requires an active change");let a=await he(t,i.artifactRootRef);if(!(await oe(t,Gh.relative(t,Gh.join(a.specsDir,r,"spec.md")),{label:"Canonical Native spec",expected:"file"})).exists)throw new Error(`Canonical Native spec does not exist: ${r}`);if((await oe(t,Gh.relative(t,Gh.join(a.changesDir,n.name,"specs",r)),{label:"Native proposed spec",expected:"directory"})).exists)throw new Error(`Capability ${r} cannot be proposed and removed together`);return n}var Yh,x$,Xh,P$=x(()=>{"use strict";st();cd();Dt();Ke();Ae();Yh={id:"comet-native-remove-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=L(e.state);if(t!=="remove-capability"||!["active","await-user","blocked"].includes(i.status)||r===null||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!=="capability,expectedStateVersion"||typeof r.capability!="string"||r.expectedStateVersion!==i.state_version||!n?.projectRoot)return{accepted:!1,reason:"Native capability removal is stale or invalid"};try{return await PR(e,n.projectRoot,r.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},x$={id:"comet-native-remove",capabilities:[],supports(e){return e.stepId==="shape.remove"&&e.ref==="native-remove"},async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native SDK project context is required");let n=e.input.activation,i=L(r.state);if(typeof n?.capability!="string"||n.expectedStateVersion!==i.state_version)throw new Error("Native capability removal references a stale change");return await PR(r,t.projectRoot,n.capability),{status:"succeeded",output:{capability:n.capability}}}},Xh={id:"comet-native-remove-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){let i=t.input.activation;if(r.status!=="succeeded"||t.stepId!=="shape.remove"||!n?.projectRoot||typeof i?.capability!="string"||r.output?.capability!==i.capability)return{accepted:!1,reason:"Native capability removal has no matching receipt"};try{return await PR(e,n.projectRoot,i.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}}});function wi(e,t){let r=t.stepId==="supervisor.child.verifier",n=t.input.activation,i=e.actions.findIndex(o=>o.id===t.id);for(let o=i-1;o>=0;o-=1){let a=e.actions[o];if(a.stepId==="shape.revalidate"||a.stepId==="shape.prepare")break;if(!(a.status!=="succeeded"||a.outcome?.output?.requireIndependentReview!==!0)){if(r){let c=a.input.activation;if(a.stepId==="supervisor.child.builder"&&c?.child===n?.child)return!0}else if(["build.builder","supervisor.parent.builder"].includes(a.stepId))return!0}}return!1}var Sd=x(()=>{"use strict"});function OR(e,t){let r=L(e.state),n=new Map;for(let i of e.actions){if(i.status!=="succeeded")continue;let o=i.outcome?.output;if(i.stepId==="supervisor.prepare"){let a=Rt(t,r.name),s=wt(r.name);if(typeof o?.integrationWorktree!="string"||!we(o.integrationWorktree,a)||o.integrationBranch!==s)throw new Error("Native 需求修订的集成工作区归属不一致");n.set(s,{kind:"integration",child:null,worktree:a,branch:s,head:""})}if(i.stepId==="supervisor.child.prepare"){if(typeof o?.child!="string")throw new Error("Native 需求修订缺少 Child 归属");let a=o.child,s=Bt(t,r.name,a),c=`comet/supervisor/${r.name}/${a}`;if(typeof o.worktree!="string"||!we(o.worktree,s)||o.branch!==c)throw new Error("Native 需求修订的 Child 工作区归属不一致");n.set(c,{kind:"child",child:a,worktree:s,branch:c,head:""})}}return[...n.values()].map(i=>{let o=de(i.worktree),a=ye(i.worktree,i.branch);if(o.currentBranch!==i.branch||!o.primaryWorktreeRoot||!we(o.primaryWorktreeRoot,t)||!a)throw new Error("Native 需求修订的 Git 工作区身份已变化");return{...i,head:a}})}function is(e,t,r){let o=[...e.actions].reverse().find(a=>a.stepId==="shape.revise"&&a.status==="succeeded")?.outcome?.output?.workspaces?.find(a=>typeof a.worktree=="string"&&we(a.worktree,t)&&a.branch===r);if(!o)return null;if(ye(t,r)!==o.head)throw new Error("Native 修订后保留的工作区提交已变化,请核对原现场");return o}var TR=x(()=>{"use strict";Ze();Ae();Sr()});function jR(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return Object.keys(t).sort().join(",")!=="archiveActionId,expectedStateVersion,proposalHash,reason"||typeof t.reason!="string"||!t.reason.trim()||typeof t.expectedStateVersion!="number"||typeof t.proposalHash!="string"||typeof t.archiveActionId!="string"?null:t}async function O$(e,t,r){let n=e.actions.find(i=>i.id===t.archiveActionId);if(!n||n.status!=="cancelled"||!["archive.prepare","archive.execute"].includes(n.stepId))throw new Error("Native implementation revision has no original pending Archive action");return{drift:!0,requirementsChanged:!1,driftKind:"implementation-changed",archiveStep:n.stepId,reason:t.reason.trim()}}function DR(e){return e.waits.find(t=>{if(t.status!=="pending"||t.stepId!=="build.resume")return!1;let r=t.proposal?.activation?.failedBuilderActionId;return e.actions.some(n=>n.id===r&&n.stepId==="build.builder"&&n.status==="failed")})}function BR(e,t,r){if(e.actions.some(o=>["running","unknown"].includes(o.status)))return!1;if(["verify","archive"].includes(t.phase))return r===void 0;if(t.phase!=="build")return!1;if(t.children_contract_ref)return r===void 0;let n=tg(e);if(n)return r===n;let i=DR(e);return i!==void 0&&i.proposalHash===r}function tg(e){let t=L(e.state);if(t.phase!=="build"||t.children_contract_ref||!["running","waiting"].includes(e.status)||e.actions.some(a=>["running","unknown"].includes(a.status)))return null;let r=e.actions.filter(a=>a.status==="pending");if(r.length!==1||r[0].stepId!=="build.builder")return null;let{id:n,attempt:i,inputHash:o}=r[0];return j({actionId:n,attempt:i,inputHash:o})}var Zh,$R,eg,rg,T$,ng,WR=x(()=>{"use strict";Me();Ae();TR();Zh={id:"comet-native-implementation-revision-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=L(e.state),o=jR(r),a=e.actions.filter(l=>l.status==="pending"),s=a[0],c=[...e.waits].reverse().find(l=>l.stepId==="verify.confirm"&&l.status==="resolved"&&l.decision?.choice==="approved");return t!=="revise-implementation"||!o||!n?.projectRoot||i.phase!=="archive"||i.status!=="active"||i.archived||i.state_version!==o.expectedStateVersion||!c||c.proposalHash!==o.proposalHash||a.length!==1||s.id!==o.archiveActionId||!["archive.prepare","archive.execute"].includes(s.stepId)||e.actions.some(l=>["running","unknown"].includes(l.status))||e.actions.some(l=>l.stepId==="archive.execute"&&l.status==="succeeded")||e.waits.some(l=>l.status==="pending")||e.evidenceWaits?.some(l=>l.status==="pending")||e.ready.length>0?{accepted:!1,reason:"Native implementation revision is stale or Archive is already in progress"}:{accepted:!0}}};$R={id:"comet-native-revise-implementation",capabilities:[],supports:e=>e.stepId==="repair.implementation"&&e.ref==="native-revise-implementation",async execute(e,t,r){let n=jR(e.input.activation);if(!r||!n||!t?.projectRoot)throw new Error("Native implementation revision lacks its input");return{status:"succeeded",output:await O$(r,n,t.projectRoot)}}},eg={id:"comet-native-implementation-revision-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){let i=jR(t.input.activation);if(!i||!n?.projectRoot||r.status!=="succeeded"||t.claim?.executorId!==$R.id)return{accepted:!1,reason:"Native implementation revision has no matching read-only result"};let o=await O$(e,i,n.projectRoot);return{accepted:j(r.output)===j(o),reason:"Native candidate changed during revision"}}};rg={id:"comet-native-revise-command",version:"1",async validate({run:e,name:t,input:r}){let n=L(e.state);return t!=="revise-requirements"||n.archived||!["active","await-user","blocked"].includes(n.status)||e.status==="completed"||r===null||typeof r!="object"||Array.isArray(r)||!["expectedStateVersion,reason","expectedStateVersion,proposalHash,reason"].includes(Object.keys(r).sort().join(","))||!BR(e,n,r.proposalHash)||r.expectedStateVersion!==n.state_version||typeof r.reason!="string"||!r.reason.trim()||e.actions.some(i=>i.stepId==="archive.execute"&&["succeeded","running","unknown"].includes(i.status))?{accepted:!1,reason:"Native requirements revision is stale or cannot interrupt Archive application"}:{accepted:!0}}},T$={id:"comet-native-revise-requirements",capabilities:[],supports(e){return e.stepId==="shape.revise"&&e.ref==="native-revise-requirements"},async execute(e,t,r){if(!r)throw new Error("Native SDK Run is required");let n=e.input.activation,i=L(r.state);if(typeof n?.reason!="string"||!n.reason.trim()||n.expectedStateVersion!==i.state_version)throw new Error("Native requirements revision references a stale change");if(i.children_contract_ref&&!t?.projectRoot)throw new Error("Native Supervisor 需求修订缺少实际项目");let o=i.children_contract_ref?OR(r,t.projectRoot):void 0;return{status:"succeeded",output:{reason:n.reason.trim(),...o?{workspaces:o}:{}}}}},ng={id:"comet-native-revise-outcome",version:"1",validate({run:e,action:t,outcome:r,context:n}){let i=t.input.activation,o=L(e.state),a=!0;try{o.children_contract_ref&&(a=!!n?.projectRoot&&j(r.output?.workspaces??null)===j(OR(e,n.projectRoot)))}catch{a=!1}return{accepted:r.status==="succeeded"&&t.stepId==="shape.revise"&&typeof i?.reason=="string"&&r.output?.reason===i.reason.trim()&&a,reason:"Native requirements revision has no matching receipt"}}}});function er(e){for(let t=e.actions.length-1;t>=0;t--){let r=e.actions[t];if((r.id===e.state.children_contract_ref||r.stepId==="shape.revalidate")&&r.status==="succeeded")return e.actions.slice(t+1)}return e.actions}function LR(e){if(!Number.isSafeInteger(e.maxParallel)||e.maxParallel<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let t=new Set(e.contract.children.map(o=>o.name)),r=new Set(e.integrated),n=new Set(e.active);if(r.size!==e.integrated.length||n.size!==e.active.length)throw new Error("Native Supervisor child facts contain duplicate names");for(let o of[...r,...n]){if(!t.has(o))throw new Error(`Native Supervisor fact names unknown child ${o}`);if(r.has(o)&&n.has(o))throw new Error(`Native Supervisor child ${o} cannot be both integrated and active`)}let i=Math.max(0,e.maxParallel-n.size);return e.contract.children.filter(o=>!r.has(o.name)&&!n.has(o.name)&&o.depends_on.every(a=>r.has(a))).slice(0,i).map(o=>o.name)}var os=x(()=>{"use strict"});async function Wc(e,t){let r=L(e.state),n=e.input;if(!["build","verify","archive"].includes(r.phase)||r.name!==n.name||!r.children_contract_ref||typeof n.artifactRootRef!="string")throw new Error("Native SDK Supervisor preparation lacks a confirmed child plan");let i=await Fe(t);if(!i||i.native.artifact_root!==n.artifactRootRef)throw new Error("Native SDK Supervisor project configuration changed");let o=e.outputs["shape.revalidate"]?.value??e.outputs["shape.prepare"]?.value,a=r.children_contract??o?.children?.contract;if(!a)throw new Error("Native SDK Supervisor lacks its original approved children plan; explicitly revise requirements to confirm it");let s=r.workspace.change_branch??r.workspace.target_branch;if(!s)throw new Error("Native SDK Supervisor requires a bound Git target branch");return{state:r,config:i,contract:a,targetBranch:s}}async function sn(e,t){let r=await Wc(e,t),n=ye(t,r.targetBranch);if(!n)throw new Error("Native SDK Supervisor target branch has no commit");return{...r,targetCommit:n}}function W4(e){let t=e.input.activation;if(!t||typeof t.child!="string"||typeof ze(t)!="string"||typeof t.integrationBranch!="string"||typeof t.integrationWorktree!="string"||typeof t.targetCommit!="string")throw new Error("Native SDK Supervisor child preparation lacks its activation");return{...t,contractRef:ze(t)}}async function qR(e,t,r){let n=await sn(e,r),i=W4(t);if(!n.contract.children.some(({name:a})=>a===i.child)||ze(i,e)!==n.state.children_contract_ref||i.integrationBranch!==wt(n.state.name)||!we(i.integrationWorktree,Rt(r,n.state.name))||ye(r,i.integrationBranch)!==i.targetCommit)throw new Error("Native SDK Supervisor child preparation no longer matches its parent plan");if(de(i.integrationWorktree).currentBranch!==i.integrationBranch)throw new Error("Native SDK Supervisor integration worktree changed before child preparation");return{...n,input:i}}var VR,ig,MR,og,as=x(()=>{"use strict";vr();Ze();Dt();Ae();TR();Sr();VR={id:"native-supervisor-prepare",capabilities:[],supports(e){return e.stepId==="supervisor.prepare"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor preparation requires a bound Run and project");let n=await sn(r,t.projectRoot);is(r,Rt(t.projectRoot,n.state.name),wt(n.state.name))},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor preparation requires a bound Run and project");let n=await sn(r,t.projectRoot),i=is(r,Rt(t.projectRoot,n.state.name),wt(n.state.name)),o=await xm({projectRoot:t.projectRoot,parent:n.state.name,targetBranch:n.targetBranch,sourceConfig:n.config});return{status:"succeeded",output:{contractRef:n.state.children_contract_ref,integrationBranch:o.binding.changeBranch,integrationWorktree:o.projectRoot,targetBranch:n.targetBranch,targetCommit:n.targetCommit,integrationCommit:i?.head??n.targetCommit,maxParallelChildren:n.state.coordination_mode==="single-session"?1:n.config.native.max_parallel_children??Hu}}}},ig={id:"native-supervisor-prepare-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||!VR.supports(t))return{accepted:!1,reason:"Native SDK Supervisor preparation lacks its project"};try{let i=await sn(e,n.projectRoot),o=r.output,a=Rt(n.projectRoot,i.state.name),s=wt(i.state.name),c=is(e,a,s);if(!o||ze(o,e,t)!==i.state.children_contract_ref||o.integrationBranch!==s||typeof o.integrationWorktree!="string"||!we(o.integrationWorktree,a)||o.targetBranch!==i.targetBranch||o.targetCommit!==i.targetCommit||(o.integrationCommit??o.targetCommit)!==(c?.head??i.targetCommit))throw new Error("Native SDK Supervisor preparation result does not match its plan");if(de(a).currentBranch!==s)throw new Error("Native SDK Supervisor integration worktree has a different branch");if(ye(a,s)!==(c?.head??i.targetCommit))throw new Error("Native SDK Supervisor integration worktree head changed");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},MR={id:"native-supervisor-child-prepare",capabilities:[],supports(e){return e.stepId==="supervisor.child.prepare"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor child preparation requires a bound Run and project");let n=await qR(r,e,t.projectRoot);is(r,Bt(t.projectRoot,n.state.name,n.input.child),`comet/supervisor/${n.state.name}/${n.input.child}`)},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor child preparation requires a bound Run and project");let n=await qR(r,e,t.projectRoot);is(r,Bt(t.projectRoot,n.state.name,n.input.child),`comet/supervisor/${n.state.name}/${n.input.child}`);let i=await Pm({projectRoot:t.projectRoot,parent:n.state.name,child:n.input.child,targetBranch:n.input.integrationBranch,sourceConfig:n.config});return{status:"succeeded",output:{child:n.input.child,contractRef:n.input.contractRef,worktree:i.projectRoot,branch:i.binding.changeBranch,baseCommit:n.input.targetCommit}}}},og={id:"native-supervisor-child-prepare-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||!MR.supports(t))return{accepted:!1,reason:"Native SDK Supervisor child preparation lacks its project"};try{let i=await qR(e,t,n.projectRoot),o=r.output,a=Bt(n.projectRoot,i.state.name,i.input.child),s=`comet/supervisor/${i.state.name}/${i.input.child}`;if(!o||o.child!==i.input.child||ze(o,e)!==ze(i.input,e)||typeof o.worktree!="string"||!we(o.worktree,a)||o.branch!==s||o.baseCommit!==i.input.targetCommit)throw new Error("Native SDK Supervisor child preparation result does not match its plan");let c=de(a),l=is(e,a,s);if(c.currentBranch!==s||ye(a,s)!==o.baseCommit&&!l)throw new Error("Native SDK Supervisor child worktree changed before Builder dispatch");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});import{promises as $$}from"node:fs";import Yr from"node:path";function Lc(e){let t=e?.activation;if(!t||typeof t.child!="string"||typeof t.candidateCommit!="string"||typeof t.integrationCommit!="string"||typeof t.checksActionId!="string"&&typeof t.mergeActionId!="string"||typeof ze(t)!="string")throw new Error("Native Supervisor child archive lacks its activation");return{...t,contractRef:ze(t)}}function FR(e,t,r,n){for(let i of[...er(e)].reverse()){if(i.stepId!==t||i.status!=="succeeded"||!i.outcome||i.input?.activation?.child!==r)continue;let a=i.outcome.output;if(!(!a||!n(a)))return{action:i,output:a}}return null}async function D$(e,t,r,n=!1){let i=await sn(e,r),o=i.state,a=Lc(t.input);if(o.phase!=="build"||o.status!=="active"||!o.children_contract_ref||ze(a,e)!==o.children_contract_ref||!i.contract.children.some(({name:X})=>X===a.child)||!ss.test(a.candidateCommit)||!ss.test(a.integrationCommit))throw new Error("Native Supervisor child archive does not match the confirmed plan");let s=a.checksActionId?e.actions.find(X=>X.id===a.checksActionId):void 0,c=s?.outcome?.output;if(s&&(s.stepId!=="supervisor.child.integration-checks"||s.status!=="succeeded"||c?.candidateId!==a.integrationCommit||typeof c.completedAt!="string"))throw new Error("Native legacy archive lacks its original accepted integration result");let l=a.mergeActionId??s?.input?.activation?.mergeActionId,u=e.actions.find(X=>X.id===l),f=u?.outcome?.output,d=a.repairActionId??s?.input?.activation?.repairActionId,m=d?e.actions.find(X=>X.id===d):void 0,h=m?.outcome?.output;if(u?.stepId!=="supervisor.child.integrate"||u.status!=="succeeded"||f?.child!==a.child||(m?m.stepId!=="supervisor.child.integration-repair"||m.status!=="succeeded"||m.input.activation?.mergeActionId!==u.id||m.input.activation.child!==a.child||m.input.activation.candidateCommit!==a.candidateCommit||ze(m.input.activation,e)!==o.children_contract_ref||h?.integrationCommit!==a.integrationCommit:f.integrationCommit!==a.integrationCommit))throw new Error("Native Supervisor child archive lacks its accepted integration task");let p=c?.completedAt??q((e.outputs["supervisor.prepare"]?.value).integrationWorktree,["show","-s","--format=%cI",a.integrationCommit]).trim(),g=FR(e,"supervisor.child.verifier",a.child,X=>{let Oe=X.evidence;return X.verdict==="pass"&&X.candidateCommit===a.candidateCommit&&typeof Oe?.summary=="string"&&!!Oe.summary.trim()});if(!g||!g.action.claim?.sessionId)throw new Error("Native Supervisor child archive lacks its passing Verifier");let v=g.output.evidence,w=FR(e,"supervisor.child.builder",a.child,X=>X.candidateCommit===a.candidateCommit),y=["1","2","3"].includes(g.action.executionOrigin?.workflow.version??""),b=y?FR(e,"supervisor.child.checks",a.child,X=>X.candidateId===a.candidateCommit):null;if(y&&!b)throw new Error("Legacy Child archive lacks its original accepted checks");let N=b?.output,A=e.outputs["supervisor.prepare"]?.value;if(typeof A?.integrationWorktree!="string"||typeof A.integrationBranch!="string")throw new Error("Native Supervisor child archive lacks its integration workspace");let S=Bt(r,o.name,a.child),_=`comet/supervisor/${o.name}/${a.child}`;if(de(S).currentBranch!==_)throw new Error("Native Supervisor child worktree moved before the child archive");if(de(A.integrationWorktree).currentBranch!==A.integrationBranch)throw new Error("Native Supervisor integration worktree moved before the child archive");let Q=q(S,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(X=>X&&X!==".comet/config.yaml").map(X=>X.replaceAll("\\","/"));if(!n&&(!di(S,Q)||!di(A.integrationWorktree)))throw new Error("Native Supervisor child archive requires clean worktrees");let F=new Map;if(Array.isArray(v.acceptance))for(let X of v.acceptance)typeof X?.id!="string"||typeof X?.result!="string"||F.set(X.id,typeof X.reason=="string"?X.reason:"");let K=Ai(i.contract,a.child);for(let{id:X}of K)if(!F.has(X))throw new Error(`Native Supervisor child archive evidence does not cover acceptance ${X}`);let Z=(N?.checks??[]).map(X=>{if(typeof X.id!="string"||typeof X.name!="string"||!Array.isArray(X.argvDisplay)||typeof X.cwdRef!="string"||X.status!=="passed"||!Number.isSafeInteger(X.durationMs))throw new Error("Native Supervisor child archive requires passed Child checks");return{id:X.id,name:X.name,argvDisplay:X.argvDisplay,cwdRef:X.cwdRef,status:X.status,exitCode:typeof X.exitCode=="number"?X.exitCode:null,durationMs:X.durationMs}}),re=Array.isArray(v.risks)?v.risks.filter(X=>typeof X=="string"):[];return{parent:o.name,maxParallelChildren:i.state.coordination_mode==="single-session"?1:i.config.native.max_parallel_children??Hu,child:a.child,language:o.language,targetBranch:i.targetBranch,worktree:S,branch:_,candidateCommit:a.candidateCommit,integrationBranch:A.integrationBranch,integrationWorktree:A.integrationWorktree,integrationCommit:a.integrationCommit,builderSessionId:w?.action.claim?.sessionId??null,builderSummary:typeof w?.output.summary=="string"?w.output.summary:null,verifierSessionId:g.action.claim.sessionId,verifierSummary:v.summary,verifierRisks:re,verifierAcceptance:F,childChecks:Z,...y?{}:{reportedChecks:li(v.checks??[])},childChecksCompletedAt:N?.completedAt??p,integrationChecksCompletedAt:p,scopedAcceptance:K}}async function q4(e,t,r,n){let i=await sn(e,r),o=await he(r,i.config.native.artifact_root),a=Yr.join(o.changesDir,n.parent),s=await Qe({root:a,ref:i.state.brief,includeHash:!1}),c=await Promise.all(i.state.spec_changes.flatMap(d=>d.source?[Qe({root:a,ref:d.source,includeHash:!1})]:[])),l=n.language==="zh-CN"?"子任务归档":"Archived Child",u=n.scopedAcceptance.map(d=>`- ${d.id}: ${d.text}`).join(`
382
+ `),f=[s,...c].map(d=>`- ${d.ref}`).join(`
383
+ `);return{"brief.md":`# ${n.child}
384
+
385
+ ${l}: ${n.parent}
386
+
387
+ ${n.language==="zh-CN"?"本归档仅覆盖以下已确认验收项。Spec 是 Parent 已确认内容的快照,不表示独立 Child Spec 变更或新增验收。":"This archive covers only the confirmed acceptance below. The Spec is a snapshot of the confirmed Parent, not an independent Child Spec change or additional acceptance."}
388
+
389
+ ${u}
390
+
391
+ [Parent Spec](spec.md) · [${n.language==="zh-CN"?"来源与原始简报":"Sources and original brief"}](archive-source.md) · [${n.language==="zh-CN"?"验收记录":"Verification"}](verification.md)
392
+ `,"spec.md":c.length===0?`# Parent Spec
393
+
394
+ No Spec change was declared by the confirmed Parent.
395
+ `:c.length===1?c[0].text:c.map(d=>`# ${d.ref}
396
+
397
+ ${d.text}`).join(`
398
+
399
+ `),"archive-source.md":`# ${n.language==="zh-CN"?"归档材料来源":"Archive material sources"}
400
+
401
+ - Parent Run: ${e.runId}
402
+ - Archive Action: ${t.id}
403
+ - Contract: ${ze(Lc(t.input),e)}
404
+ - Candidate: ${n.candidateCommit}
405
+ - Verifier: ${n.verifierSessionId}
406
+ - Integration Action: ${Lc(t.input).mergeActionId??Lc(t.input).checksActionId}
407
+
408
+ ${f}
409
+
410
+ ## ${n.language==="zh-CN"?"Parent 原始简报":"Original Parent brief"}
411
+
412
+ ${s.text}`}}async function V4(e,t,r){let n=[];for(let i of Object.keys(t))await Qe({root:e,ref:i}).catch(a=>{if(a.code==="ENOENT")return null;throw a})||n.push(i);if(!r)for(let i of n)await et(Yr.join(e,i),t[i],{containedRoot:e});return n}function M4(e){let t=e.scopedAcceptance.filter(({id:n})=>L4.test(n)).map(({id:n,source:i,text:o})=>{let a=e.verifierAcceptance.get(n);return{id:n,source:i,text:o,result:"passed",reason:a?Ct(a):null}}),r=rc({name:e.child,language:e.language,workspace:{isolation:"worktree",change_branch:e.branch,target_branch:e.targetBranch,finish:"merge"}});return L({...r,created_at:e.childChecksCompletedAt,phase:"archive",status:"done",archived:!0,loop:{...r.loop,iteration:1,attempt:1,stage:"done",next_action:null},acceptance:t,builder_handoff:{candidate_id:e.candidateCommit,identity_provider:hr,builder_execution_ref:e.builderSessionId??e.verifierSessionId,iteration:1,summary:Ct(e.builderSummary??e.verifierSummary),addressed_acceptance_ids:t.map(({id:n})=>n),checks:e.childChecks.map(n=>({name:Ct(n.name),result:"passed",note:null})),checks_truncated:!1,known_limits:[],known_limits_truncated:!1,review:null,submitted_at:e.childChecksCompletedAt},verification:{candidate_id:e.candidateCommit,identity_provider:hr,verifier_execution_ref:e.verifierSessionId,iteration:1,attempt:1,assurance:e.builderSessionId===e.verifierSessionId?"self-reviewed":"skill-coordinated",verdict:"pass",...e.reportedChecks?{reported_checks:e.reportedChecks}:{},checks:e.childChecks.map(n=>({id:n.id,name:Ct(n.name),argv_display:n.argvDisplay.map(i=>Ct(i)),argv_truncated:!1,cwd_ref:n.cwdRef,status:"passed",exit_code:n.exitCode,duration_ms:n.durationMs})),summary:Ct(e.verifierSummary),risks:e.verifierRisks.map(n=>Ct(n)),risks_truncated:!1,completed_at:e.integrationChecksCompletedAt},verification_result:"pass",verification_report:"verification.md",history:[]})}async function B$(e,t){let r=await Fe(e.worktree);if(!r)throw new Error("Native Supervisor child worktree has no project config");let n=await he(e.worktree,r.native.artifact_root),i=Yr.join(n.archiveDir,t),o=Yr.resolve(i),a=Yr.resolve(n.archiveDir);if(!o.toLowerCase().startsWith(`${a.toLowerCase()}${Yr.sep}`)&&o.toLowerCase()!==a.toLowerCase())throw new Error("Native Supervisor child archive path escaped the archive root");return{target:o,relative:Yr.relative(e.worktree,o).replaceAll("\\","/"),changesDir:n.changesDir,nativeRoot:n.nativeRoot}}function QR(e){let t=e.integrationChecksCompletedAt.slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(t))throw new Error("Native Supervisor child archive lacks a valid archive date");return`${t}-${e.child}`}function ag(e,t,r){let n=q(e,["show","--name-only","--format=",t]).split(`
413
+ `).map(i=>i.trim()).filter(Boolean);if(n.length===0||n.some(i=>!i.startsWith(`${r}/`)))throw new Error(`Native Supervisor child archive commit ${t} touches paths outside ${r}`)}async function F4(e,t,r,n){let i=e.actions.findIndex(s=>s.id===t.id),o=i<0?void 0:e.actions.slice(0,i).reverse().find(s=>s.stepId==="supervisor.child.archive"&&s.status==="succeeded"&&s.input?.activation?.child===r.child),a=o?.outcome?.output;if(!o||o.claim?.executorId!==sg.id||a?.child!==r.child||a.archiveRef!==QR(r)||a.candidateCommit!==Lc(o.input).candidateCommit||a?.baseCommit!==Lc(o.input).integrationCommit||typeof a.archiveCommit!="string"||!ss.test(a.archiveCommit))throw new Error("Native Supervisor child archive lacks its accepted predecessor receipt");ag(r.worktree,a.archiveCommit,n.relative);for(let[s,c]of[[r.worktree,r.candidateCommit],[r.integrationWorktree,r.integrationCommit]])q(s,["merge-base","--is-ancestor",a.archiveCommit,c])}async function j$(e){try{return await $$.access(e),!0}catch{return!1}}var HR,ss,L4,sg,cg,UR=x(()=>{"use strict";vr();HR=tr(jr(),1);Ze();rr();bt();Xr();Dt();Ke();Ae();Ii();na();os();as();Yn();Sr();Ic();oc();ss=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,L4=/^A[1-9][0-9]*$/u;sg={id:"native-supervisor-child-archive",capabilities:[],supports(e){return e.stepId==="supervisor.child.archive"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native Supervisor child archive requires a bound Run and project");let n=await D$(r,e,t.projectRoot);if(ye(n.worktree,n.branch)!==n.candidateCommit)throw new Error("Native Supervisor child worktree moved before the child archive");if(ye(n.integrationWorktree,n.integrationBranch)!==n.integrationCommit)throw new Error("Native Supervisor integration head moved before the child archive");let i=QR(n),o=await B$(n,i),a=null;if(await j$(o.target)&&(a=await Gt(Yr.join(o.target,"comet-state.yaml")).catch(()=>null),!a||a.name!==n.child||!a.archived||a.workspace.change_branch!==n.branch))throw new Error("Native Supervisor child archive directory holds another change");let s;if(a?.verification?.candidate_id===n.candidateCommit&&a.verification.verifier_execution_ref===n.verifierSessionId&&a.verification.completed_at===n.integrationChecksCompletedAt){let u=ye(n.worktree,n.branch);if(!u||!ss.test(u))throw new Error("Native Supervisor child worktree has no archive commit");ag(n.worktree,u,o.relative),s=u}else{if(await j$(Yr.join(o.changesDir,n.child)))throw new Error(`Native Supervisor child ${n.child} still has an active change directory; archive it through the normal flow first`);let u=M4(n),f=await q4(r,e,t.projectRoot,n);if(a&&await F4(r,e,n,o),await $$.mkdir(o.target,{recursive:!0}),a){let g={...f,"comet-state.yaml":(0,HR.stringify)(u),"verification.md":pd(u)};for(let[v,w]of Object.entries(g))await et(Yr.join(o.target,v),w,{containedRoot:o.nativeRoot})}else await V4(o.target,f,!1),await et(Yr.join(o.target,"comet-state.yaml"),(0,HR.stringify)(u),{containedRoot:o.nativeRoot}),await vh({file:Yr.join(o.target,"verification.md"),state:u});if(await md({file:Yr.join(o.target,"verification.md"),stateVersion:u.state_version})!=="aligned")throw new Error("Native Supervisor child archive report is not aligned");q(n.worktree,["add","--force","--",`${o.relative}/comet-state.yaml`,`${o.relative}/verification.md`,`${o.relative}/brief.md`,`${o.relative}/spec.md`,`${o.relative}/archive-source.md`]);let m=q(n.worktree,["diff","--cached","--name-only","--",o.relative]).split(`
414
+ `).filter(Boolean);if(m.length===0)throw new Error("Native Supervisor child archive produced no committable content");let h=m.filter(g=>!g.startsWith(`${o.relative}/`));if(h.length>0)throw new Error(`Native Supervisor child archive staging left unrelated paths: ${h.join(", ")}`);q(n.worktree,["commit","-m",`chore(native): archive ${n.child}`]);let p=ye(n.worktree,n.branch);if(!p||!ss.test(p))throw new Error("Native Supervisor child archive commit is missing");ag(n.worktree,p,o.relative),s=p}let c=ye(n.integrationWorktree,n.integrationBranch);if(!c||!ss.test(c))throw new Error("Native Supervisor integration branch has no head");let l=c;try{q(n.integrationWorktree,["merge-base","--is-ancestor",s,c])}catch{q(n.integrationWorktree,["merge","--no-ff","--no-edit",n.branch]);let u=ye(n.integrationWorktree,n.integrationBranch);if(!u||!ss.test(u))throw new Error("Native Supervisor child archive merge produced no head");l=u;let f=q(n.integrationWorktree,["rev-list","--parents","-n","1",l]).split(" ");if(f.length!==3||f[1]!==c||f[2]!==s)throw new Error("Native Supervisor child archive merge is not the expected commit")}if(ye(n.worktree,n.branch)!==s)throw new Error("Native Supervisor child branch moved after the archive commit");return{status:"succeeded",output:{child:n.child,archiveRef:i,candidateCommit:n.candidateCommit,archiveCommit:s,baseCommit:n.integrationCommit,integrationCommit:l,maxParallelChildren:n.maxParallelChildren}}}},cg={id:"native-supervisor-child-archive-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==sg.id||r.status!=="succeeded")return{accepted:!1,reason:"Native Supervisor child archive was not executed by Runtime"};try{let i=await D$(e,t,n.projectRoot),o=r.output,a=QR(i);if(!o||o.child!==i.child||o.archiveRef!==a||o.candidateCommit!==i.candidateCommit||o.baseCommit!==i.integrationCommit||typeof o.archiveCommit!="string"||typeof o.integrationCommit!="string")throw new Error("Native Supervisor child archive outcome does not match its binding");let s=await B$(i,a),c=await Gt(Yr.join(s.target,"comet-state.yaml"));if(c.name!==i.child||!c.archived||c.status!=="done"||c.verification?.verdict!=="pass"||c.workspace.change_branch!==i.branch)throw new Error("Native Supervisor child archive state does not match the child");if(ag(i.worktree,o.archiveCommit,s.relative),ye(i.worktree,i.branch)!==o.archiveCommit)throw new Error("Native Supervisor child branch is not at its archive commit");let l=q(i.integrationWorktree,["rev-list","--parents","-n","1",o.integrationCommit]).split(" ");if(!l.includes(o.archiveCommit)||!l.includes(i.integrationCommit))throw new Error("Native Supervisor integration did not receive the child archive commit");if(ye(i.integrationWorktree,i.integrationBranch)!==o.integrationCommit)throw new Error("Native Supervisor integration head moved after the child archive");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});var W$,lg,ug,L$=x(()=>{"use strict";Ze();rr();vr();Ae();Sd();as();Yn();Sr();tl();W$=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,lg={id:"native-supervisor-builder-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.child.builder"||t.type!=="handoff")return{accepted:!1,reason:"Native SDK Supervisor Builder result lacks its project"};try{let i=L(e.state),o=await Wc(e,n.projectRoot),a=t.input.activation,s=r.output;if(s?.requireIndependentReview!==void 0&&typeof s.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");if(i.phase!=="build"||!t.claim?.sessionId||!a||typeof a.child!="string"||!o.contract.children.some(({name:l})=>l===a.child)||ze(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!we(a.worktree,Bt(n.projectRoot,i.name,a.child))||a.branch!==`comet/supervisor/${i.name}/${a.child}`||typeof a.baseCommit!="string"||!W$.test(a.baseCommit)||!s||typeof s.candidateCommit!="string"||!W$.test(s.candidateCommit))throw new Error("Native SDK Supervisor Builder result lacks a claimed child candidate");if(de(a.worktree).currentBranch!==a.branch||ye(a.worktree,a.branch)!==s.candidateCommit)throw new Error("Native SDK Supervisor Builder candidate does not match its worktree");return li(s.checks??[]),q(a.worktree,["merge-base","--is-ancestor",a.baseCommit,s.candidateCommit]),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},ug={id:"native-supervisor-verifier-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.child.verifier"||t.type!=="handoff")return{accepted:!1,reason:"Native SDK Supervisor Verifier lacks its project"};try{let i=L(e.state),o=await Wc(e,n.projectRoot),a=t.input.activation,s=r.output,c=s?.evidence;if(i.phase!=="build"||!t.claim?.sessionId||!a||typeof a.child!="string"||!o.contract.children.some(({name:f})=>f===a.child)||ze(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!we(a.worktree,Bt(n.projectRoot,i.name,a.child))||typeof a.candidateCommit!="string"||typeof a.builderSessionId!="string"||wi(e,t)&&t.claim.sessionId===a.builderSessionId||!s||s.candidateCommit!==a.candidateCommit||!["pass","fail","blocked"].includes(String(s.verdict))||!c||typeof c.summary!="string"||!c.summary.trim()||!Array.isArray(c.checks))throw new Error("Native SDK Supervisor Verifier lacks a bound result or required independent session");let l=li(c.checks),u=Qd(c.acceptance);return Ud({verdict:s.verdict,acceptance:u},{acceptanceIds:Ai(o.contract,a.child).map(({id:f})=>f),requiredChecksPassed:l.every(f=>f.result==="passed")}),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function JR(e,t){let n=[...e.actions].reverse().find(i=>i.stepId===t&&i.status==="succeeded")?.outcome?.output;return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function q$(e,t,r){let n=JR(e,"supervisor.prepare"),i=Rt(t,r.name),o=wt(r.name);if(!n||ze(n,e)!==r.children_contract_ref||typeof n.integrationWorktree!="string"||!we(n.integrationWorktree,i)||n.integrationBranch!==o)throw new Error("Native SDK Supervisor cleanup lacks its integration workspace");let a=new Map;for(let s of er(e)){if(s.stepId!=="supervisor.child.prepare"||s.status!=="succeeded")continue;let c=s.outcome?.output;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Native SDK Supervisor cleanup has an invalid Child receipt");let l=c;if(typeof l.child!="string"||typeof l.worktree!="string"||ze(l,e)!==r.children_contract_ref||!we(l.worktree,Bt(t,r.name,l.child))||l.branch!==`comet/supervisor/${r.name}/${l.child}`)throw new Error("Native SDK Supervisor cleanup has a mismatched Child receipt");a.set(l.child,{root:l.worktree,branch:l.branch})}if(a.size===0)throw new Error("Native SDK Supervisor cleanup has no prepared Children");return[...a.values(),{root:i,branch:o}]}function zR(e,t,r){let n=L(e.state),i=JR(e,"supervisor.parent.deliver");if(t.stepId!=="supervisor.cleanup"||n.status!=="done"||!n.archived||!n.children_contract_ref||!JR(e,"archive.finalize")||!i||typeof i.targetRoot!="string"||typeof i.targetBranch!="string"||typeof i.targetCommit!="string"||i.targetCommit!==i.integrationCommit||!Mt(r).some(o=>we(o,i.targetRoot))||de(i.targetRoot).currentBranch!==i.targetBranch||ye(i.targetRoot,i.targetBranch)!==i.targetCommit)throw new Error("Native SDK Supervisor cleanup lacks the verified delivery");return{projectRoot:r,targetRoot:i.targetRoot,targetBranch:i.targetBranch,targetCommit:i.targetCommit,candidates:q$(e,r,n)}}function V$(e,t,r,n){lc({projectRoot:t,targetRoot:Rt(t,n.name),targetBranch:wt(n.name),targetCommit:r,candidates:q$(e,t,n)})}function M$(e){return{targetBranch:e.targetBranch,targetCommit:e.targetCommit}}async function F$(e){let t=await e.runtime.inspect(e.runId),r=[...t.actions].reverse().find(i=>i.stepId==="supervisor.cleanup"&&i.status==="unknown");if(!r?.claim||r.claim.executorId!==dg.id)throw new Error("Native SDK Supervisor has no lost cleanup Action to recover");let n=zR(t,r,e.projectRoot);return await uc(n),e.runtime.recordOutcome({runId:t.runId,context:{requestId:`native-sdk-supervisor-cleanup-recovery:${t.runId}:${r.id}`,projectRoot:e.projectRoot},outcome:{actionId:r.id,attempt:r.attempt,inputHash:r.inputHash,claimToken:r.claim.token,outcomeId:`${r.id}:${r.attempt}:executor-result`,status:"succeeded",output:M$(n)}})}var dg,fg,pg=x(()=>{"use strict";vr();Ze();Ae();os();Sr();dg={id:"native-supervisor-cleanup",capabilities:[],supports(e){return e.stepId==="supervisor.cleanup"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor cleanup requires a bound Run and project");let n=zR(r,e,t.projectRoot);return await uc(n),{status:"succeeded",output:M$(n)}}},fg={id:"native-supervisor-cleanup-outcome",version:"1",validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==dg.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor cleanup was not executed by Runtime"};try{let i=zR(e,t,n.projectRoot),o=r.output;if(!o||o.targetBranch!==i.targetBranch||o.targetCommit!==i.targetCommit||!Li(i))throw new Error("Native SDK Supervisor cleanup outcome does not match the worktrees");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function qc(e,t=e.outcome){let r=e.input.activation,i=t?.output?.candidateCommit??r?.integrationCommit;if(e.stepId!=="supervisor.parent.builder"||typeof r?.integrationCommit!="string"||!H$.test(r.integrationCommit)||typeof i!="string"||!H$.test(i))throw new Error("Native Supervisor parent candidate has no valid Git commit");return i}var H$,KR=x(()=>{"use strict";H$=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});import Q$ from"node:path";async function mg(e,t,r){let n=await sn(e,r),i=L(e.state),o=t.input.activation,a=e.outputs["supervisor.prepare"]?.value,s=[...e.actions].reverse().find(v=>v.stepId==="supervisor.parent.builder"&&v.status==="succeeded"),c=s?qc(s):null,l=e.waits.some(v=>v.stepId==="verify.confirm"&&v.status==="resolved"&&v.decision?.choice==="approved"),u=e.workflow.version==="4"||e.actions.some(v=>v.stepId==="verify.revalidate"&&v.status==="succeeded"),f=wt(i.name),d=Rt(r,i.name);if(i.phase!=="archive"||i.verification_result!=="pass"||!i.verification||!i.builder_handoff||!l||!u||!o||ze(o,e)!==i.children_contract_ref||o.candidateId!==i.builder_handoff.candidate_id||o.integrationBranch!==f||typeof o.integrationWorktree!="string"||!we(o.integrationWorktree,d)||typeof o.integrationCommit!="string"||c!==o.integrationCommit||a?.targetBranch!==n.targetBranch||typeof a.targetCommit!="string"||de(d).currentBranch!==f||ye(d,f)!==o.integrationCommit)throw new Error("Native SDK Supervisor delivery lacks the approved integration candidate");let m=Mt(r).find(v=>de(v).currentBranch===n.targetBranch);if(!m)throw new Error("Native SDK Supervisor target branch worktree is unavailable");let h=ye(m,n.targetBranch),g=[...er(e)].reverse().find(v=>v.stepId==="supervisor.child.integrate"&&v.status==="succeeded")?.outcome?.output?.targetCommit??a.targetCommit;if(h!==g&&h!==o.integrationCommit)throw new Error("Native SDK Supervisor target branch changed after Shape confirmation");return q(d,["merge-base","--is-ancestor",a.targetCommit,o.integrationCommit]),V$(e,r,o.integrationCommit,i),{state:i,input:o,targetRoot:m,targetBranch:n.targetBranch,targetCommit:h,integrationBranch:f,integrationCommit:o.integrationCommit}}function U$(e){return{contractRef:e.state.children_contract_ref,integrationCommit:e.integrationCommit,targetBranch:e.targetBranch,targetRoot:e.targetRoot,targetCommit:e.integrationCommit}}function H4(e,t){try{let r=e.targetRoot;q(r,["diff","--cached","--quiet",e.integrationCommit]),q(r,["diff","--quiet"]);let n=q(r,["diff","--name-only","--no-renames","-z",e.targetCommit,e.integrationCommit]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/"));return q(r,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/")).some(o=>n.includes(o))?!1:di(r,[...t,...n])}catch{return!1}}async function J$(e,t,r,n){let i=await he(n,t.input.artifactRootRef),o=we(e.targetRoot,n)?Q$.relative(e.targetRoot,Q$.join(i.changesDir,e.state.name)).replaceAll("\\","/"):null,a=[...o?[o]:[],".comet/current-change.json",".comet/runtime"];if(!di(e.targetRoot,a)&&!(e.targetCommit!==e.integrationCommit&&r.reconciliations.some(s=>s.attempt===r.attempt-1)&&H4(e,a)))throw new Error("Native SDK Supervisor target worktree has unrelated changes")}async function z$(e,t,r){let n=await mg(e,t,r);return await J$(n,e,t,r),{targetBranch:n.targetBranch,targetRoot:n.targetRoot,targetCommit:n.targetCommit,integrationBranch:n.integrationBranch,integrationCommit:n.integrationCommit}}async function K$(e){let t=await e.runtime.inspect(e.runId),r=[...t.actions].reverse().find(i=>i.stepId==="supervisor.parent.deliver"&&i.status==="unknown");if(!r?.claim||r.claim.executorId!==hg.id)throw new Error("Native SDK Supervisor has no lost delivery Action to recover");let n=await mg(t,r,e.projectRoot);if(n.targetCommit!==n.integrationCommit)throw new Error("Native SDK Supervisor target has not received the verified integration");return e.runtime.recordOutcome({runId:t.runId,context:{requestId:`native-sdk-supervisor-delivery-recovery:${t.runId}:${r.id}`,projectRoot:e.projectRoot},outcome:{actionId:r.id,attempt:r.attempt,inputHash:r.inputHash,claimToken:r.claim.token,outcomeId:`${r.id}:${r.attempt}:executor-result`,status:"succeeded",output:U$(n)}})}var hg,gg,GR=x(()=>{"use strict";pg();vr();Ze();rr();Ke();Ae();KR();os();as();Sr();oc();hg={id:"native-supervisor-parent-deliver",capabilities:[],supports(e){return e.stepId==="supervisor.parent.deliver"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor delivery requires a bound Run and project");let n=await mg(r,e,t.projectRoot);if(await J$(n,r,e,t.projectRoot),n.targetCommit!==n.integrationCommit&&q(n.targetRoot,["merge","--ff-only",n.integrationBranch]),ye(n.targetRoot,n.targetBranch)!==n.integrationCommit)throw new Error("Native SDK Supervisor target did not receive the verified integration");return{status:"succeeded",output:U$(n)}}};gg={id:"native-supervisor-parent-deliver-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==hg.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor delivery was not executed by Runtime"};try{let i=await mg(e,t,n.projectRoot),o=r.output;if(!o||ze(o,e)!==i.state.children_contract_ref||o.integrationCommit!==i.integrationCommit||o.targetBranch!==i.targetBranch||typeof o.targetRoot!="string"||!we(o.targetRoot,i.targetRoot)||o.targetCommit!==i.integrationCommit||ye(i.targetRoot,i.targetBranch)!==i.integrationCommit)throw new Error("Native SDK Supervisor delivery outcome does not match the target");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});async function Y$(e,t,r){let n=await sn(e,r),i=L(e.state),o=t.input.activation;if(i.phase!=="build"||!o||typeof o.child!="string"||!n.contract.children.some(({name:h})=>h===o.child)||ze(o,e)!==i.children_contract_ref||typeof o.worktree!="string"||!we(o.worktree,Bt(r,i.name,o.child))||o.branch!==`comet/supervisor/${i.name}/${o.child}`||typeof o.candidateCommit!="string"||ye(o.worktree,o.branch)!==o.candidateCommit||typeof o.verifierActionId!="string"||typeof o.verifierSessionId!="string")throw new Error("Native SDK Supervisor integration lacks its verified Child candidate");let a=e.actions.find(h=>h.id===o.verifierActionId),s=a?.outcome?.output;if(a?.stepId!=="supervisor.child.verifier"||a.status!=="succeeded"||a.claim?.sessionId!==o.verifierSessionId||s?.verdict!=="pass"||s.candidateCommit!==o.candidateCommit)throw new Error("Native SDK Supervisor integration lacks a bound passing Verifier");let c=wt(i.name),l=Rt(r,i.name);if(de(l).currentBranch!==c)throw new Error("Native SDK Supervisor integration worktree changed");let u=e.actions.findIndex(h=>h.id===t.id),f=er(e).filter(h=>e.actions.indexOf(h)<u).reverse().find(h=>["supervisor.child.integrate","supervisor.child.integration-repair"].includes(h.stepId)&&h.status==="succeeded"),d=e.outputs["supervisor.prepare"]?.value,m=f?f.outcome?.output?.integrationCommit:d?.integrationCommit??d?.targetCommit;if(typeof m!="string")throw new Error("Native SDK Supervisor integration lacks its checked base commit");return{state:i,plan:n,input:o,integrationBranch:c,integrationWorktree:l,expectedBaseCommit:m}}function X$(e,t,r){let n=t;for(let i of e.actions){if(i.stepId!=="supervisor.child.archive"||i.status!=="succeeded"||!i.outcome)continue;let o=i.outcome.output;o&&typeof o.baseCommit=="string"&&typeof o.integrationCommit=="string"&&o.baseCommit===n&&(n=o.integrationCommit)}return n===r}async function G$(e,t,r){let n=await Y$(e,t,r);if(e.actions.some(a=>a.id!==t.id&&a.stepId==="supervisor.child.integrate"&&["running","unknown"].includes(a.status)))throw new Error("Another Native SDK Supervisor integration Action is unresolved");if(!Zo(n.integrationWorktree))throw new Error("Native SDK Supervisor integration worktree must be clean before merge");let i=ye(n.integrationWorktree,n.integrationBranch);if(!i||i!==n.expectedBaseCommit&&!X$(e,n.expectedBaseCommit,i))throw new Error("Native SDK Supervisor integration branch changed after the prior check");let o=e.outputs["supervisor.prepare"]?.value;if(typeof o?.targetCommit!="string")throw new Error("Native SDK Supervisor integration lacks its original target binding");return q(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,i]),q(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,n.plan.targetCommit]),{...n,baseCommit:i}}var vg,YR,wg,Z$=x(()=>{"use strict";Ze();rr();vr();Ae();Ae();os();as();Sr();vg={id:"native-supervisor-integration-repair-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};try{if(!n?.projectRoot||!t.claim?.sessionId)throw new Error("Integration repair requires its actual Agent session");let i=await sn(e,n.projectRoot),o=t.input.activation,a=r.output,s=e.actions.find(y=>y.id===o?.mergeActionId),c=s?.outcome?.output,l=e.actions.find(y=>y.id===o?.failedCheckActionId),u=e.actions.find(y=>y.id===o?.failedExtensionActionId),f=u?.input?.activation?.reviewSource,d=e.actions.find(y=>y.id===o?.repairActionId),m=d?.outcome?.output,h=d?.status==="succeeded"&&d.stepId==="supervisor.child.integration-repair"&&d.input.activation?.mergeActionId===s?.id?m?.integrationCommit:c?.integrationCommit,p=l?.status==="failed"&&l.stepId==="supervisor.child.integration-checks"&&l.input.activation?.mergeActionId===s?.id,g=u?.stepId.startsWith("native.extension.integration.")&&u.outcome&&u.outcome.output.verdict==="fail"&&f?.scope==="integration"&&(f.actionId===s?.id||f.actionId===o?.repairActionId),v=Rt(n.projectRoot,i.state.name),w=wt(i.state.name);if(!o||!p&&!g||ze(o,e)!==i.state.children_contract_ref||typeof o.child!="string"||!i.contract.children.some(y=>y.name===o.child)||s?.stepId!=="supervisor.child.integrate"||s.status!=="succeeded"||c?.child!==o.child||h!==o.integrationCommit||typeof o.integrationWorktree!="string"||!we(o.integrationWorktree,v)||o.integrationBranch!==w||!a||typeof a.summary!="string"||!a.summary.trim()||typeof a.integrationCommit!="string"||typeof o.integrationCommit!="string"||a.integrationCommit===o.integrationCommit||de(v).currentBranch!==w||ye(v,w)!==a.integrationCommit||!Zo(v))throw new Error("Integration repair does not match its original merge, failure and workspace");if(q(v,["merge-base","--is-ancestor",o.integrationCommit,a.integrationCommit]),li(a.checks??[]).some(y=>y.result==="failed"))throw new Error("Resolve failed platform checks before submitting integration repair");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};YR={id:"native-supervisor-integrate",capabilities:[],supports(e){return e.stepId==="supervisor.child.integrate"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor integration requires a bound Run and project");await G$(r,e,t.projectRoot)},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor integration requires a bound Run and project");let n=await G$(r,e,t.projectRoot),{baseCommit:i}=n;q(n.integrationWorktree,["merge-base",n.plan.targetCommit,i])===n.plan.targetCommit||q(n.integrationWorktree,["merge","--no-ff","--no-edit",n.plan.targetCommit]);let a=ye(n.integrationWorktree,n.integrationBranch);if(!a)throw new Error("Native SDK Supervisor target sync produced no commit");q(n.integrationWorktree,["merge-base",n.input.candidateCommit,a])===n.input.candidateCommit||q(n.integrationWorktree,["merge","--no-ff","--no-edit",n.input.candidateCommit]);let c=ye(n.integrationWorktree,n.integrationBranch);if(!c)throw new Error("Native SDK Supervisor merge produced no commit");return{status:"succeeded",output:{child:n.input.child,candidateCommit:n.input.candidateCommit,baseCommit:i,targetCommit:n.plan.targetCommit,targetMergeCommit:a,integrationCommit:c,integrationBranch:n.integrationBranch,integrationWorktree:n.integrationWorktree}}}},wg={id:"native-supervisor-integrate-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==YR.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor integration was not executed by Runtime"};try{let i=await Y$(e,t,n.projectRoot),o=r.output;if(!o||o.child!==i.input.child||o.candidateCommit!==i.input.candidateCommit||o.baseCommit!==i.expectedBaseCommit&&(typeof o.baseCommit!="string"||!X$(e,i.expectedBaseCommit,o.baseCommit))||typeof o.integrationCommit!="string"||o.integrationBranch!==i.integrationBranch||typeof o.integrationWorktree!="string"||!we(o.integrationWorktree,i.integrationWorktree)||ye(i.integrationWorktree,i.integrationBranch)!==o.integrationCommit)throw new Error("Native SDK Supervisor integration outcome does not match the worktree");if(!Zo(i.integrationWorktree))throw new Error("Native SDK Supervisor integration worktree changed after execution");let a=e.outputs["supervisor.prepare"]?.value,s=o.targetCommit??a.targetCommit,c=o.targetMergeCommit??o.baseCommit;if(s!==i.plan.targetCommit||typeof c!="string")throw new Error("Native SDK Supervisor target changed during integration");if(c!==o.baseCommit){let l=q(i.integrationWorktree,["rev-list","--parents","-n","1",c]).split(" ");if(l.length!==3||l[0]!==c||l[1]!==o.baseCommit||l[2]!==s)throw new Error("Native SDK Supervisor target sync is not the expected merge commit")}if(q(i.integrationWorktree,["merge-base","--is-ancestor",s,c]),o.integrationCommit===c)q(i.integrationWorktree,["merge-base","--is-ancestor",o.candidateCommit,o.integrationCommit]);else{let l=q(i.integrationWorktree,["rev-list","--parents","-n","1",o.integrationCommit]).split(" ");if(l.length!==3||l[0]!==o.integrationCommit||l[1]!==c||l[2]!==o.candidateCommit)throw new Error("Native SDK Supervisor integration is not the expected merge commit")}return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function yg(e,t){let r=L(e.state),n=t.input.activation;if(r.phase!=="build"||r.archived||!r.children_contract_ref||t.stepId!=="supervisor.child.verifier"||t.status!=="failed"||t.outcome?.status!=="failed"||!t.claim||!n||ze(n,e)!==r.children_contract_ref||typeof n.child!="string"||typeof n.candidateCommit!="string"||typeof n.builderSessionId!="string"||!er(e).some(i=>i.id===t.id))throw new Error("Native Child Verifier recovery requires a known failed current execution");return{...n,failedVerifierActionId:t.id}}function eD(e){return e.waits.filter(t=>{if(t.status!=="pending"||t.stepId!=="supervisor.child.verifier-retry")return!1;let r=t.proposal.activation;if(XR(e,t))return!0;let n=e.actions.find(i=>i.id===r?.failedVerifierActionId);return n!==void 0&&j(yg(e,n))===j(r)})}function XR(e,t){return e.actions.find(r=>["supervisor.child.checks","supervisor.child.integration-checks"].includes(r.stepId)&&r.status==="failed"&&r.outcome?.status==="failed"&&r.executionOrigin&&["1","2","3"].includes(r.executionOrigin.workflow.version)&&e.actionContexts[r.id].sequence===t.results[r.stepId]?.sequence)}var ZR=x(()=>{"use strict";Me();vr();Ae();os();as()});var sD={};Dd(sD,{assertNativeSdkStartAvailable:()=>cN,collectNativeSdkShapeProposal:()=>U4,defineNativeWorkflowApplication:()=>Vc,nativeSdkApplicationForRun:()=>sN,registerNativeSdkStartOwner:()=>Q4});import oD from"node:path";function sN(e,t=Vc()){if(e&&(e.workflow.version!=="4"||!Qh(t.workflow,e)))throw new Error("Native Run 尚未完成业务数据适配,请通过原 change 的当前入口继续;原记录与批准保留。");return t}async function cN(e){let t=await he(e.projectRoot,e.artifactRootRef,{change:e.name});if((await oe(e.projectRoot,oD.relative(e.projectRoot,Qr(t,e.name)),{label:"Native legacy change state",expected:"file"})).exists)throw new Error(`Native change ${e.name} already has legacy Runtime state`)}async function Q4(e){let t=await he(e.projectRoot,e.artifactRootRef,{change:e.name});await Ve(t,async()=>{await cN(e),await Wo(e.projectRoot,{schema:Mn,workflow:"native",change:e.name,format:"sdk",application:"native",runId:e.name})})}function aD(e){return e.phase==="shape"&&e.status==="active"&&e.loop.next_action==="prepare-shape-confirmation"?3:e.document_constraints_version??2}async function U4(e){let t=L({...e.state,document_constraints_version:aD(e.state)});if(t.phase!=="shape"||!["active","await-user"].includes(t.status))throw new Error("Native Shape proposal requires an active or pending Shape");let r=oD.join(e.paths.changesDir,t.name),n=await bh({paths:e.paths,state:t});e.materializeTargets===!0&&t.status==="active"&&t.shape_confirmation_hash===void 0&&n.some(s=>s.delta_source)&&await Ve(e.paths,()=>cR({paths:e.paths,state:t,specChanges:n}));let i=t.status==="active"&&t.loop.next_action==="prepare-shape-confirmation"&&t.shape_confirmation_hash===void 0;await uR({paths:e.paths,state:i?{...t,spec_changes:n}:t,specChanges:n});let o=e.acceptance===void 0?(await Ah({paths:e.paths,state:t,specChanges:n})).acceptance:e.acceptance.map((s,c)=>{let l=["brief.md",...n.flatMap(f=>f.source?[f.source]:[])];if(!s||typeof s.source!="string"||typeof s.text!="string"||!s.text.trim())throw new Error("Native acceptance requires a readable source reference and nonempty text");let u=Ao(s.source,"Native acceptance source");if(!l.includes(u))throw new Error("Native acceptance must reference this change brief or a declared specification");return{id:`A${c+1}`,source:u,text:s.text.trim()}});if(!o.length)throw new Error("Native Shape requires at least one acceptance criterion");let a=await dn({changeDir:r,acceptanceIds:o.map(({id:s})=>s),validation:un({...t,acceptance:o})});return{specChanges:n,acceptance:o.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l})),children:a?{contract:a.contract}:null}}function eN(e){let t={...e,status:"active",state_version:e.state_version+1,loop:{...e.loop,stage:"shape",next_action:"prepare-shape-confirmation"},acceptance:[]};return delete t.shape_confirmation_hash,delete t.children_contract_ref,delete t.children_contract,delete t.coordination_mode,L(t)}function J4(e,t){let r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:t,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:Bu(),loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};return delete r.shape_confirmation_hash,delete r.children_contract_ref,delete r.children_contract,delete r.coordination_mode,delete r.verifier_action,L(r)}function tD(e,t){let n={...tn(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ct(t),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};return delete n.shape_confirmation_hash,delete n.children_contract_ref,delete n.children_contract,delete n.coordination_mode,delete n.verifier_action,L(n)}function cs(e){if(e===null||typeof e!="object")throw new Error("Native Shape proposal missing");return e}function rD(e,t,r=!1){let n=e.input.activation,i=t;if(!n||!e.claim?.sessionId||!r&&!i?.integrationChecks)throw new Error("Native SDK Supervisor Verifier lacks its Child activation");return{...n,verifierActionId:e.id,verifierSessionId:e.claim.sessionId,...r?{}:{integrationChecks:i.integrationChecks}}}function z4(e){let t=er(e),r=new Set(t.filter(n=>n.stepId==="supervisor.child.integrate").map(n=>n.input.activation?.child));return t.find(n=>n.stepId==="supervisor.child.verifier"&&n.status==="succeeded"&&n.outcome?.output?.verdict==="pass"&&!r.has(n.input.activation?.child))??null}function tN(e,t,r){let n=t.input.activation,o=er(e).find(a=>a.stepId==="supervisor.child.builder"&&a.status==="succeeded"&&a.claim?.sessionId===n?.builderSessionId&&a.outcome?.output?.candidateCommit===n?.candidateCommit)?.input?.activation;if(!o||o.child!==n?.child)throw new Error("Native SDK Supervisor repair lacks the failed Child Builder");return{...o,[r]:t.id}}function kg(e,t){let r=[...er(e)].reverse().find(i=>i.stepId==="supervisor.parent.builder"&&i.status==="succeeded"),n=r?.input?.activation;if(!r||!n)throw new Error("Native Supervisor parent repair lacks the prior integration candidate");return{...n,integrationCommit:qc(r),...t}}function nD(e,t,r){let n=r.output,i=t.claim?.sessionId;if(["3","4"].includes(e.workflow.version)&&n?.requireIndependentReview!==void 0&&typeof n.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");let o=L(e.state);if(o.phase!=="build"||!["build.builder","supervisor.parent.builder"].includes(t.stepId)||t.type!=="handoff"||!i||!n||typeof n.summary!="string"||!n.summary.trim()||n.addressedAcceptanceIds!==void 0&&(!Array.isArray(n.addressedAcceptanceIds)||n.addressedAcceptanceIds.some(l=>typeof l!="string"))||!Array.isArray(n.checks)||!Array.isArray(n.knownLimits)||n.knownLimits.some(l=>typeof l!="string"))throw new Error("Native Builder result needs a claimed host session and a complete candidate");let a=n.checks,s=n.review;if(s!=null&&(s.status!=="passed"||typeof s.summary!="string"||typeof s.reviewerExecutionRef!="string"))throw new Error("Native Builder review is invalid");let c=Fg().captureExecutionIdentity({identityProvider:hr,executionRef:i});return rR({state:o,requireAcceptanceReview:!["3","4"].includes(e.workflow.version),input:{identity:c,summary:n.summary,addressedAcceptanceIds:n.addressedAcceptanceIds??[],acceptanceReview:n.acceptanceReview===void 0?void 0:n.acceptanceReview,checks:a,knownLimits:n.knownLimits,review:s?{status:"passed",summary:s.summary,reviewerExecutionRef:s.reviewerExecutionRef}:null,candidateId:t.id,now:typeof n.submittedAt=="string"&&!Number.isNaN(Date.parse(n.submittedAt))?new Date(n.submittedAt):new Date}})}function K4(e,t,r){let n=r.output,i=t.claim?.sessionId,o=L(e.state),a=o.builder_handoff;if(o.phase!=="verify"||o.status!=="active"||o.loop.next_action!=="await-verifier-result"||t.stepId!=="verify.verifier"||t.type!=="handoff"||r.status!=="succeeded"||!a||!i||wi(e,t)&&i===a.builder_execution_ref||!n||n.candidateId!==a.candidate_id||n.verifierExecutionRef!==i)throw new Error(`Native Verifier result is not bound to an independent current execution; candidateId must match the current candidate and verifierExecutionRef must equal the claimed sessionId ${i??"(missing)"}; use the current outcomeRequest template`);let c=e.input.maxVerifyFailures??xs;if(!Number.isSafeInteger(c)||c<1)throw new Error("Native Verify failure budget is invalid");let l=Fg(),u=l.captureExecutionIdentity({identityProvider:hr,executionRef:i}),f=nR({state:o,requireIndependentSession:!1,envelope:l.envelopeVerifierResponse({candidateId:a.candidate_id,identity:u,payload:n.response}),reportedChecks:li(n.checks??[]),maxVerifyFailures:c});if(typeof e.input.task=="string"&&f.response.result.verdict==="pass"&&f.response.result.requestReview?.result!=="aligned")throw new Error("Native pass requires requestReview aligned with the original task and authorized changes; report fail or blocked for conflicts or unresolved requirements");return{state:f.state}}function G4(e,t,r){let n=r.output;if(r.status!=="failed"||t.stepId!=="verify.verifier"||t.type!=="handoff"||!t.claim?.sessionId||!n||typeof n.summary!="string"||!n.summary.trim())throw new Error("Native Verifier execution failure needs the original claimed session and summary");let i=L(e.state);return aR({state:i,summary:n.summary})}function Vc(e="4"){if(e!=="4")throw new Error("旧 Native 受管检查定义不再支持;普通检查请使用 Agent 平台工具。");return X4()}function iD(e,t){let r=[...e.actions].reverse().find(o=>o.stepId==="shape.prepare"&&o.status==="succeeded"),n=cs(r.outcome.output),i=eR({state:t,acceptance:t.acceptance.map(({id:o,source:a,text:s})=>({id:o,source:a,text:s}))});return n.children?{state:L({...i,children_contract_ref:r.id,children_contract:n.children.contract}),next:["supervisor.prepare"]}:{state:i,next:["build.builder"]}}function Y4(e,t){let r=iR(t);if(!r.children_contract_ref)return{state:r,next:["archive.prepare"]};let n=[...e.actions].reverse().find(o=>o.stepId==="supervisor.parent.builder"&&o.status==="succeeded"),i=n?.input?.activation;if(!n||!i)throw new Error("Native Supervisor delivery lacks its parent integration candidate");return{state:r,next:[{stepId:"supervisor.parent.deliver",input:{...i,integrationCommit:qc(n),candidateId:r.builder_handoff?.candidate_id??null}}]}}function X4(){return{workflow:{id:"comet-native",version:"4",entry:"shape.prepare",commands:{"revise-implementation":{stepId:"repair.implementation",validator:{id:Zh.id,version:Zh.version}},"revise-requirements":{stepId:"shape.revise",validator:{id:rg.id,version:rg.version}},"remove-capability":{stepId:"shape.remove",validator:{id:Yh.id,version:Yh.version}},"disassociate-capability":{stepId:"shape.disassociate",validator:{id:zh.id,version:zh.version}}},stateSchema:{type:"object",required:["schema","name","phase","status","state_version","loop","acceptance"],properties:{schema:{const:"comet.native.v4"},name:{type:"string"},phase:{enum:["shape","build","verify","archive"]},status:{enum:["active","await-user","blocked","done"]},state_version:{type:"integer",minimum:1},loop:{type:"object"},acceptance:{type:"array"}}},transitionHandler:{id:"comet-native-transition",version:"1"},stateValidator:{id:aN.id,version:aN.version},steps:{"repair.implementation":{type:"call_tool",ref:"native-revise-implementation",validator:{id:eg.id,version:eg.version}},"shape.revise":{type:"call_tool",ref:"native-revise-requirements",validator:{id:ng.id,version:ng.version}},"shape.remove":{type:"call_tool",ref:"native-remove",validator:{id:Xh.id,version:Xh.version}},"shape.disassociate":{type:"call_tool",ref:"native-disassociate",validator:{id:Kh.id,version:Kh.version}},"shape.prepare":{type:"call_tool",ref:"native-shape-prepare",validator:{id:rN.id,version:rN.version}},"shape.confirm":{type:"ask_user",proposalFrom:"shape.prepare",choices:["approved","rejected"]},"supervisor.shape.confirm":{type:"ask_user",proposalFrom:"shape.prepare",choices:["multi-session","single-session","rejected"]},"build.builder":{type:"handoff",ref:"native-builder",validator:{id:nN.id,version:nN.version}},"build.resume":{type:"ask_user",proposalFrom:"build.builder",choices:["continue"]},"supervisor.prepare":{type:"call_tool",ref:"native-supervisor-prepare",validator:{id:ig.id,version:ig.version}},"supervisor.child.prepare":{type:"call_tool",ref:"native-supervisor-child-prepare",validator:{id:og.id,version:og.version}},"supervisor.child.builder":{type:"handoff",ref:"native-supervisor-builder",validator:{id:lg.id,version:lg.version}},"supervisor.child.resume":{type:"ask_user",proposalFrom:"supervisor.child.builder",choices:["continue"]},"supervisor.child.verifier":{type:"handoff",ref:"native-supervisor-verifier",validator:{id:ug.id,version:ug.version}},"supervisor.child.verifier-retry":{type:"ask_user",proposalFrom:"supervisor.child.verifier",choices:["retry","repair"]},"supervisor.child.integrate":{type:"call_tool",ref:"native-supervisor-integrate",validator:{id:wg.id,version:wg.version}},"supervisor.child.integration-repair":{type:"handoff",ref:"native-supervisor-integration-repair",validator:{id:vg.id,version:vg.version}},"supervisor.child.integration-resume":{type:"ask_user",proposalFrom:"supervisor.child.integration-repair",choices:["continue"]},"supervisor.child.archive":{type:"call_tool",ref:"native-supervisor-child-archive",validator:{id:cg.id,version:cg.version}},"supervisor.parent.builder":{type:"handoff",ref:"native-supervisor-parent-builder",validator:{id:iN.id,version:iN.version}},"supervisor.parent.resume":{type:"ask_user",proposalFrom:"supervisor.parent.builder",choices:["continue"]},"supervisor.parent.deliver":{type:"call_tool",ref:"native-supervisor-parent-deliver",validator:{id:gg.id,version:gg.version}},"supervisor.cleanup":{type:"call_tool",ref:"native-supervisor-cleanup",validator:{id:fg.id,version:fg.version}},"verify.verifier":{type:"handoff",ref:"native-verifier",validator:{id:oN.id,version:oN.version}},"verify.retry":{type:"ask_user",proposalFrom:"verify.verifier",choices:["retry"]},"verify.stop":{type:"ask_user",proposalFrom:"verify.verifier",choices:["retry","repair"]},"verify.confirm":{type:"ask_user",proposalFrom:"verify.verifier",choices:["approved","rejected","reverify"]},"archive.prepare":{type:"call_tool",ref:"native-archive-preflight",retry:"idempotent",validator:{id:qh.id,version:qh.version}},"archive.execute":{type:"call_tool",ref:"native-archive",validator:{id:Vh.id,version:Vh.version}},"archive.finalize":{type:"call_tool",ref:"native-archive-finalize",validator:{id:Fh.id,version:Fh.version}}},transitions:[{from:"repair.implementation",to:"archive.prepare"},{from:"repair.implementation",to:"archive.execute"},{from:"repair.implementation",to:"shape.prepare"},{from:"repair.implementation",to:"build.builder"},{from:"repair.implementation",to:"supervisor.parent.builder"},{from:"shape.revise",to:"shape.prepare"},{from:"shape.remove",to:"shape.prepare"},{from:"shape.disassociate",to:"shape.prepare"},{from:"shape.prepare",to:"shape.confirm"},{from:"shape.prepare",to:"supervisor.shape.confirm"},{from:"shape.confirm",to:"shape.prepare",on:"rejected"},{from:"supervisor.shape.confirm",to:"shape.prepare",on:"rejected"},{from:"supervisor.prepare",to:"supervisor.child.prepare"},{from:"supervisor.child.prepare",to:"supervisor.child.builder"},{from:"supervisor.child.builder",to:"supervisor.child.resume",on:"failed"},{from:"supervisor.child.resume",to:"supervisor.child.builder",on:"continue"},{from:"supervisor.child.verifier",to:"supervisor.child.verifier-retry",on:"failed"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.verifier",on:"retry"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.builder",on:"repair"},{from:"supervisor.child.verifier",to:"supervisor.child.integrate"},{from:"supervisor.child.verifier",to:"supervisor.child.builder"},{from:"supervisor.child.archive",to:"supervisor.child.integrate"},{from:"supervisor.child.archive",to:"supervisor.child.prepare"},{from:"supervisor.child.archive",to:"supervisor.parent.builder"},{from:"supervisor.parent.builder",to:"supervisor.parent.resume",on:"failed"},{from:"supervisor.parent.resume",to:"supervisor.parent.builder",on:"continue"},{from:"build.builder",to:"build.resume",on:"failed"},{from:"build.resume",to:"build.builder",on:"continue"},{from:"verify.verifier",to:"verify.confirm"},{from:"verify.verifier",to:"build.builder"},{from:"verify.verifier",to:"supervisor.parent.builder"},{from:"verify.verifier",to:"verify.verifier",on:"failed"},{from:"verify.verifier",to:"verify.retry",on:"failed"},{from:"verify.retry",to:"verify.verifier",on:"retry"},{from:"verify.verifier",to:"verify.stop"},{from:"verify.stop",to:"verify.verifier",on:"retry"},{from:"verify.stop",to:"build.builder",on:"repair"},{from:"verify.stop",to:"supervisor.parent.builder",on:"repair"},{from:"verify.confirm",to:"archive.prepare",on:"approved"},{from:"verify.confirm",to:"build.builder",on:"rejected"},{from:"verify.confirm",to:"supervisor.parent.builder",on:"rejected"},{from:"supervisor.parent.deliver",to:"archive.prepare"},{from:"archive.prepare",to:"archive.execute"},{from:"archive.prepare",to:"verify.stop",on:"failed"},{from:"archive.execute",to:"verify.stop",on:"failed"},{from:"archive.execute",to:"archive.finalize"},{from:"archive.finalize",to:"supervisor.cleanup"},{from:"verify.confirm",to:"verify.verifier",on:"reverify"},{from:"build.builder",to:"verify.verifier"},{from:"supervisor.parent.builder",to:"verify.verifier"},{from:"supervisor.child.builder",to:"supervisor.child.verifier"},{from:"supervisor.child.integrate",to:"supervisor.child.archive"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.integration-repair",on:"repair"},{from:"supervisor.child.integration-repair",to:"supervisor.child.archive"},{from:"supervisor.child.integration-repair",to:"supervisor.child.integration-resume",on:"failed"},{from:"supervisor.child.integration-resume",to:"supervisor.child.integration-repair",on:"continue"},{from:"shape.confirm",to:"build.builder",on:"approved"},{from:"shape.confirm",to:"supervisor.prepare",on:"approved"},{from:"supervisor.shape.confirm",to:"supervisor.prepare",on:"multi-session"},{from:"supervisor.shape.confirm",to:"supervisor.prepare",on:"single-session"},{from:"verify.confirm",to:"supervisor.parent.deliver",on:"approved"}]},transitionHandler:{id:"comet-native-transition",version:"1",apply({run:t,event:r}){let n=L(t.state);if(r.kind==="action-outcome"&&r.stepId==="repair.implementation"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output;if(!i.drift)return{state:n,next:[i.archiveStep]};if(i.requirementsChanged)return{state:tD(n,i.reason),next:["shape.prepare"]};let o=_c({state:n,reason:i.reason}),a=[...t.actions].reverse().find(s=>s.stepId==="verify.verifier"&&s.status==="succeeded");if(!a)throw new Error("Native implementation revision has no original Verifier result");return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:kg(t,{failedVerifierActionId:a.id})}]:[{stepId:"build.builder",input:{repairContext:Xc(o,t)}}]}}if(r.kind==="action-outcome"&&r.stepId==="shape.revise"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output.reason;return{state:tD(n,i),next:["shape.prepare"]}}if(r.kind==="action-outcome"&&r.stepId==="shape.remove"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output.capability,o=[...n.spec_changes.filter(a=>a.capability!==i),{capability:i,operation:"remove",source:null}].sort((a,s)=>a.capability.localeCompare(s.capability,"en"));return{state:J4(n,o),next:["shape.prepare"]}}if(r.kind==="action-outcome"&&r.stepId==="shape.disassociate")return r.outcome.status!=="succeeded"?{state:n,next:[]}:{state:eN(n),next:["shape.prepare"]};if(r.kind==="action-outcome"&&r.stepId==="shape.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=cs(r.outcome.output);return{state:tR({state:{...n,document_constraints_version:aD(n),spec_changes:i.specChanges},acceptance:i.acceptance}),next:i.children&&i.children.contract.children.length>=2?["supervisor.shape.confirm"]:["shape.confirm"]}}if(r.kind==="wait-resolved"&&r.stepId==="shape.confirm")return r.choice==="approved"?iD(t,n):{state:eN(n),next:["shape.prepare"]};if(r.kind==="wait-resolved"&&r.stepId==="supervisor.shape.confirm"){if(r.choice==="rejected")return{state:eN(n),next:["shape.prepare"]};let i=cs(t.outputs["shape.prepare"]?.value);if(!i.children||i.children.contract.children.length<2)throw new Error("Native Supervisor approval lacks its child plan");let o=r.choice,a=L({...n,coordination_mode:o});return iD(t,a)}if(r.kind==="action-outcome"&&r.stepId==="supervisor.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=cs(t.actions.find(s=>s.id===n.children_contract_ref)?.outcome?.output);if(!i.children||!n.children_contract_ref)throw new Error("Native Supervisor preparation lacks the confirmed child plan");let o=r.outcome.output,a=LR({contract:i.children.contract,integrated:[],active:[],maxParallel:n.coordination_mode==="single-session"?1:o.maxParallelChildren??2});return{state:n,next:a.map(s=>({stepId:"supervisor.child.prepare",input:{child:s,contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,targetCommit:o.integrationCommit??o.targetCommit}}))}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output;return{state:n,next:[{stepId:"supervisor.child.builder",input:i}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.builder"){if(r.outcome.status!=="succeeded"){let s=t.actions.find(l=>l.id===r.outcome.actionId),c=s?.input?.activation;if(!c||!s)throw new Error("Native SDK Supervisor Child Builder failure lacks its Action");return{state:n,next:[{stepId:"supervisor.child.resume",input:{...c,failedBuilderActionId:s.id}}]}}let i=t.actions.find(s=>s.id===r.outcome.actionId);if(!i?.claim?.sessionId)throw new Error("Native SDK Supervisor Builder Action lacks its host session");let o=i.input.activation,a=cs(t.actions.find(s=>s.id===n.children_contract_ref)?.outcome?.output);if(!o||!a.children||typeof o.child!="string")throw new Error("Native SDK Supervisor Builder lacks its confirmed child plan");return{state:n,next:[{stepId:"supervisor.child.verifier",input:{...o,candidateCommit:r.outcome.output.candidateCommit,builderSessionId:i.claim.sessionId,acceptance:Ai(a.children.contract,o.child),checks:r.outcome.output.checks??[]}}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.resume"){let o=t.waits.find(a=>a.stepId==="supervisor.child.resume"&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash)?.proposal?.activation;if(!o||typeof o.failedBuilderActionId!="string"||!t.actions.some(a=>a.id===o.failedBuilderActionId&&a.stepId==="supervisor.child.builder"&&a.status==="failed"))throw new Error("Native SDK Supervisor Child continuation lacks its failed Action");return{state:n,next:[{stepId:"supervisor.child.builder",input:o}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.verifier-retry"){let i=t.waits.find(c=>c.stepId===r.stepId&&c.decision?.id===r.decisionId&&c.proposalHash===r.proposalHash),o=i?.proposal?.activation,a=i&&XR(t,i);if(a){if(r.choice!=="repair")throw new Error("旧失败提案只允许原 repair 决定");let c=a.input.activation;return{state:n,next:[{stepId:a.stepId==="supervisor.child.integration-checks"?"supervisor.child.integration-repair":"supervisor.child.builder",input:a.stepId==="supervisor.child.integration-checks"?{...c,contractRef:n.children_contract_ref,failedCheckActionId:a.id}:tN(t,a,"failedCheckActionId")}]}}let s=t.actions.find(c=>c.id===o?.failedVerifierActionId);if(!s||!o||j(yg(t,s))!==j(o))throw new Error("Native Child Verifier recovery lacks its original failed Action");return{state:n,next:[{stepId:r.choice==="retry"?"supervisor.child.verifier":"supervisor.child.builder",input:r.choice==="retry"?o:tN(t,s,"failedVerifierActionId")}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.verifier"){if(r.outcome.status!=="succeeded"){let a=t.actions.find(s=>s.id===r.outcome.actionId);if(!a)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.verifier-retry",input:yg(t,a)}]}}let i=r.outcome.output;if(i.verdict==="fail"||i.verdict==="blocked"){let a=t.actions.find(s=>s.id===r.outcome.actionId);if(!a)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.builder",input:tN(t,a,"failedVerifierActionId")}]}}if(i.verdict!=="pass")return{state:n,next:[]};if(t.actions.some(a=>["supervisor.child.integrate","supervisor.child.integration-repair"].includes(a.stepId)&&["pending","running","unknown"].includes(a.status)))return{state:n,next:[]};let o=t.actions.find(a=>a.id===r.outcome.actionId);if(!o)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.integrate",input:rD(o,r.outcome.output,t.workflow.version==="4")}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.integrate"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let o=t.actions.find(s=>s.id===r.outcome.actionId)?.input?.activation,a=r.outcome.output;if(!o)throw new Error("Native SDK Supervisor integration lacks its Child activation");return{state:n,next:[{stepId:"supervisor.child.archive",input:{child:o.child,candidateCommit:o.candidateCommit,integrationCommit:a.integrationCommit,mergeActionId:r.outcome.actionId,contractRef:n.children_contract_ref}}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.integration-repair"){let i=t.actions.find(a=>a.id===r.outcome.actionId),o=i.input.activation;return{state:n,next:[{stepId:r.outcome.status==="failed"?"supervisor.child.integration-resume":"supervisor.child.archive",input:r.outcome.status==="failed"?{...o,failedBuilderActionId:i.id}:{...o,integrationCommit:r.outcome.output.integrationCommit,repairActionId:i.id}}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.integration-resume"){let o=t.waits.find(a=>a.stepId===r.stepId&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash).proposal.activation;if(!t.actions.some(a=>a.id===(o.failedRepairActionId??o.failedBuilderActionId)&&a.stepId==="supervisor.child.integration-repair"&&a.status==="failed"))throw new Error("Integration continuation lacks its original failed repair");return{state:n,next:[{stepId:"supervisor.child.integration-repair",input:o}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.archive"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=cs(t.actions.find(d=>d.id===n.children_contract_ref)?.outcome?.output),o=t.outputs["supervisor.prepare"]?.value;if(!i.children||!n.children_contract_ref||!o)throw new Error("Native SDK Supervisor continuation lacks its confirmed plan");let a=new Set(er(t).filter(d=>d.stepId==="supervisor.child.archive"&&d.status==="succeeded").map(d=>d.input.activation.child)),s=t.actions.find(d=>d.id===r.outcome.actionId);if(!s)throw new Error("Native SDK Supervisor archive Action missing");a.add(s.input.activation.child);let c=z4(t);if(c)return{state:n,next:[{stepId:"supervisor.child.integrate",input:rD(c,c.outcome?.output,t.workflow.version==="4")}]};let l=new Set(er(t).filter(d=>d.stepId==="supervisor.child.prepare").map(d=>d.input.activation.child).filter(d=>!a.has(d))),u=LR({contract:i.children.contract,integrated:[...a],active:[...l],maxParallel:n.coordination_mode==="single-session"?1:r.outcome.output.maxParallelChildren??2}),f=r.outcome.output;return a.size===i.children.contract.children.length?{state:n,next:[{stepId:"supervisor.parent.builder",input:{contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,integrationCommit:f.integrationCommit,acceptance:n.acceptance.map(({id:d,source:m,text:h})=>({id:d,source:m,text:h}))}}]}:{state:n,next:u.map(d=>({stepId:"supervisor.child.prepare",input:{child:d,contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,targetCommit:f.integrationCommit}}))}}if(r.kind==="action-outcome"&&r.stepId==="build.builder"){if(r.outcome.status==="failed")return{state:n,next:[{stepId:"build.resume",input:{failedBuilderActionId:r.outcome.actionId}}]};let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Builder Action is missing from its Run");let o=nD(t,i,r.outcome);return{state:hi(o),next:["verify.verifier"]}}if(r.kind==="wait-resolved"&&r.stepId==="build.resume"){let a=t.waits.find(s=>s.stepId==="build.resume"&&s.decision?.id===r.decisionId&&s.proposalHash===r.proposalHash)?.proposal?.activation?.failedBuilderActionId;if(typeof a!="string"||!t.actions.some(s=>s.id===a&&s.stepId==="build.builder"&&s.status==="failed"))throw new Error("Native SDK Builder continuation lacks its failed Action");return{state:n,next:[{stepId:"build.builder",input:{failedBuilderActionId:a}}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.parent.builder"){if(r.outcome.status==="failed"){let a=t.actions.find(c=>c.id===r.outcome.actionId),s=a?.input?.activation;if(!s||!a)throw new Error("Native SDK Supervisor parent Builder failure lacks its Action");return{state:n,next:[{stepId:"supervisor.parent.resume",input:{...s,failedBuilderActionId:a.id}}]}}let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Supervisor parent Builder Action is missing");let o=nD(t,i,r.outcome);return{state:hi(o),next:["verify.verifier"]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.parent.resume"){let o=t.waits.find(a=>a.stepId==="supervisor.parent.resume"&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash)?.proposal?.activation;if(!o||typeof o.failedBuilderActionId!="string"||!t.actions.some(a=>a.id===o.failedBuilderActionId&&a.stepId==="supervisor.parent.builder"&&a.status==="failed"))throw new Error("Native SDK Supervisor parent continuation lacks its failed Action");return{state:n,next:[{stepId:"supervisor.parent.builder",input:o}]}}if(r.kind==="action-outcome"&&r.stepId==="verify.verifier"){let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Verifier Action is missing from its Run");if(r.outcome.status==="failed"){let a=G4(t,i,r.outcome);return a.status==="blocked"?{state:a,next:["verify.retry"]}:{state:hi(a),next:["verify.verifier"]}}let o=K4(t,i,r.outcome);return{state:o.state,next:o.state.verification_result==="pass"?[{stepId:"verify.confirm",input:{report:wh(o.state,t.input.artifactRootRef)}}]:o.state.phase==="build"?n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:kg(t,{failedVerifierActionId:i.id})}]:[{stepId:"build.builder",input:{repairContext:Xc(o.state,t)}}]:["verify.stop"]}}if(r.kind==="wait-resolved"&&r.stepId==="verify.stop"){let i=t.waits.find(c=>c.stepId===r.stepId&&c.decision?.id===r.decisionId&&c.proposalHash===r.proposalHash);if(!i||!ns(n,i,t).some(({choice:c})=>c===r.choice))throw new Error("Native Verify stop decision does not match the current Run");if(r.choice==="retry")return{state:hi(oR(n,{reason:i.decision?.reason})),next:[{stepId:"verify.verifier",input:{recoveryWaitId:i.id,...i.decision?.reason===void 0?{}:{reason:i.decision.reason}}}]};let o=_c({state:n,reason:"The user chose to revise the implementation after Verify stopped."}),a=[...t.actions].reverse().find(c=>c.stepId==="verify.verifier"&&c.status==="succeeded"),s=a?void 0:t.actions.find(c=>c.stepId==="verify.checks"&&c.status==="failed"&&t.actionContexts[c.id].sequence===i.results["verify.checks"]?.sequence);if(!a&&!s)throw new Error("Native Verify stop has no original failed result");return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:kg(t,a?{failedVerifierActionId:a.id}:{failedCheckActionId:s.id})}]:[{stepId:"build.builder",input:{repairContext:Xc(o,t)}}]}}if(r.kind==="wait-resolved"&&r.stepId==="verify.retry")return{state:hi(sR(n)),next:["verify.verifier"]};if(r.kind==="wait-resolved"&&r.stepId==="verify.confirm"){let i=t.waits.find(a=>a.stepId===r.stepId&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash);if(!i||!ns(n,i,t).some(({choice:a})=>a===r.choice))throw new Error("Native Verify confirmation does not match an executable current decision");if(r.choice==="reverify"){let a=L({...n,status:"active",state_version:n.state_version+1,verification:null,verification_result:"pending",verification_report:null,acceptance:n.acceptance.map(s=>({...s,result:"pending",reason:null})),loop:{...n.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}});return{state:hi(a),next:["verify.verifier"]}}if(r.choice==="approved")return Y4(t,n);let o=_c({state:n,reason:"The user rejected the Skill-coordinated Verifier pass."});return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:kg(t,{rejectedDecisionId:r.decisionId})}]:[{stepId:"build.builder",input:{repairContext:Xc(o,t)}}]}}if(r.kind==="action-outcome"&&["archive.prepare","archive.execute"].includes(r.stepId)&&r.outcome.status==="failed"&&r.outcome.output.reason==="candidate-drift")return{state:L({...n,phase:"verify",status:"await-user",state_version:n.state_version+1,verification:null,verification_result:"pending",verification_report:null,acceptance:n.acceptance.map(o=>({...o,result:"pending",reason:null})),blockers:[{owner:"user",reason:Ct("归档候选已变化;由 Agent 核对实际修改,选择修订实现或重新验收。"),acceptance_ids:[],resolution_action:"await-user"}],loop:{...n.loop,stage:"await-user",next_action:"await-user"}}),next:["verify.stop"]};if(r.kind==="action-outcome"&&r.stepId==="supervisor.parent.deliver")return{state:n,next:r.outcome.status==="succeeded"?["archive.prepare"]:[]};if(r.kind==="action-outcome"&&r.stepId==="archive.prepare")return{state:n,next:r.outcome.status==="succeeded"?["archive.execute"]:[]};if(r.kind==="action-outcome"&&r.stepId==="archive.execute")return r.outcome.status!=="succeeded"?{state:n,next:[]}:{state:L({...n,status:"done",archived:!0,state_version:n.state_version+1,blockers:[],loop:{...n.loop,stage:"done",next_action:null}}),next:["archive.finalize"]};if(r.kind==="action-outcome"&&r.stepId==="archive.finalize")return{state:n,next:r.outcome.status==="succeeded"&&n.children_contract_ref?["supervisor.cleanup"]:[]};if(r.kind==="action-outcome"&&r.stepId==="supervisor.cleanup")return{state:n,next:[]};throw new Error(`Native SDK does not handle ${r.stepId} yet`)}},validators:[eg,ng,Xh,Kh,rN,nN,oN,qh,Vh,Fh,ig,og,lg,ug,wg,vg,iN,gg,fg,cg],stateValidators:[aN],commandValidators:[Zh,rg,Yh,zh],executors:[$R,T$,x$,_$,Dc,Bc,Uo,VR,MR,YR,hg,sg,dg]}}var rN,nN,iN,oN,aN,Ed=x(()=>{"use strict";st();vr();Ke();Yt();_R();Ze();rr();Me();Xt();Ci();vr();Ho();Dt();Ga();Vt();Qo();Ae();Ii();Zs();na();Nd();Uh();I$();P$();Ji();Sd();WR();UR();L$();pg();GR();Z$();KR();os();as();ZR();lR();Yn();Sr();Zc();rN={id:"comet-native-shape-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=e.input;if(!n?.projectRoot||typeof i.name!="string"||typeof i.artifactRootRef!="string"||!["shape.prepare","shape.revalidate"].includes(t.stepId))return{accepted:!1,reason:"Native Shape lacks its project and Action"};try{let o=cs(r.output);if(L(e.state).name!==i.name||!Array.isArray(o.acceptance)||o.acceptance.length===0||!Array.isArray(o.specChanges))throw new Error("Native Shape requires its change, specifications and acceptance criteria");return{accepted:!0}}catch(o){return{accepted:!1,reason:String(o)}}}},nN={id:"comet-native-builder-outcome",version:"1",async validate({run:e,outcome:t,context:r}){if(t.status==="failed")return{accepted:!0};let n=e.input;if(!r?.projectRoot||typeof n.name!="string"||typeof n.artifactRootRef!="string")return{accepted:!1,reason:"Native Builder result lacks its project binding"};try{if(L(e.state).name!==n.name)return{accepted:!1,reason:"Native Builder result belongs to another change"};let o=await Fe(r.projectRoot);if(!o||o.native.artifact_root!==n.artifactRootRef)return{accepted:!1,reason:"Native artifact root changed after Run creation"};let a=t.output;if(["3","4"].includes(e.workflow.version)&&a?.requireIndependentReview!==void 0&&typeof a.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");{if(a?.response||a?.verificationChecks!==void 0)throw new Error("Run checks with platform tools and submit checks reports, not Runtime check plans.");return{accepted:!0}}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},iN={id:"native-supervisor-parent-builder-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.parent.builder"||t.type!=="handoff")return{accepted:!1,reason:"Native Supervisor parent Builder lacks its project"};try{let i=await Wc(e,n.projectRoot),o=t.input.activation,a=i.state,s=Rt(n.projectRoot,a.name),c=wt(a.name),l=qc(t,r),u=new Set(er(e).filter(f=>f.stepId==="supervisor.child.archive"&&f.status==="succeeded").map(f=>f.input.activation.child));if(a.phase!=="build"||!o||ze(o,e)!==a.children_contract_ref||o.integrationBranch!==c||typeof o.integrationWorktree!="string"||!we(o.integrationWorktree,s)||typeof o.integrationCommit!="string"||de(s).currentBranch!==c||ye(s,c)!==l||u.size!==i.contract.children.length||i.contract.children.some(({name:f})=>!u.has(f)))throw new Error("Native Supervisor parent candidate is not the complete integration");return q(s,["merge-base","--is-ancestor",o.integrationCommit,l]),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},oN={id:"comet-native-verifier-outcome",version:"1",async validate({run:e,outcome:t,context:r}){let n=e.input;if(!r?.projectRoot||typeof n.artifactRootRef!="string")return{accepted:!1,reason:"Native Verifier result lacks its project binding"};try{if(t.status==="failed")return{accepted:!0};let i=await Fe(r.projectRoot);if(!i||i.native.artifact_root!==n.artifactRootRef||(n.maxVerifyFailures??xs)!==i.native.max_verify_failures)return{accepted:!1,reason:"Native project configuration changed after Run creation"};if(t.output?.response?.kind==="request-checks")throw new Error("Run additional checks with platform tools and report the final result.");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},aN={id:"comet-native-state",version:"1",validate({state:e}){try{return L(e),{accepted:!0}}catch(t){return{accepted:!1,reason:t instanceof Error?t.message:String(t)}}}}});var cD={};Dd(cD,{upgradeNativeRun:()=>Jo});function Jo(e,t,r){let n=An(t),i=j(n);if(e.workflow.hash===i&&e.workflow.version===n.version)return e;if(e.workflow.version==="4"&&e.workflow.hash!==Z4)throw new Error("Native 当前 Run 的 definition hash 不匹配;不能作为旧业务数据重新绑定。");if(e.workflow.id!=="comet-native"||!["1","2","3","4"].includes(e.workflow.version))throw new Error("Native Run 不属于可升级的内置协议");let o=L(e.state);if(o.name!==e.runId||e.input?.name!==e.runId)throw new Error("Native Run 与需求名称不一致");let a=mb(e);a.state=o;let s=d=>Object.hasOwn(n.steps,d),c=[],l={"verify.checks-stop":"verify.stop","supervisor.child.checks-stop":"supervisor.child.verifier-retry","supervisor.child.integration-checks-stop":"supervisor.child.verifier-retry"};for(let d of a.actions)s(d.stepId)||!["pending","running","unknown"].includes(d.status)||(c.push({step:d.stepId,results:a.actionContexts[d.id].results}),d.status="cancelled",d.reason="旧检查调度已移交 Agent 平台;原进程结果未确认,不代表已经停止或通过。");for(let d of a.waits)if(!(d.status!=="pending"||s(d.stepId))){if(l[d.stepId]){d.stepId=l[d.stepId];continue}throw new Error("旧 Native 待决定事项没有当前业务对应项,原提案保持不变。")}for(let d of a.evidenceWaits??[])d.status==="pending"&&!s(d.stepId)&&(c.push({step:d.stepId,results:d.results}),d.status="cancelled");let u=a.ready;a.ready=u.filter(d=>s(d.to)&&(d.from===null||s(d.from)));for(let d of u)(!s(d.to)||d.from!==null&&!s(d.from))&&c.push({step:d.to,results:d.results});if(e.status==="failed"&&e.reason?.startsWith("ACTION_FAILED: ")){let d=e.reason.slice(15),m=[...a.actions].reverse().find(h=>h.stepId===d);!s(d)&&m&&c.push({step:d,results:a.actionContexts[m.id].results})}if(o.children_contract_ref&&!a.actions.some(d=>d.id===o.children_contract_ref)){let d=[...a.waits].reverse().find(p=>["shape.confirm","supervisor.shape.confirm"].includes(p.stepId)&&p.status==="resolved"&&["approved","single-session","multi-session"].includes(p.decision?.choice??"")),m=a.actions.find(p=>p.stepId==="shape.prepare"&&p.status==="succeeded"&&a.actionContexts[p.id].sequence===d?.results["shape.prepare"]?.sequence),h=m?.outcome?.output?.children?.contract;if(!m||!h)throw new Error("旧 Supervisor 缺少原已批准的子任务方案");a.state={...o,children_contract_hash:o.children_contract_ref,children_contract_ref:m.id,children_contract:h}}let f=new Set;for(let d of c){if(["completed","cancelled"].includes(e.status))break;if(a.waits.some(v=>v.status==="pending"&&["verify.stop","verify.confirm","verify.retry"].includes(v.stepId))&&!d.step.startsWith("supervisor.child."))continue;let h=["shape.revalidate","build.checks"].includes(d.step)?["shape.confirm","supervisor.shape.confirm"]:d.step==="verify.revalidate"?["verify.confirm"]:[],p=[...a.waits].reverse().find(v=>h.includes(v.stepId)&&v.status==="resolved"&&d.results[v.stepId]?.sequence===v.sequence&&["approved","single-session","multi-session"].includes(v.decision?.choice??"")),g;if(p){let v;if(d.step==="build.checks")v={state:a.state,next:["build.builder"]};else{if(!r)throw new Error("旧批准需要当前业务转移器完成数据转换");v=r.apply({run:a,event:{kind:"wait-resolved",stepId:p.stepId,choice:p.decision.choice,proposalHash:p.proposalHash,decisionId:p.decision.id}})}if(v.next.length!==1)throw new Error("旧批准没有唯一的当前业务续行");a.state=v.state;let w=v.next[0];g={from:p.stepId,to:typeof w=="string"?w:w.stepId,results:{...p.results,[p.stepId]:{sequence:p.sequence,value:{choice:p.decision.choice,proposal:p.proposal}}},...typeof w=="string"?{}:{activation:w.input}}}else{let v=[...a.actions].reverse().find(N=>s(N.stepId)&&N.status==="succeeded"&&["build.builder","supervisor.parent.builder","supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair","verify.verifier"].includes(N.stepId)&&d.results[N.stepId]?.sequence===a.actionContexts[N.id].sequence);if(!v)throw new Error("旧 Native Run 缺少已接受的业务续行来源,原记录保持不变。");if(f.has(v.id))continue;f.add(v.id);let w=a.actionContexts[v.id],y,b;if(["supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair"].includes(v.stepId)){if(!r)throw new Error("旧 Child 需要当前业务转移器完成数据转换");let N=r.apply({run:a,event:{kind:"action-outcome",stepId:v.stepId,outcome:v.outcome}});if(N.next.length!==1)throw new Error("旧 Child 没有唯一的当前业务续行");a.state=N.state;let A=N.next[0];y=typeof A=="string"?A:A.stepId,b=typeof A=="string"?void 0:A.input,b&&typeof b=="object"&&!Array.isArray(b)&&(b={...b,contractRef:L(a.state).children_contract_ref},delete b.contractHash)}else{let N=L(a.state),A=v.stepId==="verify.verifier"&&N.verification_result==="pass";y=A?"verify.confirm":"verify.verifier",!A&&N.phase==="verify"&&N.loop.stage==="verify-ready"&&N.loop.next_action!=="await-verifier-result"&&(a.state=hi(N))}g={from:v.stepId,to:y,results:{...w.results,[v.stepId]:{sequence:w.sequence,value:v.outcome.output}},...b===void 0?{}:{activation:b}}}g.to==="verify.confirm"&&(g.activation={report:wh(L(a.state),a.input.artifactRootRef)}),a.ready.push(g),a.status="running",delete a.reason}a.workflow={id:n.id,version:n.version,hash:i};for(let d of Object.keys(a.definitionHashes))JSON.parse(d)[0]===n.id&&delete a.definitionHashes[d];return a.definitionHashes[JSON.stringify([n.id,n.version])]=i,a}var Z4,bg=x(()=>{"use strict";Ga();Ji();Me();Ae();Z4="26c4e50c65dcb5e1280529642a73b650400e3109ba6fa2efded90e03ad790443"});Sr();Pc();import pB from"node:path";import{randomUUID as Z3}from"node:crypto";ta();Zs();function Ih(e,t){return[...e,...t&&!e.includes("--project-root")?["--project-root",t]:[],...e.includes("--json")?[]:["--json"]]}function xh(e){if(e.continuation.disposition!=="blocked")return;let{state:t,continuation:r,projectRoot:n}=e,i=Ih(["comet","native","doctor",t.name],n),o=e.reason??(t.blockers.map(({reason:a})=>String(a)).join("; ")||`Native ${t.phase} requires inspection of the original execution before continuing.`);return{schema:"comet.native.recovery.v1",code:t.phase==="archive"?"archive-blocked":"runtime-recovery-required",reason:o,affectedPaths:[],owner:null,diagnosticArgs:i,recoveryArgs:r.commandArgs?Ih(r.commandArgs,n):null,preconditions:r.requiredInputs.length?r.requiredInputs.map(a=>`Resolve the recorded condition: ${a}`):["Inspect the original Action and its retained evidence before retrying."],preserved:{candidateId:t.builder_handoff?.candidate_id??null,shapeConfirmationHash:t.shape_confirmation_hash??null}}}Yn();Zc();$u();function pr(e,t,r){return e.language==="zh-CN"?r:t}function e4(e,t,r){let n=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:pr(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:pr(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:pr(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(pr(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(pr(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return n(`${pr(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a platform-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、Agent 平台报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`);if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:pr(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:pr(e,"Accept the result","接受结果"),agentInstruction:pr(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let i=r?.children.some(({status:c})=>c==="blocked")??!1,o=r?.children.some(({status:c})=>c==="needs-reverify")??!1,a=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=Jd)??!1;return i&&!o&&!a&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(pr(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(pr(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function t4(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function r4(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:n,name:i,description:o})=>({name:i,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",n,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:pr(e,o[1],o[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:pr(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function o$(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Za(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function n4(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function n$(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function i4(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function o4(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Pn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:o$({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Za("summary","--summary"),n4(e.name,e.flag)]}}function i$(e,t){return t.some(n=>/^verification\.md is (?:missing|stale|invalid)$/u.test(n))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:pr(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function a4(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Ph(e){return[Pn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Pn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function s4(e){let t={"final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(n=>{let i=n.response?.kind??n.kind;return{...r,name:i,required:!1,exclusiveGroup:"runner-input",description:t[i],template:n}}):[r])}function Gr(e,t,r={}){let n=c4(e,t,e.verifier_action?{...r,verifierExecutionRef:vb(e.verifier_action)??r.verifierExecutionRef}:r),i=xh({state:e,continuation:n,reason:r.archiveBlockers?.join("; ")||void 0});return i?{...n,recovery:i}:n}function c4(e,t,r={}){let n=i4(t)&&e.coordination_mode===void 0,i=e4(e,n,t),o={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,...e.status==="active"?{contextRequest:ms(e)}:{},mode:"execute",inputOptions:[],requiresUserDecision:i.required,userCommunication:i},a=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...o,disposition:"done",mode:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:a("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...o,disposition:"await-user",mode:"ask",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...n?["coordination-choice"]:[]],inputOptions:[Za("summary","--summary")],commandAlternatives:n?Du.map(s=>{let c=Pn({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,n$("coordination-mode","--coordination-mode",[s])]}}):[Pn({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:a("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...o,disposition:"await-user",mode:"ask",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Za("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=Pn({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],Pn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),Pn({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),...Ph({change:e.name,stateVersion:e.state_version})],runnerAction:a("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...o,disposition:"await-user",mode:"ask",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Za("summary","--summary")],commandAlternatives:[Pn({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Pn({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:a("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...o,disposition:"await-user",mode:"ask",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Za("summary","--summary")],commandAlternatives:[Pn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ph({change:e.name,stateVersion:e.state_version})],runnerAction:a("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...o,disposition:"await-user",mode:"ask",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Za("summary","--summary")],commandAlternatives:Ph({change:e.name,stateVersion:e.state_version}),runnerAction:a("none")}:{...o,disposition:"await-user",mode:"ask",action:"none",commandArgs:null,commandAlternatives:Ph({change:e.name,stateVersion:e.state_version}),userCommunication:{...o.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):o.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:o.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:a("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...o,disposition:"blocked",mode:"reconcile",action:s?"retry-verifier":"none",commandArgs:s?o$({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:a(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...o,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:o4({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:a("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...o,disposition:"blocked",mode:"reconcile",action:"repair",commandArgs:null,requiredInputs:[],inputOptions:[],runnerAction:a("none"),userCommunication:{...i,agentInstruction:"restore children.yaml and retry next; preserve the original Child tasks and approved scope. Do not dispatch or accept results while the scope is unavailable."}};if(t.allDone)return{...o,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],...e.loop.stage==="repairing"&&e.verification_result==="fail"?{commandAlternatives:[Pn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}:{},requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:h})=>h),acceptance_review:e.acceptance.map(({id:h})=>({id:h,status:Gn(Yc),evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:Gn(Kc),note:null}],known_limits:[]}}],runnerAction:a("builder-handoff")};let s=t.children.find(({status:h})=>h==="verified");if(s)return{...o,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-result"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,integrationCommit:"<actual-integration-commit>",checks:[{name:"<check-name>",status:"<passed|failed|incomplete>",reason:"<actual-result>"}]}}],runnerAction:a("none")};let c=t.children.some(({status:h})=>h==="blocked"||h==="needs-reverify"),l=t.children.some(({status:h})=>h==="needs-reverify"),u=t.children.some(({status:h})=>h==="ready"||h==="active"),f=t.supervisorStateVersion===void 0?null:t.children.find(h=>h.status==="blocked"&&(h.builderFailureCount??0)>=Jd)??null,d=f===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:f.name,stateVersion:t.supervisorStateVersion},description:pr(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},m=c&&!l&&!u&&d===null;return{...o,disposition:m?"blocked":"continue",mode:m?"reconcile":"execute",action:"advance-children",commandArgs:m?null:d!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:m?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:m?[]:d!==null?[d]:[Za("summary","--summary")],runnerAction:a("none")}}return{...o,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:Gn(Yc),evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:Gn(Kc),note:null}],known_limits:[]}}],runnerAction:a("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_ref;return{...o,userCommunication:!s&&c?{...o.userCommunication,agentInstruction:`${o.userCommunication.agentInstruction} ${pr(e,"Run necessary integration checks with platform tools and reuse applicable Child reports. Parent acceptance must cover every confirmed criterion.","使用平台工具执行必要的集成检查,复用适用的子任务报告。父级验收仍须覆盖全部已确认条目。")}`}:o.userCommunication,disposition:"continue",mode:s?"wait":"execute",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"verifier-dispatch-json-file"],inputOptions:s4([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:Gn(ea),acceptance:[{id:"<acceptance-id>",result:Gn(Gc),reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier"}}]),runnerAction:a(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...o,disposition:"blocked",mode:"reconcile",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:a("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=i$(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(f=>a4(f))?{...o,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:a("none")}:{...o,disposition:"blocked",mode:"reconcile",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:i$(e,r.archiveBlockers),runnerAction:a("none")}}return{...o,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:a("none")}}return l?{...o,disposition:"await-user",mode:"ask",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[n$("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...r4(e)],userCommunication:t4(e),runnerAction:a("none")}:{...o,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Pn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:a("none")}}return{...o,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:a("none")}}Fo();dR();bt();import{accessSync as g4,constants as v4,promises as Ir}from"node:fs";import Le from"node:path";import m$ from"node:os";var a$=tr(jr(),1);rr();eh();Xr();Ae();import l4 from"node:path";var yR=class extends Error{};async function s$(e,t){let r=await Qe({root:e.nativeRoot,ref:l4.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),n=(0,a$.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(n?.schema))throw new yR("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:L(n)}}Qc();rr();Ze();gh();Sc();pR();oc();KA();Qc();var u4=6e4,Ut=class extends Error{constructor(r,n,i){super(r,i);this.pullRequest=n;this.name="NativePullRequestFinishError"}pullRequest};function kR(e,t){try{return fs("gh",t,{cwd:e,timeoutMs:u4}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function bR(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function AR(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function c$(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function es(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function l$(e,t){let r=es(e,t),n;try{n=new URL(r)}catch(i){throw new Error(`${t} must be an absolute HTTP URL`,{cause:i})}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function Th(e,t){let r=es(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function u$(e,t){let r=bR(e,t);if(es(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:c$(r.number,`${t}.number`),url:l$(r.url,`${t}.url`),baseBranch:es(r.baseRefName,`${t}.baseRefName`),headBranch:es(r.headRefName,`${t}.headRefName`),headSha:Th(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function d4(e){let t=bR(e,"pull request finish provider output.pullRequest");return{number:c$(t.number,"pull request finish provider output.pullRequest.number"),url:l$(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:es(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:es(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Th(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function f4(e){let t=bR(AR(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=d4(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function RR(e){let t=kR(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=AR(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:u$(r[0],"gh pr list output[0]")}function d$(e){let t=kR(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=u$(AR(t,"gh pr view output"),"gh pr view output"),n=Th(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new Ut("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new Ut(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new Ut(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==n)throw new Ut(`Pull request head SHA mismatch: expected ${n}, got ${r.headSha}`,r);return r}function Oh(e){try{return RR(e)}catch{return null}}function p4(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function m4(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let o=kR(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(a=>a.trim()).find(a=>/^https?:\/\//u.test(a));if(!o)throw new Error("GitHub CLI did not return a pull request URL");if(t=RR(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==o)throw new Ut("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(i){if(i instanceof Ut)throw i;let o=Oh(e);if(!o)throw new Ut(i.message,null,{cause:i});t=o,r="reused"}let n;try{n=d$({...e,pullRequest:t})}catch(i){throw i instanceof Ut?i:new Ut(`Final GitHub pull request verification failed: ${i.message}`,t,{cause:i})}return{provider:"github-fill",disposition:r,pullRequest:n,remoteVerified:!0}}function h4(e){let[t,...r]=e.config.command,n;try{let a=fs(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${p4(e)}
415
+ `}).trim();n=f4(a)}catch(a){if(a instanceof Ut)throw a;let s=Oh(e)??e.existingPullRequest;throw new Ut(`Repository pull request finish provider failed: ${a.message}`,s,{cause:a})}let i={...n.pullRequest,state:"OPEN"};if(i.baseBranch!==e.baseBranch||i.headBranch!==e.headBranch||i.headSha!==Th(e.headSha,"Native Archive head SHA")){let a=Oh(e)??e.existingPullRequest;throw new Ut("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",a)}let o;try{o=d$({...e,pullRequest:i})}catch(a){if(a instanceof Ut)throw a;let s=Oh(e)??e.existingPullRequest??i;throw new Ut(`Final repository pull request verification failed: ${a.message}`,s,{cause:a})}return{provider:"repository-command",disposition:n.disposition,pullRequest:o,remoteVerified:!0}}function f$(e){let t=RR(e);return e.config?h4({...e,existingPullRequest:t,config:e.config}):m4({...e,existingPullRequest:t})}var rs="comet.native.workspace-finish.v1",w4="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",h$=new RegExp(`^${w4}$`,"u"),y4=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,ts=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function $h(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function g$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==rs||typeof t.name!="string"||!h$.test(t.name)||typeof t.transactionId!="string"||!y4.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Le.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(n=>typeof n!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(n=>typeof n!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(n=>typeof n=="string"&&Le.isAbsolute(n))||![r.changeBranch,r.targetBranch].every(n=>typeof n=="string"&&n.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!Le.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");$h(r.commitMessage,"commit-message"),r.mergeMessage!==null&&$h(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!ts.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(n=>typeof n=="string"&&n.length>0&&!Le.posix.isAbsolute(n)&&!Le.win32.isAbsolute(n)&&!n.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(n=>typeof n=="string")||r.sha!==null&&!ts.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!ts.test(r.target)||!ts.test(r.source)||r.sha!==null&&!ts.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:rs,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function NR(e,t){if(!h$.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Le.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function jc(e,t,r={}){let n=NR(e,t);try{let i=await Ir.lstat(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let o=g$(JSON.parse(await Ir.readFile(n,"utf8")));if(o.name!==t)throw new Error("Native workspace finish journal name is invalid");return o}catch(i){if(i.code==="ENOENT")return null;if(r.onError)return r.onError(t,i instanceof Error?i.message:String(i)),null;throw i}}async function Ki(e,t){let r=g$(t);await Pr(NR(e,r.name),r,{containedRoot:e.transactionsDir})}async function bd(e,t){try{await Ir.unlink(NR(e,t))}catch(r){if(r.code!=="ENOENT")throw r}}async function $c(e){let{plan:t,journal:r}=e,n=r?.plan;if(n){for(let a of["finish","isolation","changeBranch","targetBranch","remote"])if(t[a]!==n[a])throw new Error(`Recorded Native workspace finish ${a} changed`);for(let a of["changeRoot","primaryRoot","targetRoot"])if(t[a]!==n[a])throw new Error(`Recorded Native workspace finish ${a} changed`)}let i=e.commitMessage??n?.commitMessage??`chore(native): archive ${e.name}`,o=e.mergeMessage??n?.mergeMessage??(t.finish==="merge"?await k4(t,i,r):null);if(e.mergeMessage!==void 0&&t.finish!=="merge")throw new Error("--merge-message requires a merge workspace finish");if(n?.commitMessage!==void 0&&i!==n.commitMessage&&r?.commit){let a=q(t.changeRoot,["rev-parse","HEAD"]);if(r.commit.sha||a!==r.commit.parent&&kd(t.changeRoot,r.commit,a))throw new Error("The archive commit already exists; --commit-message cannot rewrite it")}if(n&&o!==n.mergeMessage&&r?.merge?.sha)throw new Error("The merge commit already exists; --merge-message cannot rewrite it");return{...t,commitMessage:i,mergeMessage:o}}async function k4(e,t,r){let n=Le.resolve(m$.tmpdir()),i=await Ir.mkdtemp(Le.join(n,"comet-native-merge-preview-"));if(!Tc(n,i)||Le.resolve(i)===n)throw new Error("Native merge preview temporary directory is outside its root");try{let o=q(e.changeRoot,["rev-parse","--show-object-format"]),a=Le.join(i,"hooks");await Ir.mkdir(a,{recursive:!0}),q(i,["-c",`core.hooksPath=${a}`,"init","--bare","--template=",`--object-format=${o}`]),q(i,["config","core.hooksPath",a]);let s=q(e.changeRoot,["rev-parse","--path-format=absolute","--git-common-dir"]);await Ir.writeFile(Le.join(i,"objects/info/alternates"),`${Le.join(s,"objects").replaceAll("\\","/")}
416
+ `);let c=["-c","commit.gpgsign=false"];for(let p of["user.name","user.email","author.name","author.email","committer.name","committer.email","i18n.commitEncoding","merge.log","merge.branchdesc","merge.suppressDest",`branch.${e.changeBranch}.description`]){let g;try{g=q(e.targetRoot??e.changeRoot,["config","--null","--get-all",p]).split("\0").filter(Boolean)}catch{continue}p==="merge.suppressDest"&&c.push("-c",`${p}=`);for(let v of g)c.push("-c",`${p}=${v}`)}let l=q(e.changeRoot,["rev-parse",`refs/heads/${e.changeBranch}`]),u=r?.commit,f=u&&l!==u.parent&&kd(e.changeRoot,u,l),d=l;if(!f){let p=Le.join(i,"archive-message");await Ir.writeFile(p,t);let g=q(e.changeRoot,["rev-parse",`${l}^{tree}`]);d=q(i,[...c,"commit-tree",g,"-p",l,"-F",p])}let m=q(e.changeRoot,["rev-parse",`refs/heads/${e.targetBranch}`]);q(i,["update-ref","--no-deref","HEAD",m]),q(i,["update-ref",`refs/heads/${e.changeBranch}`,d]);let h=Le.join(i,"merge-head");return await Ir.writeFile(h,`${d} branch '${e.changeBranch}' of .
417
+ `),q(i,[...c,"fmt-merge-msg",...v$(e,e.targetRoot??e.changeRoot),"--into-name",e.targetBranch,"-F",h])}finally{Tc(n,i)&&Le.resolve(i)!==n&&await Ir.rm(i,{recursive:!0,force:!0})}}function v$(e,t){let r;try{r=q(t,["config","--get",`branch.${e.targetBranch}.mergeOptions`])}catch{return[]}return r.split(/\s+/u).map(n=>n.replace(/^(['"])(.*)\1$/u,"$2")).filter(n=>/^--(?:no-log|log(?:=\d+)?)$/u.test(n))}async function SR(e,t){if(!t.archiveDir||!Tc(e.archiveDir,t.archiveDir)||Le.resolve(e.archiveDir)===Le.resolve(t.archiveDir))throw new Error("Native workspace finish journal has no safe archived change directory");let r=await s$(e,Le.join(t.archiveDir,"comet-state.yaml"));if(r.state.name!==t.name||!r.state.archived||r.state.status!=="done"||t.createdAt!==void 0&&r.state.created_at!==t.createdAt)throw new Error("Native workspace finish journal does not match a completed Archive record");return r}function w$(e,t,r){return q(e,r?["ls-tree","-r","-z",r,"--",...t]:["ls-files","--stage","-z","--",...t]).split("\0").filter(Boolean).map(i=>{let o=r?/^(\d+) (?:blob|commit) ([a-f0-9]+)\t([\s\S]+)$/u.exec(i):/^(\d+) ([a-f0-9]+) 0\t([\s\S]+)$/u.exec(i);if(!o)throw new Error("Native workspace finish encountered an unresolved index entry");return`${o[1]} ${o[2]} ${o[3]}`}).sort()}function kd(e,t,r){try{return q(e,["merge-base","--is-ancestor",t.parent,r]),t.sha&&q(e,["merge-base","--is-ancestor",t.sha,r]),JSON.stringify(w$(e,t.paths,r))===JSON.stringify(t.entries)}catch{return!1}}async function b4(e,t,r,n,i){let o=[];async function a(s){for(let c of await Ir.readdir(s,{withFileTypes:!0})){if(c.isSymbolicLink())throw new Error("Native archived record contains a symbolic link");let l=Le.join(s,c.name);c.isDirectory()?await a(l):c.isFile()&&o.push(l)}}await a(r);for(let s of t.spec_changes){let c=hh(e,s.capability);await k$(c)&&o.push(c)}try{if(q(n,["ls-tree","-r","--name-only",i,"--",zn(e.projectRoot,dd(e,t.name))]))return!1;let s=l=>{let u=zn(e.projectRoot,l);return q(n,["rev-parse",`${i}:${u}`])===q(n,["hash-object","--path",u,"--",l])};if(Le.resolve(n)!==Le.resolve(e.projectRoot))return o.every(s);let c=o.map(l=>zn(e.projectRoot,l));for(let l=0;l<c.length;){let u=l,f=0;for(;u<c.length&&u-l<32;){let m=Buffer.byteLength(JSON.stringify(c[u]),"utf8")+1;if(u>l&&f+m>8192)break;f+=m,u++}let d=c.slice(l,u);try{let m=q(n,["--literal-pathspecs","ls-tree","-r","-z",i,"--",...d]).split("\0").filter(Boolean),h=new Map;for(let g of m){let v=/^\d+ blob ([a-f0-9]+)\t([\s\S]+)$/u.exec(g);if(!v||!ts.test(v[1]))return!1;h.set(v[2],v[1])}let p=q(n,["hash-object","--",...d]).split(/\r?\n/u);if(p.length!==d.length||p.some((g,v)=>!ts.test(g)||g!==h.get(d[v])))return!1}catch{if(!o.slice(l,u).every(s))return!1}l=u}return!0}catch{return!1}}async function A4(e,t){let r=await Ir.mkdtemp(Le.join(m$.tmpdir(),"comet-native-merge-message-")),n=Le.join(r,"merge-head");try{let i=q(e.changeRoot,["rev-parse",`refs/heads/${e.changeBranch}`]);return await Ir.writeFile(n,`${i} branch '${e.changeBranch}' of .
418
+ `),q(t,["fmt-merge-msg",...v$(e,t),"--into-name",e.targetBranch,"-F",n])}finally{await Ir.unlink(n).catch(()=>{}),await Ir.rmdir(r)}}var Oc=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},Kn=class extends Error{constructor(r,n,i="Native workspace finish is blocked"){super(`${i}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=n;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function Tc(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}function zn(e,t){let r=Le.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||Le.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function jh(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function R4(e,t,r,n=[]){let i=[...ic(e.projectRoot)?[".comet/config.yaml"]:[],zn(e.projectRoot,dd(e,t.name)),zn(e.projectRoot,fR(e))];r&&i.push(zn(e.projectRoot,r));for(let o of r?t.spec_changes:n)i.push(zn(e.projectRoot,hh(e,o.capability)));return i}function N4(e,t){let r=eo(e).filter(n=>!jh(n,t));if(r.length>0)throw new Kn(r,e)}function S4(e,t){return t.map(r=>Le.resolve(e,...r.split("/")))}function E4(e){let t=eo(e).filter(r=>!(r===".comet/config.yaml"&&ic(e)));if(t.length>0)throw new Kn(S4(e,t),e,`Native merge target worktree is not clean: ${e}`)}function y$(e){return e.split("\0").filter(Boolean)}function C4(e,t){return y$(q(e,["ls-files","-z","--",t]))}function _4(e,t){return y$(q(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function p$(e){try{if(q(e,["config","--get","user.name"])&&q(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function I4(e,t){for(let r of Mt(e))if(de(r).currentBranch===t)return r;return null}function x4(e,t){try{fs(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function P4(e,t){if(!t)return;let r=t.command[0];try{if(Le.posix.isAbsolute(r)||Le.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let i=Le.resolve(e,r);if(!Tc(e,i))throw new Error("configured executable escapes the project root");g4(i,v4.X_OK);return}fs(process.platform==="win32"?"where":"which",[r],{timeoutMs:1e4})}catch(n){throw new Error(`Configured Native pull request finish executable is not available: ${r}`,{cause:n})}}async function Ad(e){let{paths:t,state:r}=e,n=r.workspace,i=de(t.projectRoot);if(n.isolation==="current"){if(!i.isGitWorktree)return null;if(!i.primaryWorktreeRoot||!i.currentBranch)throw new Error("Native current workspace finish requires a registered Git branch");return p$(t.projectRoot),{finish:"keep",changeRoot:t.projectRoot,primaryRoot:i.primaryWorktreeRoot,changeBranch:i.currentBranch,targetBranch:i.currentBranch,targetRoot:t.projectRoot,remote:null,isolation:"current",pullRequestFinish:null}}if(!n.finish||!n.change_branch||!n.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(n.change_branch===n.target_branch)throw new Error("Native change and target branches must be different for workspace finish");if(!i.primaryWorktreeRoot||i.currentBranch!==n.change_branch)throw new Error(`Native workspace finish requires branch ${n.change_branch} in the current registered worktree`);p$(t.projectRoot);let o=R4(t,r,e.archiveDir,e.appliedSpecChanges);n.finish!=="keep"&&N4(t.projectRoot,o);let a=n.isolation==="branch"?t.projectRoot:I4(i.primaryWorktreeRoot,n.target_branch);if(n.finish==="merge"&&n.isolation==="worktree"){if(!a)throw new Error(`Native merge finish requires a registered worktree on target branch ${n.target_branch}`);E4(a)}let s=n.finish==="push"||n.finish==="pull-request"?LN(t.projectRoot,n.change_branch):null;return n.finish==="pull-request"&&(x4("gh",["--version"]),P4(t.projectRoot,e.pullRequestFinish)),{finish:n.finish,changeRoot:t.projectRoot,primaryRoot:i.primaryWorktreeRoot,changeBranch:n.change_branch,targetBranch:n.target_branch,targetRoot:a,remote:s,isolation:n.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function k$(e){try{return await Ir.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function O4(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},blockedPaths:[],message:null,diagnosticArgs:null,recoveryArgs:null}}async function T4(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(Tc(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return await Vu(e.changeRoot),q(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function ER(e){let t=O4(e.plan),r=null,n=null,i=!1,o=await jc(e.paths,e.name),a=async()=>{o&&(o={...o,result:{...t},updatedAt:new Date().toISOString()},await Ki(e.paths,o))};try{let s=[zn(e.paths.projectRoot,dd(e.paths,e.name)),zn(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(g=>zn(e.paths.projectRoot,hh(e.paths,g.capability))),zn(e.paths.projectRoot,fR(e.paths))];if(o?.commit&&JSON.stringify(o.commit.paths)!==JSON.stringify(s))throw new Error("Recorded Native archive commit scope does not match this change");let c=e.plan.isolation==="current"||e.plan.finish==="keep",l=q(e.plan.changeRoot,["rev-parse","HEAD"]);if(o?.commit&&(o.commit.sha||l!==o.commit.parent)){if(!kd(e.plan.changeRoot,o.commit,l))throw new Error("Recorded Native archive commit does not match the current branch or archived contents");if(eo(e.plan.changeRoot).some(g=>jh(g,s)))throw new Error("Native archived contents changed after the archive commit");t.commit=l}let u=eo(e.plan.changeRoot).filter(g=>!jh(g,s)&&!(g===".comet/config.yaml"&&ic(e.plan.changeRoot)));if(u.length>0&&!c)throw t.blockedPaths=u,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${u.join(", ")}`);let f=[],d=new Set;for(let g of s){let v=Le.resolve(e.paths.projectRoot,...g.split("/"));if(C4(e.plan.changeRoot,g).length>0&&f.push(g),await k$(v))for(let y of _4(e.plan.changeRoot,g))d.add(y)}if(!t.commit&&f.length>0&&q(e.plan.changeRoot,["add","-u","--",...f]),!t.commit&&d.size>0&&q(e.plan.changeRoot,["add","--",...d]),q(e.plan.changeRoot,["diff","--cached","--name-only","-z","--",...s])&&!t.commit){let g=[...new Set([...f,...d])];if(o){let v=w$(e.plan.changeRoot,s);if(o.commit&&JSON.stringify(v)!==JSON.stringify(o.commit.entries))throw new Error("Native archived contents changed since the rejected commit; restore the recorded contents before retrying");o={...o,commit:o.commit??{parent:l,paths:s,entries:v,sha:null}},await a()}try{q(e.plan.changeRoot,c?["commit","--only","-m",e.plan.commitMessage??`chore(native): archive ${e.name}`,"--",...g]:["commit","-m",e.plan.commitMessage??`chore(native): archive ${e.name}`])}catch(v){let w=q(e.plan.changeRoot,["rev-parse","HEAD"]);if(!o?.commit||w===o.commit.parent||!kd(e.plan.changeRoot,o.commit,w))throw v}}if(t.commit=q(e.plan.changeRoot,["rev-parse","HEAD"]),o){if(o.commit&&!kd(e.plan.changeRoot,o.commit,t.commit))throw new Error("Native archive commit does not contain the recorded archived contents");let g=await SR(e.paths,o);if(!await b4(e.paths,g.state,e.archiveDir,e.plan.changeRoot,t.commit))throw new Error("Native archive files are not committed with their expected contents");o.commit&&(o={...o,commit:{...o.commit,sha:t.commit}}),await a()}let h=eo(e.plan.changeRoot).filter(g=>jh(g,s));if(h.length>0)throw new Error(`Native archive commit left change-owned working-tree changes: ${h.join(", ")}`);if(!c&&!di(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){q(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,await a(),e.plan.finish==="pull-request"&&(t.pullRequest=f$({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url,await a());let g=Tc(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!g?(await Vu(e.plan.changeRoot),q(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}n=e.plan.targetRoot??e.plan.changeRoot,e.plan.isolation==="branch"&&(q(n,["switch",e.plan.targetBranch]),r=n);let p=!1;try{q(n,["merge-base","--is-ancestor",t.commit,`refs/heads/${e.plan.targetBranch}`]),p=!0}catch{}if(!p){BN(n,e.plan.changeRoot,t.commit);let g=e.plan.mergeMessage??await A4(e.plan,n);o&&(o={...o,plan:{...e.plan,mergeMessage:g},merge:{target:q(n,["rev-parse","HEAD"]),source:t.commit,sha:null}},await a()),i=!0;try{q(n,["merge","--no-ff","--no-edit","--no-log","-m",g,e.plan.changeBranch])}catch(v){try{q(n,["merge-base","--is-ancestor",t.commit,"HEAD"])}catch{throw v}}}return t.merged=!0,t.targetRoot=n,o?.merge&&(o={...o,merge:{...o.merge,sha:q(n,["rev-parse","HEAD"])}}),await a(),t.cleanup=await T4(e.plan),t}catch(s){if(s instanceof Ut&&s.pullRequest&&(t.pullRequestUrl=s.pullRequest.url),i&&n&&!t.merged)try{q(n,["rev-parse","--verify","MERGE_HEAD"])===t.commit&&q(n,["merge","--abort"])}catch{}if(r!==null){let c;try{q(r,["merge","--abort"])}catch{}try{de(r).currentBranch===e.plan.targetBranch&&q(r,["switch",e.plan.changeBranch]),c=de(r).currentBranch===e.plan.changeBranch}catch{c=!1}c||(t.targetRoot=r)}throw t.status="blocked",t.message=s.message,t.diagnosticArgs=["git","-C",e.plan.finish==="merge"&&t.targetRoot?t.targetRoot:e.plan.changeRoot,"status","--short"],t.recoveryArgs=["comet","native","archive",e.name,"--confirmed"],await a(),new Oc(t)}}Xt();yo();ti();ju();Me();Ac();Xt();st();Dt();Vt();Ke();Ae();Yt();Ed();bg();import{promises as SD}from"node:fs";import Pd from"node:path";pc();Pc();Me();yr();import{AsyncLocalStorage as t3}from"node:async_hooks";rb();import{createHash as r3,randomUUID as Cge}from"node:crypto";import dD from"node:path";jw();import{promises as Ag}from"node:fs";import lN from"node:path";async function lD(e,t){let r=Tw(e),n=lN.join(r.workspaceRoot,"observability"),i=r.dataRoot;for(let a of["","workspaces",r.workspaceId,"observability"]){i=lN.join(i,a);let s;try{s=await Ag.lstat(i)}catch(c){if(!t||c.code!=="ENOENT")throw c;await Ag.mkdir(i,{recursive:a===""}).catch(l=>{if(l.code!=="EEXIST")throw l}),s=await Ag.lstat(i)}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let o=lN.join(n,"performance.sqlite");for(let a of["","-wal","-shm"])try{let s=await Ag.lstat(o+a);if(!s.isFile()||s.isSymbolicLink()||s.size>64*1024*1024)throw new Error("Runtime 统计文件无效")}catch(s){if(s.code!=="ENOENT")throw s}return o}import{stripVTControlCharacters as e3}from"node:util";function uD(e,t=process.env){let r=e3(e).replace(/(Bearer\s+)[^\s"']+/giu,"$1[redacted]").replace(/((?:api[_-]?key|auth[_-]?token|access[_-]?token|_authToken|password|secret)\s*[=:]\s*["']?)[^\s"',}]+/giu,"$1[redacted]").replace(/(https?:\/\/[^\s/:]+:)[^\s@]+@/giu,"$1[redacted]@");for(let[n,i]of Object.entries(t))i&&i.length>=6&&/key|token|password|secret|credential/iu.test(n)&&(r=r.split(i).join("[redacted]"));return r}var n3=864e5,i3=1e4,fD=new t3;function uN(e){let t=fD.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function Cd(e,t){return uD(e).slice(0,t)}async function pD(e,t){if(!t.length)return;let r=fD.getStore();if(r){let i=o=>process.platform==="win32"?dD.resolve(o).toLowerCase():dD.resolve(o);if(i(e)===i(await r.projectRoot())){r.spans.push(...t);return}}let n=dm(await lD(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
419
+ CREATE TABLE IF NOT EXISTS trace_spans (
420
+ id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
421
+ change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
422
+ parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
423
+ started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
424
+ revision INTEGER NOT NULL, data TEXT NOT NULL);
425
+ CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
426
+ CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
427
+ BEGIN IMMEDIATE;`);let i=n.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
428
+ ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
429
+ started_at=COALESCE(trace_spans.started_at,excluded.started_at),
430
+ ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
431
+ WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
432
+ ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
433
+ revision=MAX(trace_spans.revision,excluded.revision),
434
+ data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
435
+ WHERE excluded.revision >= trace_spans.revision OR (trace_spans.started_at IS NULL AND excluded.started_at IS NOT NULL)`),o=t.length>1e3?[...t.filter(a=>a.parentSpanId===null),...t.filter(a=>a.parentSpanId!==null).slice(-999)].slice(0,1e3):t;for(let a of o){if(!a.change||!a.runId||!a.traceId||!a.spanId||a.change.length>240||a.runId.length>240||a.traceId.length>512||a.spanId.length>512||(a.parentSpanId?.length??0)>512)continue;let s={...a,name:Cd(a.name,240),summary:a.summary?Cd(a.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(a.attributes??{}).slice(0,20).map(([u,f])=>[Cd(u,80),Array.isArray(f)?f.slice(0,30).map(d=>Cd(d,240)):typeof f=="string"?Cd(f,2e3):f]))};t.length>1e3&&a.parentSpanId===null&&(s.attributes.truncated=!0);let c=JSON.stringify(s);for(;Buffer.byteLength(c,"utf8")>4096;){let u=Object.keys(s.attributes).reverse().find(f=>f!=="truncated");if(u)delete s.attributes[u];else if(s.summary)s.summary=s.summary.slice(0,Math.floor(s.summary.length*.75));else break;c=JSON.stringify(s)}if(Buffer.byteLength(c,"utf8")>4096)continue;let l=r3("sha256").update(JSON.stringify([a.traceId,a.spanId])).digest("hex");i.run(l,a.traceId,a.workflow,a.change,a.runId,a.spanId,a.parentSpanId,a.kind,s.name,a.status,a.startedAt,a.endedAt,a.updatedAt,a.revision,c)}n.prepare("DELETE FROM trace_spans WHERE updated_at < ?").run(new Date(Date.now()-7*n3).toISOString()),n.prepare("DELETE FROM trace_spans WHERE id IN (SELECT id FROM trace_spans ORDER BY updated_at DESC, id DESC LIMIT -1 OFFSET ?)").run(i3),n.exec("COMMIT")}finally{n.close()}}var o3=(e,t)=>`workflow:${e}:${t}`,mD=(e,t)=>{let r=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(r[0])?r[1]??r[0]:r[0]},hD=e=>({runId:e.runId,revision:e.revision,status:e.status,actions:e.actions.map(t=>({id:t.id,attempt:t.attempt,status:t.status,reason:t.reason,...t.outcome?{outcome:{outcomeId:t.outcome.outcomeId,summary:t.outcome.summary}}:{}})),waits:e.waits.map(t=>({id:t.id,status:t.status})),evidenceWaits:e.evidenceWaits?.map(t=>({id:t.id,status:t.status}))}),gD=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function a3(e){let{workflow:t,previous:r,next:n,initial:i,observedAt:o}=e,a=o3(t,n.runId),s=`run:${n.runId}`,c={workflow:t,change:n.runId,runId:n.runId,traceId:a,updatedAt:o,revision:n.revision},l=["completed","failed","cancelled"].includes(n.status),u=new Map(r?.actions.map(d=>[`${d.id}:${d.attempt}`,d])),f=[{...c,spanId:s,parentSpanId:null,kind:"workflow",name:n.workflow.id,status:n.status==="completed"?"succeeded":n.status,startedAt:i?o:null,endedAt:l&&(i||r!==null&&r.status!==n.status)?o:null,summary:n.reason,attributes:{workflowVersion:n.workflow.version,sequence:n.sequence,parentRunIds:n.lineage,childRunIds:n.children.map(d=>d.runId)}}];for(let d of n.actions){let m=u.get(`${d.id}:${d.attempt}`);if(m&&m.status===d.status&&m.outcome?.outcomeId===d.outcome?.outcomeId&&m.reason===d.reason&&m.outcome?.summary===d.outcome?.summary)continue;let h=["succeeded","failed","cancelled"].includes(d.status);f.push({...c,spanId:`action:${d.id}:${d.attempt}`,parentSpanId:s,kind:"action",name:d.stepId,status:d.status,attempt:d.attempt,startedAt:d.status==="running"&&(m?.status==="pending"||i)?o:null,endedAt:h&&(i||r!==null)?o:null,summary:d.outcome?.summary??d.reason,attributes:{phase:mD(d.stepId,t),actionId:d.id,actionType:d.type,ref:d.ref??null,executor:d.claim?.executorId??null,inputFields:gD(d.input),outputFields:d.outcome?gD(d.outcome.output):[],artifacts:(d.outcome?.artifacts??[]).map(p=>p.uri)}})}for(let d of["wait","evidence"]){let m=d==="wait"?n.waits:n.evidenceWaits??[],h=d==="wait"?r?.waits:r?.evidenceWaits,p=new Map(h?.map(g=>[g.id,g]));for(let g of m){let v=p.get(g.id);v?.status!==g.status&&f.push({...c,spanId:`${d}:${g.id}`,parentSpanId:s,kind:d,name:g.stepId,status:g.status==="pending"?"waiting":g.status==="resolved"?"succeeded":g.status==="cancelled"?"cancelled":"unknown",startedAt:!v&&(r!==null||i)&&g.status==="pending"?o:null,endedAt:g.status!=="pending"&&(i||r!==null)?o:null,attributes:{phase:mD(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return f}function vD(e,t,r){let n=null;return{...r,...r.restoreCheckpoint?{restoreCheckpoint:(i,o,a)=>r.restoreCheckpoint(i,o,a)}:{},async read(i){let o=await r.read(i);try{n=o?hD(o):null}catch{n=null}return o&&uN({workflow:t,change:o.runId,runId:o.runId}),o},async compareAndSwap(i,o,a){let s=n?.runId===i&&n.revision===o?n:null,c=await r.compareAndSwap(i,o,a);if(c){uN({workflow:t,change:i,runId:i});try{await pD(e,a3({workflow:t,previous:s,next:a,initial:o===null,observedAt:new Date().toISOString()}))}catch{}try{n=hD(a)}catch{n=null}}return c}}}yr();var bD=tr(jr(),1);ju();import{promises as mN}from"node:fs";import{isDeepStrictEqual as fN}from"node:util";import zo from"node:path";Fo();Ed();Uh();bg();Me();Xt();Bo();yr();Ui();Vt();Ke();Pc();Ic();Ae();import wD from"node:path";async function _d(e){let t=e.run.input;if(typeof t?.artifactRootRef!="string"||!Number.isSafeInteger(e.run.revision)||(await qe(e.projectRoot,"native",e.run.runId,{readOnly:!0}))?.application!=="native")return!1;if(await vt({singleWriter:!0,rootDir:wD.join(Ue(e.projectRoot),"sdk-runs","native")}).readDisposition(e.run.runId)==="closed")return dN(e);let i=await he(e.projectRoot,t.artifactRootRef,{readOnly:!0});return Ve(i,()=>dN(e))}async function dN(e){let{projectRoot:t}=e,r=await qe(t,"native",e.run.runId,{readOnly:!0});if(!r||r.application!=="native")return!1;let n=vt({singleWriter:!0,rootDir:wD.join(Ue(t),"sdk-runs","native")}),i=await n.read(r.runId);if(!i||i.revision!==e.run.revision||!["cancelled","completed"].includes(i.status))return!1;let o=sN(null),a=Jo(i,o.workflow,o.transitionHandler),s=Jo(e.run,o.workflow,o.transitionHandler);if(j(a)!==j(s))throw new Error("Native Run content changed at the same revision before history closure");if(!Qh(o.workflow,a))throw new Error("Native history requires a known built-in workflow definition");let c=await cr({...o,workflows:[o.workflow],transitionHandlers:[o.transitionHandler],store:{read:async()=>a,compareAndSwap:async()=>!1}}).inspect(r.runId),l=L(c.state),u=c.input;if(c.runId!==r.change||c.workflow.id!=="comet-native"||l.name!==r.change||u?.name!==r.change||typeof u.artifactRootRef!="string")throw new Error("Native history Run does not match its change ownership");if(await n.readDisposition(c.runId)==="closed")return await Vb(t,r),!0;if(c.ready.length>0||c.waits.some(f=>f.status==="pending")||c.evidenceWaits?.some(f=>f.status==="pending"))return!1;if(c.status==="cancelled"){if((await Qi({projectRoot:t,run:c}))?.status!=="cancelled")return!1}else{if(!l.archived||l.phase!=="archive"||l.status!=="done"||!(await nd({projectRoot:t,run:c})).quiescent)return!1;let f=await Ur(t);if(f.status==="selected"&&f.selection.workflow==="native"&&f.selection.change===c.runId)return!1;let d=c.outputs["archive.execute"]?.value,m=c.outputs["archive.finalize"]?.value;if(!d||typeof d.archiveRef!="string"||typeof d.transactionId!="string"||d.stateVersion!==l.state_version-1||!m)return!1;let h=await he(t,u.artifactRootRef,{readOnly:!0}),p=await vi({paths:h,state:l,runId:c.runId,archiveRef:d.archiveRef,history:!0,allowMissingReport:["3","4"].includes(c.workflow.version),verificationResultHash:c.workflow.version!=="1"?Vj(l):void 0});if(p.transactionId!==d.transactionId||j(m)!==j(p))throw new Error("Native history Archive receipt does not match its committed outcome")}return e.recover&&await n.readDisposition(c.runId)==="reopening"?(await KO(t,"native",c.runId),await n.reopenRun(c.runId,c.revision)?dN({projectRoot:t,run:c}):!1):!await n.closeRun(c.runId,c.revision)||await n.readDisposition(c.runId)!=="closed"?!1:(await Vb(t,r),!0)}Xt();Bo();Vt();Ke();Ui();async function Rg(e){if(e.run.status!=="cancelled")return;let t=e.run.input?.artifactRootRef;if(typeof t=="string"){let o=await he(e.projectRoot,t);if(await Lt(o,{kind:"archive",change:e.run.runId}))return}let r=await Qi(e);if(!r?.quiescent)return;if(!r.cleanupRequired){await _d(e);return}let n=e.run.input;if(typeof n?.artifactRootRef!="string")return;let i=await he(e.projectRoot,n.artifactRootRef);await Ve(i,async()=>{let o=await Ur(e.projectRoot);if(o.status!=="selected"||o.selection.change!==e.run.runId)return;let a=await qe(e.projectRoot,"native",e.run.runId);a&&(a.application==="native"?o.selection.workflow==="native":o.selection.workflow==="application"&&o.selection.applicationId===a.application)&&await Ma(e.projectRoot,o.selection.workflow,e.run.runId)}).catch(o=>{throw new Error(`Native cancellation is committed but current selection release remains pending. Inspect the unfinished workspace transaction with comet native doctor --json, then retry comet native doctor ${e.run.runId} --repair. ${o instanceof Error?o.message:String(o)}`,{cause:o})}),await _d(e)}async function yD(e){let{projectRoot:t,store:r,runId:n,expectedRevision:i,next:o}=e;if(o.status!=="cancelled")throw new Error("Native cancellation commit requires a cancelled Run");let a=o.input;if(typeof a?.artifactRootRef!="string")throw new Error("Native cancellation commit requires its artifact root");let s=await he(t,a.artifactRootRef);return Ve(s,async()=>{let c=await r.read(n);if(c&&c.status!=="cancelled"){if(await Lt(s,{kind:"archive",change:n}))throw new Error(`Native Archive transaction must finish before cancellation; run comet native archive ${n} or recover its original Action with --recover`);if(c.actions.some(l=>l.stepId.startsWith("archive.")&&["running","unknown"].includes(l.status)))throw new Error(`Native Archive execution must finish or recover before cancellation; run comet native archive ${n} --recover`)}return r.compareAndSwap(n,i,o)},{allowedPortableTransaction:{kind:"archive",change:n}})}Xt();Bo();Vt();Ke();async function kD(e){if(e.run.status!=="completed")return;let t=e.run.input;if(typeof t?.artifactRootRef!="string")return;let r=await he(e.projectRoot,t.artifactRootRef);await Ve(r,async()=>{let n=await Ur(e.projectRoot);if(n.status!=="selected"||n.selection.change!==e.run.runId)return;let i=await qe(e.projectRoot,"native",e.run.runId);i&&(i.application==="native"?n.selection.workflow==="native":n.selection.workflow==="application"&&n.selection.applicationId===i.application)&&await Ma(e.projectRoot,n.selection.workflow,e.run.runId)}).catch(n=>{throw new Error(`Native SDK Run ${e.run.runId} is archived but current selection release remains pending. Inspect the unfinished workspace transaction with comet native doctor --json, then retry comet native doctor ${e.run.runId} --repair. ${n instanceof Error?n.message:String(n)}`,{cause:n})}),await _d(e)}Xr();Ze();Me();Xt();st();Dt();bt();Ke();Ae();Yt();Yt();Sr();Sd();Me();var pN=class extends Error{constructor(r,n,i=!1,o){let a=o?["runtime","dispatch","--application-file",zo.join(o.packageRoot,"application.json"),"--project-root",r,"--request","<recovery-request.json>","--json"]:null;super(a?`Native SDK Run ${n} needs checkpoint recovery. Save the recovery request JSON to a file and replace <recovery-request.json> with its path. Run comet with the exact argument array below to restore the recorded state and advance only the Runtime, without executing host work.
436
+ Recovery argv: ${JSON.stringify(a)}
437
+ Recovery request: ${JSON.stringify({operation:"next",runId:n})}`:`Native SDK Run ${n} needs checkpoint recovery; run comet native doctor ${n} --repair${i?"":" --confirmed"} before continuing`);this.projectRoot=r;this.change=n;this.interrupted=i}projectRoot;change;interrupted;code="NATIVE_SDK_RUN_RECOVERY_REQUIRED"};function s3(e){return e.revision===1||["completed","cancelled","failed"].includes(e.status)||e.state.phase==="shape"&&e.waits.some(t=>["shape.confirm","supervisor.shape.confirm"].includes(t.stepId)&&t.status==="resolved"&&t.decision?.choice==="rejected")||e.waits.some(t=>t.status==="pending")||e.evidenceWaits?.some(t=>t.status==="pending")?!0:e.actions.some(t=>["pending","running","unknown"].includes(t.status)&&(t.type==="invoke_skill"||t.type==="handoff"||!!t.claim?.sessionId||!["shape.prepare","shape.revalidate","verify.revalidate","archive.prepare"].includes(t.stepId)))}function c3(e,t){return JSON.stringify(e)===JSON.stringify(t)}function l3(e,t,r){if(e.actions.some(s=>s.stepId==="supervisor.cleanup"&&s.status==="succeeded"))return;let i=e.actions.filter(s=>s.status==="succeeded"&&["supervisor.prepare","supervisor.child.prepare"].includes(s.stepId));if(i.length===0)return;let o=Mt(r),a=!t.archived;for(let s of i){let c=s.outcome?.output;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Native SDK Supervisor worktree receipt is invalid");let l=c,u=s.stepId==="supervisor.child.prepare"?l.child:null;if(s.stepId==="supervisor.child.prepare"&&typeof u!="string")throw new Error("Native SDK Supervisor Child worktree receipt is invalid");let f=typeof u=="string"?Bt(r,t.name,u):Rt(r,t.name),d=typeof u=="string"?l.worktree:l.integrationWorktree,m=typeof u=="string"?l.branch:l.integrationBranch;if(typeof d!="string"||!we(d,f)||typeof m!="string"||a&&(!o.some(h=>we(h,f))||de(f).currentBranch!==m))throw new Error(`Native SDK Supervisor worktree unavailable in this checkout: ${f}; transfer or repair the Child and integration worktrees before restoring the Run`)}}async function Id(e,t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=await oe(e.projectRoot,zo.relative(e.projectRoot,e.archiveDir),{label:"Native SDK Archive directory",expected:"directory"});if(!r.exists)return null;let n=(await mN.readdir(r.target,{withFileTypes:!0})).filter(i=>i.isDirectory()&&!i.isSymbolicLink()&&/^\d{4}-\d{2}-\d{2}-/u.test(i.name)&&i.name.slice(11)===t).map(i=>i.name);if(n.length>1)throw new Error(`Native SDK Archive ${t} is ambiguous`);return n.length===1?zo.join(r.target,n[0],"comet-state.yaml"):null}async function xd(e){let{text:t}=await JC({root:zo.dirname(e),ref:zo.basename(e),maxBytes:Buffer.byteLength(Tu)+1});return Ba(t)}async function AD(e,t){let r=await mN.readFile(e,"utf8");if(!Ba(r))return!1;let n=Do(r,"Native state file");return wm(n[Bi],t)!==null}function u3(e,t,r,n){return Tu+(0,bD.stringify)({...L(e),...r===void 0?{}:{archive_receipt:r},...n?{application_checkpoint:n}:{}})+(t?`${Bi}: ${JSON.stringify(t)}
438
+ `:"")}function Ko(e,t={},r=!1){let n=Ue(e),i=vD(e,"native",t.store??vt({singleWriter:!0,rootDir:zo.join(n,"sdk-runs","native")}));function o(){if(Ue(e)!==n)throw new Error("Native SDK workspace identity changed; recreate the store in the current workspace")}function a(f,d){return Do(d,"Native portable state")}async function s(f){return(await De(e,zo.relative(e,f),Number.MAX_SAFE_INTEGER,{label:"Native portable state"})).bytes.toString("utf8")}async function c(f,d,m=t.readOnly){let h=await Fe(e);if(!h)return null;let p=await he(e,h.native.artifact_root,{...t,readOnly:m,change:f}),g=Qr(p,f),v=g,w;try{w=await s(v)}catch(K){if(K.code!=="ENOENT")throw K;let Z=await Id(p,f);if(!Z)return null;v=Z,w=await s(v)}if(!Ba(w))return null;let y=Do(w,"Native state file"),b=wm(y[Bi],f,{preserveSourceRevision:!0});if(!b)return null;if(j(y.application_checkpoint??null)!==j(t.identity??null))throw new Error("Native portable checkpoint requires its original fixed Application package");let N=L(y),A=b.input;if(!c3(L(b.state),N)||A?.name!==f||A.artifactRootRef!==p.artifactRootRef||b.workflow.id!=="comet-native"||v!==g&&!N.archived)throw new Error(`Native portable Run checkpoint for ${f} does not match its state`);if(!t.identity){let[{nativeSdkApplicationForRun:K},{upgradeNativeRun:Z}]=await Promise.all([Promise.resolve().then(()=>(Ed(),sD)),Promise.resolve().then(()=>(bg(),cD))]);if(t.rootRunId===f&&b.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let re=K(null);Z(b,re.workflow,re.transitionHandler)}!t.allowBranchRebind&&b.status!=="cancelled"&&!(N.archived&&b.status==="completed")&&Ju(e,{isolation:N.workspace.isolation,changeBranch:N.workspace.change_branch,targetBranch:N.workspace.target_branch}),l3(b,N,e);let S=b.revision,_={...b,revision:S};if(d&&j(d)!==j({..._,revision:1}))throw new Error(`Native SDK Run ${f} differs from the interrupted checkpoint import; preserve the local records and restore matching Run history before continuing`);if(m)return _;if((S>1||d)&&!i.restoreCheckpoint)throw new Error(`Native RuntimeStore cannot restore checkpoint revision ${S}; use a store with restoreCheckpoint support or restore the original Run history`);let Q=t.identity?.id??"native",F=N.archived&&b.status==="completed"?await qe(e,"native",f,{readOnly:!0}):null;return(F?.application!==Q||F.runId!==f)&&await Wo(e,{schema:Mn,workflow:"native",change:f,format:"sdk",application:Q,runId:f}),S===1&&!d?await i.compareAndSwap(f,null,_):await i.restoreCheckpoint(f,d?1:null,_),i.read(f)}async function l(f,d){let m=L(f.state),h=f.input;if(m.name!==f.runId||h?.name!==f.runId||typeof h.artifactRootRef!="string")throw new Error(`Native SDK Run ${f.runId} does not match its portable state`);let p=await Fe(e);if(p&&p.native.artifact_root!==h.artifactRootRef)throw new Error("Native artifact root changed after Run creation");if(!d||!s3(f))return f;let g=f,v=m,w=await he(e,h.artifactRootRef,{change:f.runId}),y=Qr(w,f.runId);try{await mN.access(zo.dirname(y))}catch(_){if(_.code!=="ENOENT")throw _;if(!v.archived)return g;let Q=await Id(w,f.runId);if(!Q)throw new Error(`Native SDK Archive ${f.runId} is ambiguous`,{cause:_});y=Q}let b=null;try{b=await s(y)}catch(_){if(_.code!=="ENOENT")throw _}let N=b&&g.actions.some(_=>_.stepId==="archive.finalize")?a(y,b).archive_receipt:void 0,A=fb(pb(g)),S=u3(v,A,N,t.identity);return b!==S&&await et(y,S,{containedRoot:w.nativeRoot}),g}async function u(f,d=!1){let m=await Lo(e,f,n);if(m){let g=await Ko(m.projectRoot,{readOnly:!0,rootRunId:f}).read(f);if(!g)throw new Error(`Native Build workspace handoff is incomplete; use comet native next ${f} --project-root ${e} --json to resume it`);return g}let h;if(r)try{h=(await va(i,f)).record}catch(g){if(g.code!=="RUN_NOT_FOUND")throw g;h=null}else h=await i.read(f);let p=h?.revision===1&&h.actions.some(g=>g.status!=="pending")?h:void 0;if(!h||p){let g=await c(f,p,!0);if(!g)return h;if(!h||g.revision>h.revision){if(t.readOnly)throw new pN(e,f,!!p,t.identity);o(),await Ei(e),h=await c(f,p,!1)}}return h?l(h,d&&!t.readOnly):null}return{queryScope:i.queryScope,read:u,readProjection:f=>Ko(e,{...t,store:i,readOnly:!0},!0).read(f),async compareAndSwap(f,d,m){let h=await Lo(e,f,n);if(h)throw new Error(`Native change moved to ${h.projectRoot}; run comet native next ${f} --project-root ${e} --json to resume the transfer`);if(t.readOnly)throw new Error("Native SDK diagnostic store is read-only");o();let p=L(m.state),g=m.actions.find(S=>["build.builder","supervisor.prepare"].includes(S.stepId)&&S.status==="running");if(g&&!t.identity&&(await i.read(f))?.actions.find(Q=>Q.id===g.id)?.status!=="running"){let{listNativeSdkBuildPeers:Q}=await Promise.resolve().then(()=>(pc(),eT));if((await Q(e,f)).length>0)throw new Error(`Native Build requires its own worktree; run comet native next ${f} --project-root ${e} --json before claiming implementation`)}for(let S of m.actions){if(S.status!=="running"||!["verify.verifier","supervisor.child.verifier"].includes(S.stepId)||!wi(m,S))continue;let Q=S.input.activation?.builderSessionId??p.builder_handoff?.builder_execution_ref;if(!Q||S.claim?.sessionId!==Q)continue;let F=await i.read(f),K=F?.actions.find(Z=>Z.id===S.id);if(F?.revision===d&&(K?.status!=="running"||!fN(K.claim,S.claim)))throw new R("VERIFIER_SESSION_NOT_INDEPENDENT","Native Verifier requires an independent session; use a different sessionId from the Builder.")}let v=p.workspace;try{Ju(e,{isolation:v.isolation,changeBranch:v.change_branch,targetBranch:v.target_branch})}catch(S){let _=await i.read(f),Q=m.actions.some(K=>K.status==="running"&&!_?.actions.some(Z=>Z.id===K.id&&Z.status==="running"&&Z.attempt===K.attempt&&fN(Z.claim,K.claim))),F=_?.actions.some(K=>["running","unknown"].includes(K.status)&&m.actions.some(Z=>Z.id===K.id&&Z.attempt===K.attempt&&fN(Z.claim,K.claim)));if(Q||m.status!=="cancelled"&&!F)throw S}let w=()=>i.compareAndSwap(f,d,m),y=[...m.actions].reverse().find(S=>S.stepId==="archive.execute"&&S.status==="failed"),N=(y?await i.read(f):null)?.actions.some(S=>S.id===y?.id&&S.status==="unknown"),A=m.status==="cancelled"?await yD({projectRoot:e,store:i,runId:f,expectedRevision:d,next:m}):N?await r$({projectRoot:e,store:i,runId:f,expectedRevision:d,next:m,actionId:y.id,state:p}):await w();return A&&(await l(m,!0),m.status==="cancelled"&&await Rg({projectRoot:e,run:m}),m.status==="completed"&&await kD({projectRoot:e,run:m})),A}}}pc();Me();Xt();bt();Rc();Sc();Dt();Vt();Ed();Yt();Ae();Ke();import d3 from"node:path";async function f3(e){let t=Vc(),r=Ko(e.paths.projectRoot);return cr({store:{async read(o){let a=await r.read(o);if(a&&!await qe(e.paths.projectRoot,"native",o))throw new R("RUN_OWNER_MISSING",`SDK Run ${o} 缺少归属记录`);return a},async compareAndSwap(o,a,s){if(a===null){if(o!==e.name)throw new Error("Native SDK Run ID and change name differ");await Wo(e.paths.projectRoot,{schema:Mn,workflow:"native",change:e.name,format:"sdk",application:"native",runId:o},{canonical:!0})}return r.compareAndSwap(o,a,s)}},workflows:[t.workflow],transitionHandlers:[t.transitionHandler],validators:t.validators,stateValidators:t.stateValidators,commandValidators:t.commandValidators,validateRecovery:t.validateRecovery,executors:t.executors}).start({runId:e.name,workflow:{id:t.workflow.id,version:t.workflow.version},input:{name:e.name,...e.task===void 0?{}:{task:e.task},artifactRootRef:e.paths.artifactRootRef},initialState:e.initialState})}async function RD(e,t){let r=d3.join(Nt(e,t),"comet-state.yaml");if(!await xd(r))return null;let n=await Gt(r),i=rc({name:t,language:n.language,workspace:n.workspace,createdAt:n.created_at,nextAction:"prepare-shape-confirmation"});return JSON.stringify(n)!==JSON.stringify(i)?null:i}async function ND(e,t){let r=await RD(e,t);return r?f3({paths:e,name:t,initialState:r}):null}async function ED(e,t,r){if(r.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let n=CD(),i=Jo(r,n.workflow,n.transitionHandler);return await cr({...n,workflows:[n.workflow],transitionHandlers:[n.transitionHandler],store:{read:async()=>i,compareAndSwap:async()=>!1}}).inspect(t),Wo(e,{schema:Mn,workflow:"native",change:t,format:"sdk",application:"native",runId:t},{canonical:!0})}async function p3(e,t){let r=await Mi(e.projectRoot,"native",t);return r||Ve(e,async()=>{let n=await Mi(e.projectRoot,"native",t);if(n)return n;let i=Pd.relative(e.projectRoot,Qr(e,t));if(!(await oe(e.projectRoot,i,{label:"Native legacy change state",expected:"file"})).exists){let c=await Id(e,t);if(!c)return null;let l=Pd.relative(e.projectRoot,c),u=await oe(e.projectRoot,l,{label:"Native archived change state",expected:"file"});if(!u.exists||!await xd(u.target))return null;if(await hN(e.projectRoot,t))return await(await Go(e.projectRoot,t)).runtime.inspect(t),qe(e.projectRoot,"native",t);let f=await Ko(e.projectRoot,{rootRunId:t}).read(t);if(f){let d=await qe(e.projectRoot,"native",t);return d||ED(e.projectRoot,t,f)}throw new Error(`Native archived change ${t} has a managed state file but lost its Run checkpoint`)}if(await hN(e.projectRoot,t))return await(await Go(e.projectRoot,t)).runtime.inspect(t),qe(e.projectRoot,"native",t);let s=await Ko(e.projectRoot,{rootRunId:t}).read(t);if(s){let c=await qe(e.projectRoot,"native",t);return c||ED(e.projectRoot,t,s)}if(await ND(e,t)){let c=await qe(e.projectRoot,"native",t);if(!c)throw new Error(`Recovered Native change ${t} has no Run ownership`);return c}return await m3(e,t),Mb(e.projectRoot,{schema:Mn,workflow:"native",change:t,format:"compat"})})}async function m3(e,t){let r=Qr(e,t);if(await xd(r)&&!await AD(r,t))throw new Error(`Native change ${t} has a portable state file but lost its local Run history; inspect it with comet native doctor ${t} before restoring`)}async function hN(e,t){let r=await Fe(e);if(!r)return null;let n=await he(e,r.native.artifact_root,{readOnly:!0}),i=Qr(n,t);try{await SD.access(i)}catch(a){if(a.code!=="ENOENT")throw a;let s=await Id(n,t);if(!s)return null;i=s}return Do(await SD.readFile(i,"utf8"),"Native application checkpoint").application_checkpoint??null}var h3=Si("nativeBuiltinDefinition",()=>Vc());function CD(){return h3()}async function Go(e,t,r={}){let n=r.owner??await qe(e,"native",t,r),i=n?.application==="native"?null:await hN(e,t),o=n?.application??i?.id??"native";if(o==="native"){let c=Ko(e,{...r,rootRunId:t}),l=await c.read(t),u=CD();if(l){let f=Jo(l,u.workflow,u.transitionHandler);f!==l&&(await cr({...u,workflows:[u.workflow],transitionHandlers:[u.transitionHandler],store:{read:async()=>f,compareAndSwap:async()=>!1}}).inspect(t),l=f)}return{runtime:cr({...u,executors:r.readOnly?[]:u.executors,store:{...c,async read(f){if(l&&f===t){let m=l;return l=null,Promise.resolve(m)}let d=await c.read(f);return d&&Jo(d,u.workflow,u.transitionHandler)}},workflows:[u.workflow],transitionHandlers:[u.transitionHandler]}),executors:u.executors,application:null}}let a=i?.packageRoot?Pd.join(i.packageRoot,"application.json"):await EA(e,o,t),s=await Jm({file:a,projectRoot:e,runId:t,...i?{expectedIdentity:i}:{},readOnly:r.readOnly});if(s.identity.id!==o||s.identity.base!=="native")throw new Error("Native change owner does not match its fixed Application");return{runtime:cr({...s.implementation,...r.readOnly?{executors:[]}:{},store:s.store}),executors:s.implementation.executors??[],application:s}}async function ls(e,t,r={}){let n=await qe(e,"native",t,r);if(!n)throw new Error(`Native change ${t} is not owned by an SDK Run`);let{runtime:i,application:o}=await Go(e,t,{...r,owner:n}),a=await i.inspect(n.runId);if(a.workflow.id!=="comet-native"||!a.input||typeof a.input!="object"||Array.isArray(a.input)||a.input.name!==t||typeof a.input.artifactRootRef!="string")throw new Error(`Native SDK Run ${t} does not match its change ownership`);let s=L(a.state);if(s.name!==t)throw new Error(`Native SDK Run ${t} has a different state name`);return{run:a,state:s,artifactRootRef:a.input.artifactRootRef,application:o}}async function g3(e,t,r={}){let n=Pd.resolve(e);return await qe(n,"native",t,r)?{projectRoot:n,...await ls(n,t,r)}:null}async function Ng(e,t,r={}){let n=Pd.resolve(e),i=await Mi(n,"native",t,r);if(!i&&!r.readOnly){let o=await Fe(n);if(o){let a=await he(n,o.native.artifact_root,{change:t});i=await p3(a,t)}}return i?n:(await g3(n,t,r))?.projectRoot??n}Me();import{randomUUID as uB}from"node:crypto";sc();yo();zA();Ze();import Od from"path";import{realpathSync as O3}from"fs";function _D(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:`'${t.replace(/'/gu,`'"'"'`)}'`).join(" ")}function ID(e,t){let r=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)?p:{},n=r(e),i=r(n.entry),o=r(n.run??i.run??(typeof n.runId=="string"?n:void 0)),a=r(n.state??i.state??n),s=r(n.preparation??n.workspace??i.workspace),c=r(n.continuation??i.continuation??n.nextAction??i.nextAction),l=typeof s.projectRoot=="string"&&s.projectRoot!=="."?s.projectRoot:typeof c.cwd=="string"?c.cwd:typeof n.projectRoot=="string"?n.projectRoot:typeof i.projectRoot=="string"?i.projectRoot:t??null,u=a.stateVersion??a.state_version,f=a.status??o.status,{current:d,...m}=c,h=d===void 0?c:{...m,currentRef:n.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof a.phase=="string"?a.phase:null,status:typeof f=="string"?f:null,stateVersion:typeof u=="number"?u:null,workspace:{cwd:l},continuation:Object.keys(c).length?{...h,cwd:l}:null,...Object.keys(o).length?{run:{id:typeof o.id=="string"?o.id:typeof o.runId=="string"?o.runId:null,revision:typeof o.revision=="number"?o.revision:null,status:typeof o.status=="string"?o.status:null}}:{}}}var yi={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function xD(e){return e?e.command?`${yi.next} ${e.command}`:e.ask_user?`${yi.next} ${e.ask_user}`:e.instruction?`${yi.next} ${e.instruction}`:null:null}function PD(e,t){let r=[e.summary],n=xD(e.next);return n&&r.push(n),e.user_message&&r.push("",yi.relay,e.user_message),t!==void 0&&r.push("",yi.details,JSON.stringify(t,null,2)),`${r.join(`
439
+ `)}
440
+ `}function OD(e,t,r){let n=[e.summary],i=xD(e.next);return i&&n.push(i),e.user_message&&n.push("",yi.relay,e.user_message),n.push("",`${yi.detail} ${t}`),r!==void 0&&n.push("",yi.details,JSON.stringify(r,null,2)),n.join(`
441
+ `)}Ke();Dt();function Se(e,t,r){return e==="zh-CN"?r:t}var gN={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function TD(e,t){return typeof e=="string"&&gN[e]?Se(t,gN[e].en,gN[e].zh):typeof e=="string"?e:""}function vN(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function v3(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let n=r.result;if(n!=="passed"&&n!=="failed"&&n!=="blocked"&&n!=="pending")return null;t[n]+=1}return t}function jD(e,t){let r=[];e.failed>0&&r.push(Se(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(Se(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(Se(t,`${e.pending} pending`,`${e.pending} 项待验`));let n=Se(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${n} (${r.join(", ")})`:n}function $D(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function wN(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function w3(e,t,r){return e==="done"?Se(r,"complete","已完成"):e==="await-user"?Se(r,"waiting for a user decision","等待用户决定"):e==="blocked"?Se(r,"paused: needs attention","已暂停,需要处理"):t?Se(r,"waiting for a user decision","等待用户决定"):Se(r,"ready to continue","可继续推进")}function y3(e,t,r){let n=wN(e),i=[];r&&i.push(r);let o=Se(n,`Change ${e.change}`,`需求 ${e.change}`),a=TD(e.phase,n),s=e.mode==="wait"?Se(n,"waiting for the original task","等待原任务完成"):w3(e.disposition,e.userCommunication.required,n);i.push([o,a||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&i.push(jD(t,n));let c=e.userCommunication,l=DD(e,n);return{summary:i.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function DD(e,t){let r=e.userCommunication;return e.mode&&e.mode!=="execute"?e.mode==="ask"?{ask_user:r.agentInstruction}:{instruction:r.agentInstruction}:e.disposition==="await-user"&&r.required?{ask_user:Se(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")}:e.commandArgs&&e.commandArgs.length>0?{command:_D(e.commandArgs)}:e.disposition==="done"?{ask_user:Se(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")}:e.disposition==="blocked"?{ask_user:r.required&&r.message?r.agentInstruction:Se(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}:{instruction:r.agentInstruction}}function k3(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function b3(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",n=TD(e.phase,t),i=e.status==="await-user"?Se(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?Se(t,"paused","已暂停"):e.status==="done"?Se(t,"complete","已完成"):Se(t,"in progress","进行中"),o=vN(e.acceptance)?`${Se(t,", ",",")}${jD(e.acceptance,t)}`:"";return` ${r} · ${n||String(e.phase??"?")} · ${i}${o}`}function A3(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function R3(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function N3(e){if(e.healthy){let n=e.repaired?Se("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):Se("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),i=S3(e.continuation);return i?{summary:n,next:i}:{summary:n}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:Se("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:Se("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function S3(e){return $D(e)?DD(e,wN(e)):void 0}function BD(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(R3(t))return N3(t);if(k3(t)){let n=A3(t.items);return{summary:[t.total===t.items.length?Se(n,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):Se(n,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(o=>b3(o,n))].join(`
442
+ `)}}let r=t.continuation;if($D(r)){let n=wN(r),i=y3(r,E3(t),_3(t,n));return C3(t)==="unconfirmed"?{...i,summary:`${i.summary}${Se(n,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:i}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let n=t.language==="zh-CN"?"zh-CN":"en",i="pendingRootMove"in t;return{summary:Se(n,i?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,i?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function E3(e){if(vN(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(vN(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return v3(r.acceptance)}return null}function C3(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function _3(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return Se(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?Se(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function WD(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:r.outcome==="revision-conflict"||/^expected revision \d+, got \d+$/iu.test(e.message)?Se("en","This change was updated by another operation. Read the latest state and continue from its current instructions.","这条需求已被另一个操作更新。请读取最新状态,按当前指引继续。"):e.message,...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:Se("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:Se("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:Se("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:Se("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:Se("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:Se("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:Se("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:Se("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Sg=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Md();gh();fp();var LD=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--compact 与 --json 合用;重复字段用 outputView.references 的 JSON Pointer 定位,Request 模板保留完整;没有字节收益时返回原完整协议。去掉此选项获取完整协议。","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],yN=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","After Shape approval, new ordinary SDK tasks use `next <change> --session <actual-session>`. Submit business results using the returned command. Runtime checks and the next task are returned together. Older and Supervisor tasks retain their returned protocol through `comet runtime dispatch --application native`; read continuation.inputOptions when present.","For compat Runtime changes, execute `agent.continuation.commandArgs` in `agent.workspace.cwd` and fill `agent.continuation.inputOptions` templates."],subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","cancel <change-name> Cancel an unfinished change while keeping its code and workspace.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state.","transfer export|import Move an active Supervisor Child Build to another checkout."],options:LD,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--runtime compat|sdk] [--language en|zh-CN] [--task <text>] [--capability <id>] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--runtime compat|sdk Runtime format for this new change; defaults to sdk.","--language en|zh-CN Artifact language; defaults to project configuration.","--task <text> Preserve the original request in the SDK Run for independent alignment review; also search Project Knowledge for a capability association.","--capability <id> Directly validate and associate an existing capability without retrieval.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The SDK Run or portable state, canonical artifact paths, and workspace preparation result; compat Runtime changes include the next Runner continuation.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
443
+ comet native spec remove <change-name> <capability>
444
+ comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Compat-only Markdown reference correction; SDK changes return to Shape for revision."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec snapshot":{usage:"comet native spec snapshot <change-name>",purpose:"Restore the originally approved documents first. Runtime checks their complete legacy fingerprint and saves at most 2 MiB of original evidence in this workspace Runtime. It does not approve changed requirements or change the Run, candidate, Action, claim or check receipts. Evidence is local to this workspace; repeat the verified capture after moving to another device.",output:"The validated original Shape identity and captured sources; no workflow state changes."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Compat-only reference correction. SDK changes use Shape edits or next --revise-requirements from Verify/Archive.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"For compat Runtime changes, the audited state and Build continuation for re-verification. SDK changes receive revise-requirements guidance."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; compat Runtime state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Compatibility guidance for running checks through Agent platform tools.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details SDK: include complete business state and Action/Wait history. Compat: include one fixed-size detail page."],output:"SDK status includes the exact continuation, claim request templates, all pending/running/unknown work, and the latest 12 settled records per history collection. run.history reports omitted records; --details returns complete history without --cursor. Compat status reports business continuation and details use --cursor for fixed-size pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name> [--rebind]",options:["--rebind Explicitly bind the same idle SDK Run to the current Git branch; preserve work and approvals, and reject unresolved executions."],purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --session <actual-session> [--action <id>] [--result <json-file>] [--review current-session|independent] [--accept-on-pass <authorization-summary>] [--details]
445
+ comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
446
+ comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
447
+ comet native next <sdk-change> --confirmed --coordination-mode multi-session|single-session --summary <text> --expected-state-version <n> --expected-action confirm-shape
448
+ comet native next <sdk-change> --accept-result|--revise-implementation|--retry-verifier|--continue-builder|--resolve-verifier-blocker --summary <text> --proposal-hash <hash> --expected-state-version <n> --expected-action <action>
449
+ comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Advance SDK-owned Runtime actions and bound user decisions, or recover a compat Runtime Agent boundary and use its skill-coordinated Builder/Verifier JSON bridge.",options:["--session <actual-session> Claim a new ordinary SDK task using its real receiving session.","--action <id> Preserve the current task ID when claiming or reporting.","--result <json-file> Submit actual status/output business fields, run authorized internal steps, and return the next task. Requires --action and --session.","--review current-session|independent Continue ordinary Verify in this session or leave it for a separate actual receiver. Honor explicit user requests for independent review.","--accept-on-pass <authorization-summary> With this Verify result only, record prior explicit user delegation to accept and archive if all criteria pass. Without this option, wait for user acceptance.","--details With --session, include the full SDK projection alongside the current task.","--summary <text> Required transition or recovery summary.","--defer-build With --confirmed, save Shape approval and wait for a later next call to prepare the Build workspace.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request For compat changes, with --accept-result record the explicitly chosen isolated-workspace finish in the same guarded decision. SDK Runs keep Git delivery separate.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Renew a pending Shape proposal or return Verify, Archive, or a quiescent SDK Supervisor Build to Shape. SDK changes also allow revising after an ordinary Builder explicitly failed; use the current continuation proposal hash. Preserve partial work and reconcile running/unknown Actions first. The new Shape still requires explicit approval. Completed SDK Runs require an application-validated blocked Child recovery.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--continue-builder After a failed SDK Builder Action, explicitly continue from its preserved workspace in a new Action.","--resolve-verifier-blocker Resume an SDK or compat blocked Verifier with the retained candidate and valid checks; a completed SDK Supervisor Child resumes with a new Builder. SDK recovery requires the current proposal hash and both expected guards; original outcomes are preserved.","--max-parallel <n> Compat-only Supervisor concurrency override. SDK and Compat use native.max_parallel_children (default 2); configure it in project settings or .comet/config.yaml; single-session always uses 1.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--proposal-hash <hash> SDK decision guard from the current Wait or blocked Child continuation; required with --accept-result, --revise-implementation, --retry-verifier, --continue-builder, or --resolve-verifier-blocker, and with --revise-requirements for pending Shape or failed ordinary Builder recovery.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, known_limits, optional review. Cover every confirmed acceptance ID with its actual status, evidence and note. Only implemented-with-evidence entries with nonempty evidence are ready for handoff. checks contain actual Agent platform reports. An optional review records status=passed, summary and reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind. Run development checks through Agent platform tools and hand the current candidate to the selected Verifier."," retry-checks is a retired compatibility input that returns platform execution guidance without running a command."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (final-result). Copy the current candidate and receiving session from the dispatch and report every acceptance item."," verifier-started is optional compatibility progress reporting for the existing Verifier session; it does not supervise a process or authorize completion."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef. Record the actual platform capability failure; it never grants a passing result."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks is retired and returns platform execution guidance without starting a process or generating a receipt."," supervisor-verifier-result evidence fields: summary, checks (actual platform reports), acceptance [{id,result,reason}]. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once."," supervisor-integrate fields: child, integrationCommit and checks [{name,status,reason}], reporting the actual merge and platform checks."],output:"SDK-owned changes return the current Run Action or Wait and the same continuation as status/show, including current decision guards and pending Action claimRequest templates. Fill the template with the host session and claim token; the successful claim returns the current Action input. Authorized internal business steps and Archive continue from the original Run. Builder and Verifier handoffs use `comet runtime dispatch --application native`; never resubmit running/unknown work. Compat Runtime changes return the portable state, Runner result, continuation.inputOptions, and userCommunication. The compat JSON bridge is not trusted identity attestation: a passing skill-coordinated result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --revise-requirements --summary "User changed the pending Shape or stopped Builder requirements" --proposal-hash <hash> --expected-state-version <n> --expected-action revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --continue-builder --summary "Continue the inspected partial work" --proposal-hash <hash> --expected-state-version <n> --expected-action continue-builder','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},cancel:{usage:"comet native cancel <change-name> [--reason <text>] [--dry-run]",purpose:"Cancel an unfinished SDK Native change: it stops counting as active without verification or a fake Archive.",options:["--reason <text> Record why the change is cancelled; defaults to a neutral user-cancellation note.","--dry-run List what cancellation would stop, release, and retain without changing any state."],output:"The cancellation status and its outstanding acknowledgements. Code, commits, branches, and the workspace are always retained; deleting implementations or worktrees stays a separate explicit Git operation. Completed changes are rejected in favor of archive; legacy 0.4 runtime changes keep their original lifecycle."},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
450
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]
451
+ comet native archive <sdk-change-name> --recover [--legacy-spec-backup <json-file>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> For compat changes, set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> For compat changes, set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it.","--legacy-spec-backup <json-file> SDK only: read a bounded original-Spec backup for an existing legacy Archive transaction. Use a new file outside the project so it does not change the old candidate. Requires exact schema/runId/transactionId/path/hash and original candidate digest matches; never writes the source file or Git index. See docs/operations/native-archive-recovery.zh.md.","--recover For an SDK-owned change, reconcile one unknown Supervisor delivery, Archive, or cleanup Action only after confirming the original execution process has stopped; never retry it as new work."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair] [--confirmed] [--migrate-history]",purpose:"Inspect Native business state and existing transactions, or recover the original Run checkpoint.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary.","--migrate-history Validate and close built-in Native terminal Runs whose business cleanup is complete. Preserve documents and checkpoints; unfinished or invalid Runs remain active. Safe to rerun after interruption. Upgrade CLI and platform Hooks together: older Runtime versions cannot write the new storage format. Ordinary inspection never migrates.","--confirmed With --repair and a named managed change whose local Run history is missing, recover its saved Run checkpoint. Original business approvals and task claims are preserved."],output:"Health, original business records, and structured recovery with diagnosticArgs, recoveryArgs and preconditions. Inspection does not change the Run."},transfer:{usage:`comet native transfer export <change-name> --output <directory> --confirmed-stopped
452
+ comet native transfer import --input <directory>`,purpose:"Carry a prepared Supervisor Child Builder and its Git worktrees to another checkout before handing the next Child task to an Agent.",subcommands:["export Snapshot the parent checkpoint, Supervisor branches, and non-ignored uncommitted work.","import Validate the package and restore its Run and worktrees in a checkout at the same target commit."],options:["--output <directory> New private directory for the transfer package; must not already exist.","--input <directory> Existing transfer package to import.","--confirmed-stopped Confirm the original Builder and other Supervisor agents stopped before export."],output:"The package path or restored change and worktree paths. An in-flight Builder becomes outcome-unknown and must be reconciled; import never reports its work as completed."}});function Eg(e,t){return`${e}:
453
+ ${t.map(r=>` ${r}`).join(`
454
+ `)}`}function I3(e){let t=e.filter(n=>n!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return yN[r]||t.length>1&&yN[t[0]]?.subcommands?r:t[0]}function x3(e=[]){let t=I3(e),r=yN[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let n=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&n.push("",Eg("Agent Quick Start",r.agentQuickStart)),r.subcommands&&n.push("",Eg("Commands",r.subcommands));let i=t===""?r.options:[...r.options??[],...LD];return i&&i.length>0&&n.push("",Eg("Options",i)),n.push("",`Output:
455
+ ${r.output}`),r.examples&&n.push("",Eg("Examples",r.examples)),t===""&&n.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${n.join(`
456
+ `)}
457
+ `}}var P3=x3().usage;var xe=class extends Error{};function Yo(e,t){let r=e.flatMap((n,i)=>n===t?[i]:[]);if(r.length>1)throw new xe(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function ki(e,t){let r=e.flatMap((o,a)=>o===t?[a]:[]);if(r.length>1)throw new xe(`${t} may only be provided once`);if(r.length===0)return;let n=r[0],i=e[n+1];if(i===void 0||i.startsWith("--"))throw new xe(`${t} requires a value`);return e.splice(n,2),i}function Td(e){if(e.length>0)throw new xe(`Unexpected argument: ${e[0]}`)}function VD(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new xe(`${t} is required`);return r}function kN(e,t){let r=Od.normalize(qD(e)),n=Od.normalize(qD(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function qD(e){let t=Od.resolve(e);try{return O3.native(t)}catch{return t}}function T3(e,t){let r=Od.resolve(t,e),n=de(t);if(!n.isSecondaryWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null)return r;let i=de(r);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!kN(n.primaryWorktreeRoot,i.primaryWorktreeRoot)||kN(n.currentWorktreeRoot,i.currentWorktreeRoot)?r:kN(t,n.currentWorktreeRoot)?Od.resolve(t):n.currentWorktreeRoot}async function MD(e,t=process.cwd()){return e?T3(e,t):lp(t)}function FD(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function HD(e,t){let r=await _O({startPath:e,allowMissingConfig:!1,change:t});return{config:r.config,paths:r.paths}}function QD(e){return JSON.stringify(e,null,2)+`
458
+ `}function mr(e,t,r){return{command:e,exitCode:0,data:t,text:r??QD(t)}}function j3(e,t){if(t instanceof Ec)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof Ro)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof el)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof xe)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Sm)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof ac)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof qa)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof fi)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Sg)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function UD(e,t){let r=j3(e,t),n=r.error;if(!n)return r;let i=WD({code:n.code,message:n.message,data:r.data});return i?{...r,envelope:i}:r}function $3(e,t,r=!1){let n=e.envelope??BD(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:ID(e.data,e.executionCwd),...n===void 0?{}:{summary:n.summary,...n.next===void 0?{}:{next:n.next},...n.user_message===void 0?{}:{user_message:n.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
459
+ `}:e.error?{exitCode:e.exitCode,stderr:n?OD(n,e.error.message,r?e.data:void 0):e.error.message}:n?{exitCode:e.exitCode,stdout:PD(n,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==QD(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
460
+ ${yi.details}
461
+ ${JSON.stringify(e.data,null,2)}
462
+ `}:{exitCode:e.exitCode,stdout:e.text}}function D3(e,t,r=!1){let n=$3(e,t,r),i=!1;if(n.stdout?.trim())try{let o=JSON.parse(n.stdout);i=!!o&&typeof o=="object"&&!Array.isArray(o)}catch{i=!1}return{output:n,structuredDataVisible:i}}function JD(e,t,r=!1){return D3(e,t,r).output}Ke();Pc();Ae();Fo();Me();st();import Cg from"node:path";Ze();st();rr();Ka();import Yi from"node:path";import{promises as B3}from"node:fs";function zD(e,t,r){let n=q(e,r==="index"?["ls-files","--stage","-z","--",`:(literal)${t}`]:["ls-tree","-z","HEAD","--",`:(literal)${t}`]);if(!n)return null;let i=n.split("\0").filter(Boolean),o=i.length===1?i[0].match(r==="index"?/^(100644|100755) ([a-f0-9]+) 0\t(.+)$/u:/^(100644|100755) blob ([a-f0-9]+)\t(.+)$/u):null;if(!o||o[3]!==t)throw new Error(`旧 Archive 无法只读重建 ${t}:索引冲突或文件类型不受支持`);return{mode:Number.parseInt(o[1],8),objectId:o[2]}}function KD(e){let{paths:t,transaction:r}=e,n=de(t.projectRoot),i=n.isGitWorktree&&n.currentWorktreeRoot!==null&&we(n.currentWorktreeRoot,t.projectRoot),o=new Map;for(let a of r.spec_changes){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(a.capability))throw new Error("旧 Archive 包含无效 capability");let s=Yi.relative(t.projectRoot,Yi.join(t.specsDir,a.capability,"spec.md")).replaceAll("\\","/");if(Yi.isAbsolute(s)||s.startsWith("../"))throw new Error("旧 Archive Spec 路径越界");if(a.expected_target_hash===void 0)throw new Error(`旧 Archive 缺少 ${s} 的原目标摘要,不能重建历史验收依据`);if(a.expected_target_hash===null){if(e.originals?.has(s))throw new Error(`旧 Archive 的 ${s} 原本不存在`);o.set(s,{text:null,mode:33188});continue}let c=e.originals?.get(s),l=i?zD(t.projectRoot,s,"index"):null,u=i?zD(t.projectRoot,s,"head"):null,d=(c===void 0?[l,u].flatMap(m=>m?[{text:WN(t.projectRoot,m.objectId),mode:m.mode}]:[]):[{text:c,mode:l?.mode??u?.mode??33188}]).find(({text:m})=>C0(m)===a.expected_target_hash);if(!d)throw new Error(`旧 Archive 缺少 ${s} 的原文。请提供归档前的原文备份(SHA-256/LF:${a.expected_target_hash});不能把当前 Spec 当作旧验收依据。`);o.set(s,d)}for(let a of e.originals?.keys()??[])if(!o.has(a))throw new Error(`原文备份 ${a} 不属于原 Archive 事务`);return o}async function GD(e){let{paths:t,transaction:r}=e;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r.change)||!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r.archive_ref))throw new Error("旧 Archive 材料路径无效");let n=f=>Yi.relative(t.projectRoot,f).replaceAll("\\","/"),i=Yi.join(t.changesDir,r.change),o=Yi.join(t.archiveDir,r.archive_ref),a=await oe(t.projectRoot,n(i),{label:"旧 Archive 原材料目录",expected:"directory"}),s=await oe(t.projectRoot,n(o),{label:"旧 Archive 归档材料目录",expected:"directory"});if(a.exists&&s.exists)throw new Error("旧 Archive 原目录和归档目录同时存在,不能猜测材料归属");if(a.exists)return e.overlay;if(!s.exists)throw new Error("旧 Archive 原材料和归档材料均缺失");let c=new Map(e.overlay),l=0;async function u(f){if(!(await oe(t.projectRoot,n(f),{label:"旧 Archive 材料目录",expected:"directory"})).exists)throw new Error("旧 Archive 材料在读取期间消失");for(let m of await B3.readdir(f,{withFileTypes:!0})){let h=Yi.join(f,m.name);if(m.isSymbolicLink())throw new Error("旧 Archive 材料不能包含符号链接");if(m.isDirectory()){await u(h);continue}if(!m.isFile())throw new Error("旧 Archive 材料必须为普通文件");if(["verification.md","comet-state.yaml","children.yaml"].includes(m.name))continue;let{bytes:p,stat:g}=await De(t.projectRoot,n(h),Number.MAX_SAFE_INTEGER,{label:"旧 Archive 材料"});if(++l>4096)throw new Error("旧 Archive 材料超出只读恢复文件数量限制");let v=Yi.relative(o,h);c.set(n(h),{text:null,mode:Number(g.mode)}),c.set(n(Yi.join(i,v)),{text:p.toString("utf8"),bytes:p,mode:Number(g.mode)})}}return await u(o),c}bt();Ke();Ae();Fo();var YD=Number.MAX_SAFE_INTEGER,W3="comet.native.archive-originals.v1";function XD(e,t){return`archive-originals/${j({runId:e,transactionId:t})}.json`}function ZD(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Archive 原文备份必须是 JSON 对象");let n=e;if(Object.keys(n).some(o=>!["schema","runId","transactionId","files"].includes(o))||n.schema!==W3||n.runId!==t||n.transactionId!==r.id||!Array.isArray(n.files))throw new Error("Archive 原文备份的 schema、runId 或 transactionId 不匹配,或包含未知字段");let i=new Map;for(let o of n.files){if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(a=>!["ref","content"].includes(a))||typeof o.ref!="string"||typeof o.content!="string"||i.has(o.ref))throw new Error("Archive 原文备份 files 必须包含唯一 ref 和完整 UTF-8 content");i.set(o.ref,o.content)}return i}async function L3(e,t,r){try{let n=await De(e.runtimeDir,XD(t,r.id),YD,{label:"Native Archive original Spec evidence"});return ZD(JSON.parse(n.bytes.toString("utf8")),t,r)}catch(n){if(n.code==="ENOENT")return;throw n}}async function eB(e){let{run:t,projectRoot:r}=e;if(t.outputs["archive.prepare"]?.value?.candidateBinding)throw new Error("--legacy-spec-backup 仅用于缺少归档候选摘要的旧事务");let n=L(t.state),i=await he(r,t.input.artifactRootRef,{readOnly:!0}),o=await Lt(i,{kind:"archive",change:n.name});if(o?.kind!=="archive")throw new Error("--legacy-spec-backup 需要原有 Archive 事务");if(n.phase!=="archive"||o.journal.start_state_version!==n.state_version-(n.archived?1:0))throw new Error("Archive 原文备份与当前事务状态不匹配");let a=Cg.isAbsolute(e.ref),s=await De(a?Cg.dirname(e.ref):r,a?Cg.basename(e.ref):e.ref,YD,{label:"Native Archive original Spec backup"}),c=JSON.parse(s.bytes.toString("utf8")),l=ZD(c,t.runId,o.journal);await GD({paths:i,transaction:o.journal,overlay:KD({paths:i,transaction:o.journal,originals:l})});let u=XD(t.runId,o.journal.id),f=await L3(i,t.runId,o.journal);if(f){let d=m=>[...m].sort(([h],[p])=>h.localeCompare(p,"en"));if(j(d(f))!==j(d(l)))throw new Error("原 Archive 事务已有不同原文备份,不能覆盖");return}await xt(i.runtimeDir,"archive-originals",{label:"Native Archive original Spec evidence"}),await Pr(Cg.join(i.runtimeDir,u),c,{containedRoot:i.runtimeDir,exclusive:!0})}Nd();Ze();Me();ta();Ae();Zs();Nd();Ui();Uh();Sd();WR();ZR();_R();Zc();function jd(e){if(["failed","cancelled","completed"].includes(e.status))return[];let t=e.actions.filter(n=>n.status==="pending"),r=t.findIndex(n=>n.stepId==="supervisor.child.archive");return r>0&&t.unshift(...t.splice(r,1)),t}function _g(e,t){if(!(e.waits.some(r=>r.status==="pending")||e.evidenceWaits?.some(r=>r.status==="pending")||e.actions.some(r=>r.status==="unknown")||t.phase==="archive"&&e.actions.some(r=>r.status==="running")))return jd(e)[0]}function us(e,t){return[...e,...e.includes("--project-root")?[]:["--project-root",t],...e.includes("--json")?[]:["--json"]]}function bN(e,t){return{...e,cwd:t,commandArgs:e.commandArgs?us(e.commandArgs,t):null,...e.commandAlternatives?{commandAlternatives:e.commandAlternatives.map(r=>({...r,commandArgs:r.commandArgs?us(r.commandArgs,t):null}))}:{}}}function q3(e,t){return us(["comet","runtime","dispatch","--application",e,"--request","<request-json-file>"],t)}function V3(e,t,r){let n=r.input?.activation,i=(Array.isArray(n?.acceptance)?n.acceptance:t.acceptance).map(({id:o})=>({id:o,result:"<passed|failed|blocked>",reason:"<observed-evidence>"}));return["build.builder","supervisor.parent.builder"].includes(r.stepId)?{summary:"<actual-implementation-summary>",addressedAcceptanceIds:t.acceptance.map(({id:o})=>o),checks:[{name:"<check-name>",result:"<passed|failed|not-run>",note:"<actual-result>"}],knownLimits:["<actual-limit-or-remove-entry>"],requireIndependentReview:!1,...r.stepId==="supervisor.parent.builder"?{candidateCommit:"<current-integration-HEAD>"}:{}}:r.stepId==="verify.verifier"?{checks:(t.builder_handoff?.checks??[]).map(o=>({name:o.name.text,result:o.result,note:o.note?.text??null})),candidateId:t.builder_handoff?.candidate_id??null,verifierExecutionRef:r.claim?.sessionId??"<actual-session-id>",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:i,risks:["<observed-risk-or-remove-entry>"],summary:"<verification-summary>",...typeof e.input.task=="string"?{requestReview:{result:Gn(Vd),reason:"<compare the original request, Spec and implementation; cite authorization for changed scope>"}}:{}}}}:r.stepId==="supervisor.child.builder"?{candidateCommit:"<current-child-HEAD>",checks:[],summary:"<implementation-summary>",requireIndependentReview:!1}:r.stepId==="supervisor.child.verifier"?{candidateCommit:n?.candidateCommit??null,verdict:"<pass|fail|blocked>",evidence:{summary:"<verification-summary>",checks:n?.checks??[],acceptance:i}}:r.stepId==="supervisor.child.integration-repair"?{summary:"<repair-summary>",integrationCommit:"<new-integration-HEAD>",checks:[{name:"<check-name>",result:"<passed|failed|not-run>",note:"<actual-result>"}]}:"<actual-action-output>"}function M3(e,t,r){return!t.claim||!["running","unknown"].includes(t.status)?null:{operation:"record-outcome",runId:e.runId,outcome:{actionId:t.id,attempt:t.attempt,inputHash:t.inputHash,claimToken:t.claim.token,outcomeId:"<outcome-id>",status:t.type==="handoff"?"succeeded":"<succeeded|failed>",output:V3(e,r,t)}}}function F3(e,t,r,n){let i=M3(e,t,r);return i?{operation:"record-outcome",receipt:Buffer.from(JSON.stringify({runId:e.runId,actionId:t.id,attempt:t.attempt,inputHash:t.inputHash,claimToken:t.claim.token})).toString("base64url"),result:{status:i.outcome.status,output:n===void 0?i.outcome.output:n}}:null}function H3(e,t){if(t.type!=="handoff"||!t.claim||t.status==="running"&&!t.reason)return{};let r={runId:e.runId,expectedRevision:e.revision,actionId:t.id,attempt:t.attempt};return t.status==="running"?{markUnknownRequest:{operation:"mark-unknown",...r,reason:"<why-the-original-outcome-cannot-be-obtained>"}}:t.status!=="unknown"||t.outcome||t.rejectedOutcomes?.some(n=>n.outcome.attempt===t.attempt)?{}:{retryRequest:{operation:"retry",...r,reconciliation:{resolution:"not-executed",evidence:null}},requiredInputs:["reconciliation.evidence: authoritative evidence that the original host task never executed"]}}function Q3(e,t){let r=Gr(e);if(!t)return r;let n=e.language==="zh-CN";return{...r,requiredInputs:["summary","shared-understanding-confirmation","coordination-mode"],commandAlternatives:Du.map(i=>({name:i,stateVersion:e.state_version,expectedAction:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed","--coordination-mode",i,"--expected-state-version",String(e.state_version),"--expected-action","confirm-shape"],requiredInputs:["summary","shared-understanding-confirmation","coordination-mode"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"shared-understanding-confirmation",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null},{name:"coordination-mode",flag:"--coordination-mode",valueKind:"choice",required:!0,template:i,choices:[...Du]}]})),userCommunication:{required:!0,message:n?"请确认完整 Shape,并选择推进方式:多会话协作(推荐)或单会话推进。":"Confirm the complete Shape and choose multi-session coordination (recommended) or single-session progression.",suggestedReply:n?"确认 Shape,选择多会话协作":"Confirm Shape with multi-session coordination",agentInstruction:n?"先简要展示目标、范围、关键决定、验收标准、非目标及 Child 计划,再转述 message。只有用户明确确认当前完整 Shape 并选定推进方式后,才执行对应的 commandAlternatives;补充或修改要求不算确认。":"Summarize the target, scope, key decisions, acceptance criteria, non-goals, and child plan before relaying message. Execute the matching commandAlternative only after the user explicitly confirms the complete current Shape and chooses a coordination mode; additions or corrections are not confirmation."}}}function U3(e,t,r){let n=Gr(t),i=CR(e,t).filter(({wait:o})=>o.proposalHash===r);return t.loop.next_action==="resolve-verifier-blocker"&&!i.some(({action:o})=>o==="resolve-verifier-blocker")?{...n,action:"none",disposition:"blocked",mode:"reconcile",requiresUserDecision:!1,commandArgs:["comet","native","doctor",t.name,"--repair"],commandAlternatives:void 0,requiredInputs:[],inputOptions:[],userCommunication:{required:!1,message:null,suggestedReply:null,agentInstruction:t.language==="zh-CN"?"更新原 Run 的恢复选项,然后重新读取 continuation。保留候选和检查;只有用户明确决定后才重新验收或修复实现,不需要重新确认需求。":"Update the original Run recovery choices, then read its continuation again. Preserve the candidate and checks; retry verification or repair only after an explicit user decision. Do not reset the requirements."}}:{...n,commandAlternatives:[...i.map(({action:o,wait:a})=>cn(t,o,a.proposalHash)),cn(t,"revise-requirements")]}}function cn(e,t,r){return{name:t,stateVersion:e.state_version,expectedAction:t,commandArgs:["comet","native","next",e.name,`--${t}`,"--summary","<summary>",...r===void 0?[]:["--proposal-hash",r],"--expected-state-version",String(e.state_version),"--expected-action",t],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]}}async function rB(e){let r=await J3(e),n=[...e.run.actions].reverse().find(c=>["failed","unknown","running"].includes(c.status)),i=n?.outcome?.output,o=!!(i?.reason==="candidate-drift"&&e.state.phase==="verify"&&n&&e.run.actions.indexOf(n)>e.run.actions.map(c=>["build.builder","supervisor.parent.builder"].includes(c.stepId)&&c.status==="succeeded").lastIndexOf(!0)),a=typeof i?.message=="string"?i.message:(Array.isArray(i?.blockers)?i.blockers.filter(c=>typeof c=="string").join("; "):"")||n?.reason||e.run.reason||r.continuation.userCommunication.message||void 0,s=xh({state:e.state,continuation:o?{...r.continuation,disposition:"blocked",commandArgs:r.continuation.commandAlternatives?.find(c=>c.name==="revise-implementation")?.commandArgs??r.continuation.commandArgs}:r.continuation,projectRoot:e.projectRoot,reason:a});if(s&&n&&(s.owner={actionId:n.id,attempt:n.attempt,executorId:n.claim?.executorId??null,sessionId:n.claim?.sessionId??null},n.stepId==="archive.prepare"?s.code="archive-preflight-blocked":["unknown","running"].includes(n.status)&&(s.code="execution-unresolved"),o&&(s.code="candidate-drift")),o&&!e.state.loop.stop_reason){let c=e.state.language==="zh-CN",l=r.continuation.commandAlternatives?.find(u=>u.name==="revise-implementation");if(l){let u={...l,requiredInputs:["summary"]};r.continuation={...r.continuation,disposition:"continue",mode:"execute",action:"repair",requiresUserDecision:!1,commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions,commandAlternatives:r.continuation.commandAlternatives?.map(f=>f.name==="revise-implementation"?u:f),userCommunication:{required:!1,message:null,suggestedReply:null,agentInstruction:c?"先检查实际修改。若用户已有授权继续且改动仍在已确认需求范围内,执行 revise-implementation,保留现有工作和原检查,再建立后继候选并独立验收;不重建需求或重复原一次性检查。若需求或验收标准变化,走需求修订并重新确认;缺少继续授权或需要新增权限时先询问。不得自动接受新候选或沿用失效证据。":"Inspect the actual edits first. If the user has already authorized continued work and the edits remain within approved requirements, run revise-implementation, retain the existing work and original checks, and independently verify a successor candidate; do not recreate requirements or repeat original one-shot checks. If requirements or acceptance criteria changed, revise and reconfirm them; ask when continued work or additional permissions are not authorized. Do not automatically accept the successor or reuse invalid evidence."}}}}return s?{...r,continuation:{...r.continuation,recovery:s}}:r}function tB(e,t,r){let n=e.input,i=n?.activation??n,o=i?.worktree;return ms({name:t.name,phase:e.ref?.includes("verifier")?"verify":"build",language:t.language,projectRoot:typeof o=="string"?o:r,sessionId:e.claim?.sessionId,task:[t.name,...i?.child?[i.child]:[],...(i?.acceptance??(i?.child?[]:t.acceptance)).map(({text:a})=>a)].join(`
463
+ `).slice(0,4e3)})}async function J3(e){let{run:t,state:r,projectRoot:n}=e,i=q3(e.applicationId??"native",n),o=(A,S)=>r.language==="zh-CN"?S:A,a=(A,S=null)=>({required:S!==null,message:S,suggestedReply:null,agentInstruction:A}),s={schema:"comet.native.continuation.v2",skill:"comet-native",change:r.name,phase:r.phase,status:r.status,stateVersion:r.state_version,...r.status==="active"?{contextRequest:ms({name:r.name,phase:r.phase,language:r.language,projectRoot:n})}:{},disposition:"continue",mode:"execute",requiresUserDecision:!1,action:"none",commandArgs:null,requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:r.builder_handoff?.candidate_id??null,iteration:r.loop.iteration,attempt:r.loop.attempt},userCommunication:a(o("Continue from the current SDK Run.","按当前 SDK Run 继续。"))},c=await p0({projectRoot:n,run:t,state:r,base:s,cancellationObservation:e.cancellationObservation});if(c)return{...c,continuation:bN(c.continuation,n)};if(t.status==="failed"){let A=E$(t.reason),S=Bh(t),_=Wh(t);return{continuation:bN({...s,disposition:"blocked",mode:"reconcile",commandArgs:S||_?["comet","native","archive",r.name]:A?["comet","native","doctor",r.name,"--repair"]:["comet","native","doctor",r.name],requiredInputs:[],userCommunication:a(_?o("Archive finalization stopped before writing because the confirmed candidate changed. Restore the confirmed implementation and materials, then run archive to continue the existing Spec transaction.","归档收尾在写入前发现候选漂移并停止。恢复已确认的实现和材料后,执行 archive 继续原 Spec 事务。"):S?o("Archive preflight found blockers without changing the confirmed report. Resolve its blockers, then rerun archive to retry the read-only inspection. Existing receipts and approval remain bound to this candidate.","Archive 预检发现阻塞,未改写已确认报告。消除阻塞后重新执行 archive,只重试只读检查;原收据和审批仍绑定同一候选。"):o("The Run stopped. Inspect it with doctor and preserve the original failed receipts; do not claim pending work, retry an executed failure, or report that it never ran.","Run 已停止。请使用 doctor 核对并保留原失败收据;不能领取遗留待执行工作、重跑已执行失败的旧 Action,或声称它未执行。"))},n)}}let l=jd(t),u=_g(t,r),f=l.map(A=>{let S=A.type==="invoke_skill"?e.skillExecutors?.find(_=>_.supports(A)):void 0;return{id:A.id,stepId:A.stepId,type:A.type,ref:A.ref,attempt:A.attempt,inputHash:A.inputHash,mechanism:"runtime-dispatch",...typeof t.input.task=="string"?{originalRequest:{source:"run.input.task",text:t.input.task}}:{},commandArgs:A.type==="handoff"||A.type==="invoke_skill"?i:us(["comet","native","next",r.name],n),...A.type==="handoff"?{contextRequest:tB(A,r,n),...A.ref?.includes("verifier")?{sessionRequirements:{independent:wi(t,A),readOnly:!0,mustDifferFromSessionId:wi(t,A)?A.stepId==="verify.verifier"?r.builder_handoff?.builder_execution_ref??null:A.input?.activation?.builderSessionId??null:null,resumeCommandArgs:us(["comet","native","status",r.name],n),instruction:wi(t,A)?o("Launch a separate read-only session in this project. Pass this Action input and claimRequest to it, without adding Builder conclusions or turning design choices into expected behavior. That session must claim with its own stable session ID before verification and submit its own outcome; the Builder must not claim on its behalf.","在此项目启动独立只读会话,将本 Action 输入和 claimRequest 交给它,不附加 Builder 的自评或把设计取舍写成预期行为。由该会话在验收前使用自己的稳定会话标识领取,并提交自己的结果;Builder 不代领。"):o("Review the original request and current candidate using valid checks. Use this session or a separate reviewer according to the actual uncertainty and user requirements. Claim with the reviewing session identity and submit its actual conclusion.","依据原始请求、当前候选和有效检查完成验收。根据具体疑问和用户要求选择当前会话或独立审查。使用实际审查会话领取并提交真实结论。")}}:{},claimRequest:{operation:"claim",runId:t.runId,actionId:A.id,attempt:A.attempt,inputHash:A.inputHash,executorId:"native-host",sessionId:"<session-id>",claimToken:j({runId:t.runId,actionId:A.id,attempt:A.attempt,inputHash:A.inputHash})}}:{},...A.type==="invoke_skill"?{executeRequest:S?{operation:"execute",runId:t.runId,expectedRevision:t.revision,actionId:A.id,executorId:S.id}:null}:{},...A.type==="handoff"||A.type==="invoke_skill"?{input:A.input}:{}}}),d=t.waits.filter(A=>A.status==="pending"),m=(t.evidenceWaits??[]).filter(A=>A.status==="pending"),h=d.filter(A=>["build.resume","supervisor.child.resume","supervisor.parent.resume","supervisor.child.integration-resume"].includes(A.stepId)).map(A=>({waitId:A.id,stepId:A.stepId,proposalHash:A.proposalHash,commandArgs:us(cn(r,"continue-builder",A.proposalHash).commandArgs,n)})),p=d.filter(A=>A.stepId.startsWith("native.extension.revise.")).map(A=>({waitId:A.id,proposalHash:A.proposalHash,proposal:A.proposal,commandArgs:us(cn(r,"revise-requirements").commandArgs,n),message:o("The extension found changed requirements. Confirm whether to return to Shape after reconciling running or unknown work.","扩展发现需求变化。先核对 running/unknown 工作,再确认是否返回 Shape 修订需求。")})),g,v=d.find(A=>["verify.confirm","verify.retry","verify.stop"].includes(A.stepId)),w=t.actions.filter(A=>A.status==="running"||A.status==="unknown"),y=eD(t),b=DR(t),N=b!==void 0&&BR(t,r,b.proposalHash);if(t.status==="completed")g={...s,disposition:r.status==="done"?"done":"blocked",mode:r.status==="done"?"done":"reconcile",commandArgs:r.status==="done"?null:["comet","native","doctor",r.name],userCommunication:a(o(r.status==="done"?"SDK Archive has completed. Finish and verify any Git delivery already authorized by the user before reporting the task complete; Run completion alone does not prove commit, push, or PR delivery.":"The Run ended without completing the Native change. Inspect preserved results and follow Doctor before reporting completion.",r.status==="done"?"SDK 归档已完成。宣告任务完成前,继续执行并核对用户已经授权的 Git 交付;Run 完成不能证明提交、推送或 PR 已完成。":"Run 已结束,但 Native change 尚未完成。核对保留的结果并按 Doctor 恢复,不能宣告完成。"))};else if(y.length>0)g={...s,action:"retry-verifier",disposition:"await-user",mode:"ask",requiresUserDecision:!0,requiredInputs:["summary","user-decision"],commandAlternatives:y.flatMap(A=>[...A.choices.includes("retry")?[cn(r,"retry-verifier",A.proposalHash)]:[],...A.choices.includes("repair")?[cn(r,"revise-implementation",A.proposalHash)]:[]]),userCommunication:a(o("Preserve the failed execution receipt and independent Child progress. After an explicit decision, retry only the failed Child with its current candidate and checks, or return it to a new Builder. Never report an executed failure as not executed.","保留失败执行收据与其他 Child 的进度。明确决定后,仅为失败 Child 复用当前候选和检查派发新 Verifier,或交给新 Builder 修复。不能将已执行失败报告为未执行。"),o("A Child Verifier execution failed. Retry its independent review, or repair this Child first?","Child Verifier 执行失败。是否重新尝试独立验收,或先修复这个 Child?"))};else if(p.length>0||h.length>0){let A=p.length>0;g={...s,disposition:"await-user",mode:"ask",requiresUserDecision:!0,commandAlternatives:A?[cn(r,"revise-requirements")]:h.map(S=>cn(r,"continue-builder",S.proposalHash)).concat(N?[cn(r,"revise-requirements",b.proposalHash)]:[]),requiredInputs:["summary","user-decision"],userCommunication:a(o("Preserve completed work, reconcile running or unknown Actions, and execute the matching option only after the user decides.","保留已完成工作,先核对 running/unknown Action,用户明确决定后执行对应选项。"),A?p[0].message:h.some(S=>S.stepId==="supervisor.child.integration-resume")?o("The integration repair failed. Continue from its preserved integration workspace?","集成修复执行失败。是否从保留的集成工作区继续修复?"):N?o("The Builder stopped before completing this work. Continue from its preserved workspace, or revise the requirements and confirm a new Shape?","Builder 尚未完成本轮工作。请选择从保留的工作区继续,或调整需求并重新确认 Shape。"):o("The Builder stopped before completing this work. Continue from its preserved workspace?","Builder 尚未完成本轮工作。是否从保留的工作区继续?"))}}else if(v?.stepId==="verify.stop")g=U3(t,r,v.proposalHash);else if(v){let A=v.stepId==="verify.retry",S=CR(t,r).filter(({wait:_})=>_.id===v.id);g={...s,disposition:"await-user",mode:"ask",requiresUserDecision:!0,action:A?"retry-verifier":"confirm-skill-coordinated-pass",requiredInputs:["summary","user-decision"],commandAlternatives:[...S.map(({action:_,wait:Q})=>cn(r,_,Q.proposalHash)),...A?[]:[cn(r,"revise-requirements")]],userCommunication:a(o("Summarize the result and evidence, then wait for an explicit decision before executing the matching option.","简要说明结果和证据,等待用户明确决定后执行对应选项。"),A?o("Verification stopped without a usable result. Retry the independent Verifier with the preserved candidate and checks?","验收未正常返回可用结果。是否保留当前候选和检查,重新尝试独立验收?"):o("Verification passed. Accept the result for Archive, revise the implementation, or revise the requirements?","验收已通过。请选择接受结果进入归档、修改实现,或调整需求。"))}}else if(r.phase==="shape"&&w.length===0){let A=d.find(S=>["shape.confirm","supervisor.shape.confirm"].includes(S.stepId));g=Q3(r,A?.stepId==="supervisor.shape.confirm"),A&&(g={...g,commandAlternatives:[...g.commandAlternatives??[],cn(r,"revise-requirements",A.proposalHash)],userCommunication:{...g.userCommunication,agentInstruction:g.userCommunication.agentInstruction+" "+o("When the user requests changed requirements, finish updating the Shape documents and execute revise-requirements to reject this proposal and prepare a new one. Then ask for explicit approval of the new complete Shape; revision never grants approval.","用户要求调整需求时,先补全 Shape 文档,再执行 revise-requirements 拒绝旧提案并准备新提案。随后请用户明确批准新的完整 Shape;修订本身不代表批准。")}})}else if(w.length===1&&w[0].stepId==="repair.implementation"&&w[0].ref==="native-revise-implementation"&&w[0].claim?.executorId==="comet-native-revise-implementation"&&["running","unknown"].includes(w[0].status))g={...s,disposition:"continue",mode:"execute",commandArgs:["comet","native","next",r.name],userCommunication:a(o("Recheck the original read-only implementation revision with its existing claim; this does not assume the original process stopped and does not execute Archive.","使用原领取信息重新核对只读实现修订;不假定原进程已停止,也不执行 Archive。"))};else if(w.length===1&&w[0].status==="unknown"&&w[0].stepId==="verify.revalidate"&&w[0].ref==="native-report-revalidate"&&w[0].claim?.executorId==="comet-native-report-revalidate")g={...s,disposition:"continue",mode:"execute",commandArgs:["comet","native","next",r.name],userCommunication:a(o(`Report revalidation stopped: ${w[0].reason??"unknown result"}. Run next to repeat only the read-only validation with the original claim. Changed checks require fresh verification; unresolved storage or permission errors remain blocked.`,`报告复核停止:${w[0].reason??"结果未知"}。执行 next,只重读校验并保留原领取记录;检查失效后重新验收,未解决的存储或权限错误仍保持阻塞。`))};else if(r.phase==="archive"&&w.length===1&&(w[0].status==="unknown"||w[0].status==="running"&&w[0].stepId==="archive.prepare"&&w[0].claim?.executorId==="comet-native-archive-preflight"&&w[0].rejectedOutcomes?.some(A=>A.outcome.attempt===w[0].attempt))&&Gi.some(([A,S])=>w[0].stepId===A&&w[0].ref===S))g={...s,action:"archive",disposition:"blocked",mode:"reconcile",commandArgs:["comet","native","archive",r.name,"--recover"],requiredInputs:["original-archive-writer-stopped","archive-conflict-resolution"],userCommunication:a(o(`The original Archive step stopped: ${w[0].reason??"its outcome is unresolved"}. Confirm the original writer stopped and resolve the reported path or permission conflict, then run the recovery command. It reconciles the same transaction and Action; completed checks and applied Specs are retained.`,`原归档步骤已停止:${w[0].reason??"执行结果尚未核对"}。确认原写入进程已停止,处理报告中的路径或权限冲突后执行恢复命令。恢复会核对同一事务和 Action,保留已完成检查及已应用规格。`))};else if(w.some(A=>A.status==="unknown"))g={...s,disposition:"blocked",mode:"reconcile",commandArgs:null,requiredInputs:["original-execution-result"],userCommunication:a(o("Reconcile the original Action and execution before continuing. Submit its actual outcome if it executed. Only authoritative evidence that a host task never executed permits its retryRequest; an unknown result or a timeout is not that evidence.","先核对原 Action 和执行现场。已执行时提交原领取的真实结果;只有权威证据证明宿主任务确未执行,才可填写其 retryRequest。结果未知或等待超时不是未执行证据。"))};else if(d.length>0||m.length>0)g={...s,disposition:d.length>0?"await-user":"blocked",mode:d.length>0?"ask":"reconcile",requiresUserDecision:d.length>0,requiredInputs:[d.length>0?"user-decision":"runtime-evidence"],userCommunication:a(o("Review the pending SDK Wait and its complete proposal before submitting a decision or evidence with the original identity. Do not repeat Archive to skip it.","先核对待处理 SDK Wait 及其完整提案,再按原身份提交决定或证据。不能重复归档来跳过它。"),d.length>0?o("An application decision is required before continuing.","应用需要新的决定才能继续。"):null)};else if(u){let A=u,S=A.type==="handoff",_=A.type==="invoke_skill",Q=r.phase==="archive"&&l.length===1&&A.type==="call_tool"&&Gi.some(([K,Z])=>A.stepId===K&&A.ref===Z),F=f[0].executeRequest;g={...s,action:S?A.ref?.includes("verifier")?"dispatch-verifier":"builder-handoff":Q?"archive":"none",disposition:_&&!F?"blocked":"continue",mode:_&&!F?"reconcile":"execute",commandArgs:S||_&&F?["comet","runtime","dispatch","--application",e.applicationId??"native","--request","<request-json-file>"]:_?null:["comet","native",Q?"archive":"next",r.name],...S?{...A.stepId==="build.builder"&&tg(t)?{commandAlternatives:[cn(r,"revise-requirements",tg(t))]}:{},requiredInputs:["request-json-file","session-id","claim-token"],inputOptions:[{name:"request-json-file",flag:"--request",valueKind:"json-file",required:!0,template:f[0].claimRequest}]}:{},..._?{requiredInputs:F?["request-json-file"]:["skill-executor"],inputOptions:F?[{name:"request-json-file",flag:"--request",valueKind:"json-file",required:!0,template:F}]:[]}:{},userCommunication:a(_?o("Execute the pending Skill with its fixed Application executor and skillWork contract. If no compatible executor is configured, resolve that host requirement; repeating native next cannot execute this Skill.","按 skillWork 契约使用固定 Application 的执行器运行待处理 Skill。缺少适配执行器时先补全宿主要求;重复 native next 不能执行此 Skill。"):S?o("Use the pending Action claimRequest with a real stable session ID and unique claim token. After the claim succeeds, the receiving Agent reads context[].text; execute contextRequest only when the response has no contextDelivery. Use the returned Action input; Verifiers need a separate read-only session. Submit the original Action outcome, then follow the returned Run.","在待执行 Action 的 claimRequest 中填入真实稳定的会话标识和唯一领取令牌。领取成功后,接收 Agent 先读取 context[].text;响应没有 contextDelivery 时才执行自己的 contextRequest,再按返回的 Action 输入开展工作;Verifier 必须使用独立只读会话。提交原 Action 的结果后按返回的 Run 继续。"):Q?o("Execute Archive once and follow the returned state. If the platform returns a background handle, wait for that original task with its wait/output tool. After completion, parse its original stdout as one complete JSON document and keep stderr separate. Do not poll unrelated processes, parse task-status decorations as JSON, or start another Archive while this task is running.","只执行一次 Archive,并按返回状态继续。平台返回后台句柄时,使用对应的等待或输出工具跟踪原任务。完成后把原 stdout 作为一个完整 JSON 文档解析,stderr 另存;不要轮询无关进程、把任务状态提示当作 JSON,或在原任务运行时再启动 Archive。"):o("Execute the next Runtime-owned Action and follow its returned state. It revalidates current evidence before committing.","执行下一项 Runtime 自有 Action,并按返回状态继续;Runtime 会在提交前重新校验当前证据。"))}}else w.length>0?g={...s,mode:"wait",commandArgs:null,requiredInputs:["original-execution-result"],userCommunication:a(o("Continue or wait on the original claimed task. Do not create a second task because a wait timed out; submit its actual outcome with the original claim.","继续或等待原已领取任务。等待超时不能另建任务;用原领取信息提交真实结果。"))}:r.status==="done"?g={...s,disposition:"done",mode:"done"}:t.ready.length>0?g={...s,commandArgs:["comet","native","next",r.name]}:g={...s,disposition:"blocked",mode:"reconcile",requiredInputs:["runtime-evidence-or-decision"],userCommunication:a(o("Inspect the pending SDK Wait or evidence requirement before continuing; do not submit a compat Runner input.","先核对待处理的 SDK Wait 或证据要求;不要提交 compat Runner 输入。"))};return r.workspace.change_branch&&!r.archived&&!["completed","cancelled"].includes(t.status)&&de(n).currentBranch!==r.workspace.change_branch&&(g={...g,disposition:"blocked",mode:"reconcile",action:"none",commandArgs:["comet","native","select",r.name,"--rebind"],commandAlternatives:void 0,requiredInputs:["confirm-current-branch-ownership","settle-original-executions"],userCommunication:a(`当前分支与需求绑定的 ${r.workspace.change_branch} 不一致。切回原分支继续;确认当前分支接管且原执行已结束后,执行 select --rebind,保留同一 Run 和已有工作。`)}),{continuation:bN(g,n),...w.length>0?{activeActions:w.map(A=>({id:A.id,stepId:A.stepId,status:A.status,attempt:A.attempt,inputHash:A.inputHash,input:A.input,type:A.type,ref:A.ref,claim:A.claim,...A.reason?{reason:A.reason}:{},...A.type==="handoff"?{contextRequest:tB(A,r,n)}:{},commandArgs:i,resultRequest:F3(t,A,r),...H3(t,A)}))}:{},...t.status!=="completed"&&f.length>0?{pendingAction:(()=>{let{input:A,...S}=f[0];return{...S,...A===void 0?{}:{inputRef:"pendingActions[0].input"}}})(),pendingActions:f}:{},...d.length>0?{pendingWaits:d.map(A=>({...A,...["verify.stop","verify.retry","verify.confirm"].includes(A.stepId)?{choices:ns(r,A,t).map(({choice:S})=>S)}:{},commandArgs:i,decisionRequests:(["verify.stop","verify.retry","verify.confirm"].includes(A.stepId)?ns(r,A,t).map(({choice:S})=>S):A.choices).map(S=>({operation:"resolve-wait",runId:t.runId,expectedRevision:t.revision,waitId:A.id,proposalHash:A.proposalHash,decisionId:"<decision-id>",choice:S,...A.stepId==="verify.stop"&&S==="retry"?{reason:"<summary>"}:{}}))}))}:{},...m.length>0?{pendingEvidenceWaits:m.map(A=>({...A,commandArgs:i,evidenceRequest:{operation:"record-evidence",runId:t.runId,expectedRevision:t.revision,evidenceId:A.id,kind:A.kind,ref:"<evidence-relative-path>",contentHash:"<actual-evidence-sha256>",submissionId:"<submission-id>"}}))}:{},...h.length>0?{pendingBuilderDecisions:h}:{},...y.length>0?{pendingVerifierDecisions:y.map(A=>({waitId:A.id,proposalHash:A.proposalHash,proposal:A.proposal}))}:{},...p.length>0?{pendingRequirementDecisions:p}:{}}}pc();Ze();import cB from"node:path";var z3=tr(jr(),1);function nB(e,t){return t.actions.filter(r=>["pending","running","unknown"].includes(r.status)).flatMap(r=>e.manifest.bindings.filter(n=>n.workflowId===t.workflow.id&&n.stepId===r.stepId).map(n=>{let i=e.skills.get(n.skillId);return{actionId:r.id,attempt:r.attempt,inputHash:r.inputHash,binding:n,skill:{id:i.id,root:i.root,contentHash:i.contentHash,adapter:i.adapter,files:i.files}}}))}yr();Ze();Ho();Ke();import K3 from"node:path";Yt();import iB from"node:path";function oB(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function AN(e,t){let r=e.acceptance.reduce((n,i)=>({...n,[i.result]:n[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:n})=>n==="failed"||n==="blocked").map(({id:n})=>n),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(n=>({owner:n.owner,reason:oB(n.reason.text),acceptance_ids:n.acceptance_ids,resolution_action:n.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(n=>n.outcome==="fail"&&n.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:oB(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(n=>n.source).filter(n=>n!==null)].slice(0,16).map(n=>iB.relative(t.projectRoot,iB.join(t.changesDir,e.name,n)).replaceAll("\\","/")):[]},archived:e.archived}}Ji();vr();Ho();GA();Wi();function aB(e,t,r=de(e.projectRoot)){let n=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(n=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):n="The Native change requires a registered Git worktree."),n===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(n="The Native change requires its linked worktree."),{projectRoot:K3.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:n===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:n}}Ui();Ze();Me();Ac();Xt();yr();Ae();Nd();Ui();import G3 from"node:path";async function sB(e,t,r={}){let n=await qe(e,"native",t.runId,{readOnly:!0}),i=n&&n.application!=="native"?await d0(e,n.application,t.runId):await vt({singleWriter:!0,rootDir:G3.join(Ue(e),"sdk-runs/native")}).readPartitionMetadata(t.runId),o=["active","closed"].includes(i),a=t.actions.filter(h=>h.status==="unknown"),s=t.actions.some(h=>h.stepId==="archive.finalize"&&h.status==="cancelled"&&!h.outcome);if(s)try{await Hh({projectRoot:e,run:t,readOnly:!0}),s=!1}catch{}let c=[],l=[...t.actions].reverse().find(h=>h.stepId==="archive.prepare");l?.status==="failed"&&c.push({code:"native-archive-preflight-blocked",runId:t.runId,message:l.outcome?.output?.message??"Native Archive 预检未通过,请核对原 Action",nextCommand:"comet native status "+t.runId+" --json"});let u=t.status==="cancelled"?await Qi({projectRoot:e,run:t,ownerObservation:n}):null,f=n?.application==="native"&&i==="closed"&&u?.status==="cancelled",d=L(t.state),m=[...!f&&!d.archived&&d.workspace.change_branch&&de(e).currentBranch!==d.workspace.change_branch?[{code:"native-workspace-branch-mismatch",runId:t.runId,message:"当前分支与原 Run 绑定不一致;切回原分支,或确认接管并核对原执行已结束。",nextCommand:`comet native select ${t.runId} --rebind --json`}]:[],...c,...u?.cleanupRequired?[{code:"sdk-cancellation-cleanup-pending",runId:t.runId,message:u.cleanup?.reason??"原 Run 的业务取消尚未完成工作区收尾",nextCommand:u.cleanup?.finishCommand??`comet native doctor ${t.runId} --repair --json`}]:u?.status==="cancelling"?[{code:"sdk-cancellation-business-pending",runId:t.runId,message:"原 Run 仍有未核对结果的业务任务,请检查原任务后再完成取消",nextCommand:`comet native status ${t.runId} --details --json`}]:[],...o?[]:[{code:i==="missing"?"storage-run-missing":"storage-transaction-pending",runId:t.runId,message:`Native 存储状态为 ${i},尚未完成核对或收尾`,nextCommand:`comet native doctor ${t.runId} --repair --json`}],...a.map(h=>({code:"native-execution-outcome-unresolved",runId:t.runId,actionId:h.id,message:"原执行结果尚未核对,不能重放执行",nextCommand:h.stepId==="archive.finalize"?`comet native archive ${t.runId} --recover --json`:`comet native status ${t.runId} --details --json`})),...s?[{code:"native-cancelled-archive-finalization-unresolved",runId:t.runId,message:"已取消的归档仍保留未核对的原收据,需要恢复历史事务收尾",nextCommand:`comet native archive ${t.runId} --recover --json`}]:[]];return{stateReadable:!0,executionReconciled:a.length===0,storageSettled:o,healthy:m.length===0,issues:m}}Ji();Ui();var lB=12;function RN(e,t){if(t)return{items:e,omitted:0};let r=new Set(["pending","running","unknown"]),n=0,i=!1,o=[];for(let a=e.length-1;a>=0;a-=1){let s=e[a],c=s.status==="failed"&&!i;s.status==="failed"&&(i=!0),(r.has(s.status)||n++<lB||c)&&o.push(s)}return o.reverse(),{items:o,omitted:e.length-o.length}}async function NN(e){let t=await Lo(e.projectRoot,e.name);t&&(e={...e,projectRoot:t.projectRoot});let r=await ls(e.projectRoot,e.name,{readOnly:e.readOnly??!0});return Xo(e,r)}var Xo=(...e)=>Wd(()=>Y3(...e));async function Y3(e,{run:t,state:r,artifactRootRef:n,application:i}){let o=AN(r),a=await Qi({projectRoot:e.projectRoot,run:t}),s=RN(t.actions,e.details),c=RN(t.waits,e.details),l=RN(t.evidenceWaits??[],e.details),u=t.actions.flatMap(d=>{let m=d.outcome?.output;return d.stepId!=="verify.report"||d.status!=="succeeded"||typeof m?.preservedReportRef!="string"||!/^native\/preserved-verification\/[a-f0-9]{64}\/[a-f0-9]{64}\.md$/u.test(m.preservedReportRef)||typeof m.preservedReportSha256!="string"?[]:[{ref:m.preservedReportRef,path:cB.join(Ue(e.projectRoot),...m.preservedReportRef.split("/")),sha256:m.preservedReportSha256}]}),f=await Mj(e.projectRoot,t);return{schema:"comet.native.sdk-status.v1",diagnostics:await sB(e.projectRoot,t,{}),runtimeFormat:"sdk",...i?{application:i.identity,skillWork:nB(i,t)}:{},name:e.name,preservedReportsDirectory:{ref:Ya(t.runId),path:cB.join(Ue(e.projectRoot),Ya(t.runId))},...u.length?{preservedReports:u}:{},...f?{warning:f}:{},language:r.language,phase:r.phase,status:a?.status??r.status,stateVersion:r.state_version,acceptance:o.acceptance,unresolvedAcceptanceIds:o.unresolved_acceptance_ids,verificationResult:r.verification_result,candidateId:r.builder_handoff?.candidate_id??null,blockers:o.blockers,workspace:aB({projectRoot:e.projectRoot},r),run:{id:t.runId,revision:t.revision,status:t.status,history:{settledLimit:lB,actions:{total:t.actions.length,omitted:s.omitted,truncated:s.omitted>0},waits:{total:t.waits.length,omitted:c.omitted,truncated:c.omitted>0},evidenceWaits:{total:(t.evidenceWaits??[]).length,omitted:l.omitted,truncated:l.omitted>0},...s.omitted+c.omitted+l.omitted>0?{detailsCommandArgs:["comet","native","status",e.name,"--details","--json"]}:{}},actions:s.items.map(({id:d,stepId:m,status:h,attempt:p,inputHash:g,reason:v,outcome:w})=>({id:d,stepId:m,status:h,attempt:p,inputHash:g,...v??w?.output?.message?{reason:v??(w?.output).message}:{}})),waits:c.items.map(({id:d,stepId:m,status:h,proposalHash:p,choices:g})=>({id:d,stepId:m,status:h,proposalHash:p,choices:g})),evidenceWaits:l.items.map(({id:d,stepId:m,kind:h,status:p})=>({id:d,stepId:m,kind:h,status:p}))},...await rB({run:t,state:r,projectRoot:e.projectRoot,applicationId:i?.identity.id,implementationRevisionAvailable:!i||i.implementation.workflows.some(d=>d.id==="comet-native"&&!!d.commands?.["revise-implementation"]),skillExecutors:i?.implementation.executors,cancellationObservation:a}),...e.details?{details:{state:r}}:{}}}UR();pg();GR();function dB(e){if(jd(e).length!==1)return null;let r=_g(e,L(e.state));if(!r)return null;let n=Gi.findIndex(([i,o])=>r.stepId===i&&r.ref===o);return r.type==="call_tool"&&n>=0?{action:r,step:n}:null}async function fB(e){try{let t=await X3(e),r=t.data&&typeof t.data=="object"?t.data:{};if(t.exitCode===0||r.schema==="comet.native.sdk-status.v1")return t;let n=await ls(e.projectRoot,e.name,{readOnly:!0});return{...t,data:{...await Xo(e,n),...r}}}catch(t){if(t instanceof xe)throw t;let r=await ls(e.projectRoot,e.name,{readOnly:!0}).catch(()=>null),n=r?.run.actions.find(i=>["running","unknown"].includes(i.status)&&Gi.some(([o,a])=>i.stepId===o&&i.ref===a));if(!r||r.state.phase!=="archive"||!n)throw t;return{...mr("archive",{change:e.name,...await Xo(e,r)}),exitCode:73,error:{code:"blocked",message:t instanceof Error?t.message:String(t)}}}}async function X3(e){if(e.expectedPreflightHash!==void 0||e.finish!==void 0||e.serialFirst!==void 0||e.commitMessage!==void 0||e.mergeMessage!==void 0||e.confirmed)throw new xe("SDK Archive uses the confirmed Run decision and keeps Git delivery separate; compat preflight, finish, commit message and confirmation options are not accepted");if(e.recover&&e.dryRun)throw new xe("--recover and --dry-run cannot be used together");let t=await ls(e.projectRoot,e.name),{run:r,state:n}=t;if(e.recover&&r.status==="completed"&&n.archived){let p=r.outputs["archive.execute"]?.value,g=[...r.actions].reverse().find(w=>w.stepId==="archive.finalize"&&w.status==="succeeded");if(!p?.archiveRef||!g?.outcome)throw new Error("Native completed Archive lacks its original finalization receipt");let v=await vi({paths:await he(e.projectRoot,t.artifactRootRef,{readOnly:!0}),state:n,runId:r.runId,archiveRef:p.archiveRef,history:!0,allowMissingReport:["3","4"].includes(r.workflow.version)});if(j(v)!==j(g.outcome.output))throw new Error("Native completed Archive differs from its original receipt");return mr("archive",{change:e.name,alreadyArchived:!0,historicalRecovery:!0,currentImplementationRevalidated:!1,receipt:v,...await Xo(e,t)})}if(e.dryRun||(t.run=r),e.legacySpecBackup){if(e.dryRun)throw new xe("--legacy-spec-backup cannot be used with --dry-run");await eB({projectRoot:e.projectRoot,run:r,ref:e.legacySpecBackup})}if(e.recover&&r.status==="cancelled"){let p=await Hh({projectRoot:e.projectRoot,run:r});return await Rg({projectRoot:e.projectRoot,run:r}),mr("archive",{change:e.name,cancelled:!0,recoveredCancelledArchive:!0,receipt:p,...await NN(e)},`Finished the previously applied Archive transaction; the Run remains cancelled and no execution was restarted.
464
+ `)}if(e.recover){let p={"archive.prepare":Dc.id,"archive.execute":Bc.id,"archive.finalize":Uo.id},g=r.actions.filter(S=>S.type==="call_tool"&&S.status==="running"&&Gi.some(([_,Q])=>S.stepId===_&&S.ref===Q)&&S.claim!==void 0&&S.claim.executorId===p[S.stepId]&&S.rejectedOutcomes?.some(({outcome:_})=>_.actionId===S.id&&_.attempt===S.attempt&&_.inputHash===S.inputHash&&_.claimToken===S.claim.token));if(g.length===1&&!r.actions.some(S=>S.id!==g[0].id&&["running","unknown"].includes(S.status))){let S=g[0],{runtime:_}=await Go(e.projectRoot,e.name);r=await _.markUnknown({runId:r.runId,expectedRevision:r.revision,actionId:S.id,attempt:S.attempt,reason:"原归档执行已返回,但结果提交被拒;重新核对原 Action、事务和文件。"}),t.run=r}let v=r.actions.filter(S=>S.status==="unknown"),w=v.length===1?v[0]:void 0;if(n.phase!=="archive"||!w||!["supervisor.parent.deliver","archive.prepare","archive.execute","archive.finalize","supervisor.cleanup"].includes(w.stepId))return{command:"archive",exitCode:73,error:{code:"conflict",message:`Native SDK Archive for ${e.name} has no single recoverable delivery, Archive, or cleanup Action`}};let y=w.stepId==="archive.finalize"&&await Lt(await he(e.projectRoot,t.artifactRootRef,{readOnly:!0}),{kind:"archive",change:n.name})!==null,{runtime:b}=await Go(e.projectRoot,e.name);w.stepId==="supervisor.parent.deliver"?await K$({runtime:b,runId:r.runId,projectRoot:e.projectRoot}):w.stepId==="supervisor.cleanup"?await F$({runtime:b,runId:r.runId,projectRoot:e.projectRoot}):r=await S$({runtime:b,runId:r.runId,projectRoot:e.projectRoot});let N=r.actions.find(S=>S.id===w.id)?.status==="failed",A=mr("archive",{change:e.name,recoveredAction:{id:w.id,stepId:w.stepId},...w.stepId==="archive.execute"?{historicalRecovery:!0,currentImplementationRevalidated:!1,recoveryMessage:N?"已补记原归档执行在写入前的失败结果;请按当前 Verify 修复入口继续。":"沿原 Specs 事务补记原 Action;没有重新运行检查,也未重新验收当前文件。"}:{},...w.stepId==="archive.finalize"?{historicalRecovery:!y,resumedFinalization:y,currentImplementationRevalidated:!1,recoveryMessage:y?"已核对原候选、Specs 和报告,并继续原归档事务;没有重新运行验收检查。":"已凭原持久收据补记历史归档完成;没有重新执行归档,也未重新验收当前实现。"}:{},...await NN(e)});return N?{...A,exitCode:73,error:{code:"blocked",message:w.stepId==="archive.prepare"?"原归档预检已恢复为未通过;请按当前 Verify 修复入口继续。":"原归档执行已恢复为失败;请按当前 Verify 修复入口继续。"}}:A}let i=r.actions.find(p=>p.status==="pending");if(!e.dryRun&&i?.stepId==="verify.revalidate"&&jd(r).length===1&&_g(r,n)?.id===i.id&&!r.actions.some(p=>["running","unknown"].includes(p.status))&&r.waits.some(p=>p.stepId==="verify.confirm"&&p.status==="resolved"&&p.decision?.choice==="approved")){let{runtime:p,executors:g}=await Go(e.projectRoot,e.name),v=g.find(w=>w.supports(i));if(!v)throw new Error("Native accepted result has no revalidation executor");r=await p.execute({runId:r.runId,expectedRevision:r.revision,actionId:i.id,executorId:v.id,context:{requestId:uB(),projectRoot:e.projectRoot}}),n=L(r.state),t.run=r,t.state=n,i=r.actions.find(w=>w.status==="pending")}if(e.dryRun){let p=n.phase==="archive"&&dB(r)!==null,g=[];if(p||g.push(r.reason??`Native Archive is waiting at ${i?.stepId??n.loop.next_action??n.phase}`),p)try{if(i?.stepId.startsWith("archive.")){let w=await A$({run:r,action:i,projectRoot:e.projectRoot});if(w)throw new Error(w.message)}}catch(w){p=!1,g.push(w.message)}let v=p&&i?.stepId==="supervisor.parent.deliver"?await z$(r,i,e.projectRoot):void 0;return mr("archive --dry-run",{change:e.name,...await Xo(e,t),phase:n.phase,status:r.status,ready:p,blockers:g,...v?{delivery:v}:{}})}if(n.phase!=="archive"||r.status==="cancelled")return{...mr("archive",{change:e.name,...await Xo(e,{...t,run:r,state:n})}),command:"archive",exitCode:73,error:{code:"conflict",message:`Native SDK Archive for ${e.name} has no pending Archive Action; inspect comet native status ${e.name} --json`}};let{runtime:o,executors:a}=await Go(e.projectRoot,e.name),s=Bh(r);s&&(r=await o.retry({runId:r.runId,expectedRevision:r.revision,actionId:s.id,attempt:s.attempt}),n=L(r.state));let c=Wh(r);c&&(r=await o.retry({runId:r.runId,expectedRevision:r.revision,actionId:c.id,attempt:c.attempt,reconciliation:{resolution:"not-executed",evidence:{actionId:c.id,attempt:c.attempt,outcomeId:c.outcome.outcomeId,reason:"Runtime finalization stopped at candidate validation before any finalization writes."}}}),n=L(r.state));let l=[],u=-1;for(let p=0;p<Gi.length&&n.phase==="archive";p+=1){let g=dB(r);if(!g)break;let{action:v,step:w}=g;if(u>=0&&w!==u+1)break;let y=a.find(N=>N.supports(v));if(!y)throw new Error(`Native SDK Action ${v.stepId} has no executor`);r=await o.execute({runId:r.runId,expectedRevision:r.revision,actionId:v.id,executorId:y.id,context:{requestId:uB(),projectRoot:e.projectRoot}}),n=L(r.state);let b=r.actions.find(N=>N.id===v.id);if(l.push({id:b.id,stepId:b.stepId,status:b.status}),u=w,b.status!=="succeeded")break}let f=mr("archive",{change:e.name,completedActions:l,...await Xo(e,{...t,run:r,state:n})}),d=[...r.actions].reverse().find(p=>Gi.some(([g])=>p.stepId===g)),m=r.actions.find(p=>["running","unknown"].includes(p.status)),h=d?.status==="failed"?d:void 0;return m||h?{...f,exitCode:73,error:{code:"blocked",message:`Native SDK Archive stopped at ${m?.stepId??h.stepId}; inspect the original Action before continuing`}}:f}function mB(e,t){if(t.length===0)return e;let r=n=>n[0]==="comet"&&n[1]==="native"&&n[2]==="archive"?[...n,...t]:n;return{...e,...e.commandArgs?{commandArgs:r(e.commandArgs)}:{},...e.commandAlternatives?{commandAlternatives:e.commandAlternatives.map(n=>({...n,commandArgs:n.commandArgs?r(n.commandArgs):null}))}:{}}}async function hB(e,t){let r=VD(e,"change name"),n=Yo(e,"--dry-run"),i=Yo(e,"--recover"),o=ki(e,"--expect-preflight"),a=Yo(e,"--confirmed");if(n&&a)throw new xe("--confirmed is only valid when executing Archive");let s=ki(e,"--finish"),c=ki(e,"--expected-state-version"),l=c===void 0?void 0:Number(c);if(c!==void 0&&(!/^\d+$/u.test(c)||!Number.isSafeInteger(l)||!a||!s))throw new xe("--expected-state-version requires --confirmed --finish and a non-negative integer");let u=ki(e,"--legacy-spec-backup"),f=ki(e,"--serial-first"),d=ki(e,"--commit-message"),m=ki(e,"--merge-message");for(let[S,_]of[["--commit-message",d],["--merge-message",m]])if(_!==void 0)try{$h(_,S)}catch(Q){throw new xe(Q.message)}let h=[...d===void 0?[]:["--commit-message",d],...m===void 0?[]:["--merge-message",m]];if(f!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(f))throw new xe("--serial-first must be one Native change name");let p=s;if(p!==void 0&&p!=="merge"&&p!=="push"&&p!=="pull-request"&&p!=="keep")throw new xe("--finish must be merge, push, pull-request, or keep");Td(e);let g=await Ng(t,r);if(await qe(g,"native",r))return fB({projectRoot:g,name:r,dryRun:n,recover:i,confirmed:a,...o===void 0?{}:{expectedPreflightHash:o},...s===void 0?{}:{finish:s},...f===void 0?{}:{serialFirst:f},...d===void 0?{}:{commitMessage:d},...m===void 0?{}:{mergeMessage:m},...u===void 0?{}:{legacySpecBackup:u}});if(u!==void 0)throw new xe("--legacy-spec-backup is only available for SDK-owned Native changes");if(i)throw new xe("--recover is only available for SDK-owned Native changes");let v=await HD(t),w=await Tm(v.paths,r);if(l!==void 0&&!w)throw new xe("The workspace finish decision is stale; read the current continuation");let y=await jc(v.paths,r),b=await Lt(v.paths,{kind:"archive",change:r}),N=b?.kind==="archive"?b.journal.spec_changes.slice(0,b.journal.next_spec_index):[],A=w?!1:await Zj(v.paths,r);if(y&&!w&&b?.kind!=="archive"&&(y.archiveDir||!A)){if(o)throw new xe("A recorded workspace finish does not use preflight hashes");if(f)throw new xe("--serial-first is only valid while archiving an active change");if(s&&(y.plan?.finish??y.result?.action)&&s!==(y.plan?.finish??y.result?.action))throw new xe(`Recorded workspace finish is '${y.plan?.finish??y.result?.action}'; retry it without changing --finish`);if(n){let K=y.plan?await $c({name:r,plan:y.plan,journal:y,commitMessage:d,mergeMessage:m}):null;return{command:"archive --dry-run",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:y.result,commitMessages:{commitMessage:d??K?.commitMessage??`chore(native): archive ${r}`,mergeMessage:m??K?.mergeMessage??null},recovery:[...y.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],...h,...K?.mergeMessage&&m===void 0?["--merge-message",K.mergeMessage]:[]]},error:{code:"conflict",message:y.result?.message??"Native workspace finish is still pending"}}}if(!a)throw new xe("Native workspace finish is pending; rerun Archive with --confirmed after resolving the blocker");Td(e);let S=await SR(v.paths,y),_=await dc(v.paths,S.state);_&&!Li(_)&&await wR({paths:v.paths,name:r});let Q=y.archiveDir,F;try{F=await Ad({paths:v.paths,state:S.state,archiveDir:Q,pullRequestFinish:v.config.native.finish?.pull_request}),F&&(F=await $c({name:r,plan:F,journal:y,commitMessage:d,mergeMessage:m}))}catch(K){let Z=K instanceof Error?K.message:String(K),re={...y.result??{action:S.state.workspace.finish??"keep",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:null,cleanup:{performed:!1,reason:null},blockedPaths:[],diagnosticArgs:null,recoveryArgs:null},status:"blocked",message:Z,recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await Ki(v.paths,{...y,status:"blocked",result:re,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:S.state,archiveDir:Q,workspaceFinish:S.state.workspace.finish,workspaceFinishResult:re,continuation:{disposition:"blocked",mode:"reconcile",reason:Z,commandArgs:re.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:Z}}}if(F){await Ki(v.paths,{...y,plan:F,updatedAt:new Date().toISOString()});try{let K=await ER({paths:v.paths,state:S.state,name:r,archiveDir:Q,transactionId:y.transactionId,plan:F});return await bd(v.paths,r),mr("archive",{archived:!0,state:S.state,archiveDir:Q,workspaceFinish:S.state.workspace.finish,workspaceFinishResult:K,continuation:Gr(S.state)},`Completed pending workspace finish for Native change ${r}
465
+ `)}catch(K){if(!(K instanceof Oc))throw K;return await Ki(v.paths,{...await jc(v.paths,r)??y,status:"blocked",result:K.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:S.state,archiveDir:Q,workspaceFinish:S.state.workspace.finish,workspaceFinishResult:K.result,continuation:{disposition:"blocked",mode:"reconcile",reason:K.message,commandArgs:K.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:K.message}}}}return await bd(v.paths,r),mr("archive",{archived:!0,state:S.state,archiveDir:Q,workspaceFinish:S.state.workspace.finish,workspaceFinishResult:null,continuation:Gr(S.state)},`Native change ${r} is already archived
466
+ `)}if(w||A||y){if(o)throw new xe("Portable Native Archive does not use preflight hashes");if(n&&a)throw new xe("--confirmed is only valid when executing Archive");if(f&&f!==r)throw new xe("--serial-first must name the change being archived");if(!n&&p&&!a)throw new xe("--finish without --dry-run requires --confirmed");Td(e);let S=w?await ur(v.paths,r):null;if(l!==void 0&&(S?.state_version!==l||S.workspace.finish!==null))throw new xe("The workspace finish decision is stale; read the current continuation");if(m!==void 0&&S&&(p??S.workspace.finish)!=="merge")throw new xe("--merge-message requires a merge workspace finish");if(!n&&a&&p&&S&&S.workspace.isolation!=="current"&&S.workspace.finish===null&&(S=await Rh({paths:v.paths,name:r,finish:p,expectedStateVersion:l})),n){if(!S)return mr("archive --dry-run",{change:r,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",mode:"execute",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",r,"--confirmed",...h],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${r}
467
+ `);p&&(S=await Rh({paths:v.paths,name:r,finish:p}));let re=await wd({paths:v.paths,name:r});if(re.requiresReverification)return mr("archive --dry-run",{...re,archived:!1,ready:!1,state:S,blockers:re.blockers,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:Gr(S)},`Native Archive preview requires fresh verification after delta remerge; no rebase was written during dry-run
468
+ `);let X=[...re.blockers],Oe=[],Be=null,B=S.workspace.isolation!=="current"&&S.workspace.finish===null;if(B&&X.push("Native branch and worktree isolation require a workspace finish choice"),!B)try{Be=await Ad({paths:v.paths,state:S,appliedSpecChanges:N,pullRequestFinish:v.config.native.finish?.pull_request}),Be&&(Be=await $c({name:r,plan:Be,journal:y,commitMessage:d,mergeMessage:m}))}catch(it){let I=it.message;X.push(I),Oe.push({message:I,paths:it instanceof Kn?it.paths:[],workspaceRoot:it instanceof Kn?it.workspaceRoot:v.paths.projectRoot})}let ie=B?Gr(S):Gr(S,null,{archiveMode:"preview",archiveBlockers:X}),pe=X;return mr("archive --dry-run",{...re,ready:pe.length===0,blockers:pe,...Oe.length>0?{workspaceFinishBlockers:Oe}:{},workspaceFinish:S.workspace.finish,commitMessages:Be?{commitMessage:Be.commitMessage,mergeMessage:Be.mergeMessage}:null,continuation:mB(f===r&&ie.commandArgs?{...ie,commandArgs:[...ie.commandArgs,"--serial-first",r]}:ie,Be?.mergeMessage&&m===void 0?[...h,"--merge-message",Be.mergeMessage]:h)},`Native Archive preview: ${pe.length===0?"ready":"blocked"}
469
+ `)}if(v.config.native.archive_confirmation==="required"&&!a)throw new xe("archive requires --confirmed when native.archive_confirmation is required");if(S&&S.workspace.isolation!=="current"&&S.workspace.finish===null){let re=Gr(S);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:mB(re,h)},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let _=null;if(S)try{_=await Ad({paths:v.paths,state:S,appliedSpecChanges:N,pullRequestFinish:v.config.native.finish?.pull_request}),_&&(_=await $c({name:r,plan:_,journal:y,commitMessage:d,mergeMessage:m}))}catch(re){let X=re.message,Oe=re instanceof Kn?re.paths:[],Be=re instanceof Kn?re.workspaceRoot:v.paths.projectRoot,B={action:S.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:Be,cleanup:{performed:!1,reason:null},blockedPaths:Oe,message:X,diagnosticArgs:["git","-C",Be,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:S,workspaceFinish:S.workspace.finish,workspaceFinishResult:B,continuation:Gr(S,null,{archiveMode:"blocked",archiveBlockers:[X]})},error:{code:"conflict",message:X}}}let Q=!1;_&&(await Ki(v.paths,{...y,schema:rs,name:r,transactionId:y?.transactionId??(b?.kind==="archive"?b.journal.id:void 0)??Z3(),archiveDir:y?.archiveDir??(S?Yj(v.paths,S):null),...S?{createdAt:S.created_at}:{},status:"pending",result:null,updatedAt:new Date().toISOString(),plan:_}),Q=!0);let F;try{F=await wR({paths:v.paths,name:r})}catch(re){if(re instanceof Sh)return(Q||y)&&await bd(v.paths,r),mr("archive",{archived:!1,state:re.state,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:Gr(re.state)},`Native Archive requires fresh verification after delta remerge
470
+ `);throw re}if(S=F.state,!_&&S)try{_=await Ad({paths:v.paths,state:S,archiveDir:F.archiveDir,pullRequestFinish:v.config.native.finish?.pull_request}),_&&(_=await $c({name:r,plan:_,journal:y,commitMessage:d,mergeMessage:m}))}catch(re){let X=re.message,Oe=re instanceof Kn?re.paths:[],Be=re instanceof Kn?re.workspaceRoot:v.paths.projectRoot,B={action:S.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:Be,cleanup:{performed:!1,reason:null},blockedPaths:Oe,message:X,diagnosticArgs:["git","-C",Be,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await Ki(v.paths,{schema:rs,name:r,transactionId:F.transactionId,archiveDir:F.archiveDir,status:"blocked",result:B,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{...F,workspaceFinish:S.workspace.finish,workspaceFinishResult:B,continuation:{disposition:"blocked",mode:"reconcile",reason:X,commandArgs:B.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:X}}}_&&await Ki(v.paths,{...await jc(v.paths,r),schema:rs,name:r,transactionId:F.transactionId,archiveDir:F.archiveDir,status:"pending",result:null,updatedAt:new Date().toISOString(),plan:_});let K=null;if(_)try{K=await ER({paths:v.paths,state:F.state,name:r,archiveDir:F.archiveDir,transactionId:F.transactionId,plan:_})}catch(re){if(!(re instanceof Oc))throw re;return await Ki(v.paths,{...await jc(v.paths,r),schema:rs,name:r,transactionId:F.transactionId,archiveDir:F.archiveDir,status:"blocked",result:re.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{...F,archived:!0,workspaceFinish:F.state.workspace.finish,workspaceFinishResult:re.result,continuation:{disposition:"blocked",mode:"reconcile",reason:re.message,commandArgs:re.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:re.message}}}_&&await bd(v.paths,r);let Z=K?.merged===!0?await XA({childPaths:v.paths,childState:F.state}):null;return mr("archive",{...F,archived:!0,artifactRefs:["brief.md",...F.state.verification_report?[F.state.verification_report]:[]].map(re=>pB.relative(t,pB.join(F.archiveDir,re)).replaceAll("\\","/")),workspaceFinish:F.state.workspace.finish,workspaceFinishResult:K,...Z?{parentAdvance:Z.parentAdvance}:{},...Z?.parentState?{parentState:Z.parentState}:{},continuation:Gr(Z?.parentState??F.state)},`Archived Native change ${r} to ${F.archiveDir}
471
+ `)}if(f)throw new xe("--serial-first is only valid for portable Native changes");if(!n&&p&&!a)throw new xe("--finish without --dry-run requires --confirmed");return Td(e),{command:n?"archive --dry-run":"archive",exitCode:65,data:{change:r,migrationRequired:!0,repairCommand:`comet native doctor ${r} --repair`},error:{code:"invalid-data",message:`Native active change ${r} requires explicit business import; run comet native doctor ${r} --repair`}}}import{Buffer as gB}from"node:buffer";var e6=new Set(["continuation","input","commandArgs","userCommunication","current","pendingAction","changedPaths","artifactRefs","artifacts"]);function t6(e){if("outputView"in e)return e;let t={},r=new Map,n=new WeakMap,i=u=>u.replace(/~/gu,"~0").replace(/\//gu,"~1"),o=(u,f)=>/requests?$/iu.test(u)||f!==null&&typeof f=="object"&&"operation"in f,a=u=>{if(u===null||typeof u!="object")return!1;let f=n.get(u);if(f!==void 0)return f;let d=Object.entries(u).some(([m,h])=>o(m,h)||a(h));return n.set(u,d),d},s=(u,f,d,m)=>{if(o(d,u)||/(?:hash|revision|attempt|claim|token|blockers|workspace)$/iu.test(d))return u;if(m&&(typeof u=="string"&&u.length>=160||e6.has(d)&&u!==null&&typeof u=="object"&&!a(u))){let p=JSON.stringify(u);if(p.length>=160){let g=r.get(p);if(g!==void 0&&g.length+f.length+8<p.length){t[f]=g;return}return r.set(p,f),u}}return Array.isArray(u)?u.map((p,g)=>s(p,`${f}/${g}`,"",!1)):u!==null&&typeof u=="object"?Object.fromEntries(Object.entries(u).flatMap(([p,g])=>{let v=s(g,`${f}/${i(p)}`,p,!0);return v===void 0?[]:[[p,v]]})):u},c={..."data"in e?{data:e.data}:{},...e};return{...s(c,"","",!1),outputView:{schema:"comet.cli.compact.v1",mode:"compact",references:t,instruction:"references maps omitted JSON Pointers to equal values in this response (RFC 6901). Resolve references recursively to restore the full JSON. Request templates remain complete. Omit --compact for the full envelope."}}}function vB(e,t){if(!t||!e)return e;let r=JSON.parse(e);if(r===null||typeof r!="object"||Array.isArray(r))return e;let n=t6(r),i=n.outputView;if(!i?.references||Object.keys(i.references).length===0)return e;let o=`${JSON.stringify(n)}
472
+ `;return gB.byteLength(o)<gB.byteLength(e)?o:e}rr();import Ig from"node:path";function bi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function wB(e,t){if(e.error?.code==="usage"||e.command==="hook-guard")return e;let r=bi(e.data),n=bi(r.continuation);if(bi(r.builderReadiness).ready===!1&&n.action==="builder-handoff")return e;let i=typeof r.change=="string"?r.change:typeof r.name=="string"?r.name:t.name,o=i&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i)?i:void 0,a=e.executionCwd??Ig.resolve(t.projectRoot);o&&e.exitCode!==0&&!e.executionCwd&&(a=await Ng(a,o,{readOnly:!0}).catch(()=>a));let s=w=>Ih(w,a),c=s(["comet","native","doctor",...o?[o]:[]]),l=bi(r.state),u=bi(r.workspaceFinishResult),f=typeof u.message=="string"?u.message:e.error?.message??"",d=f.toLowerCase(),m=d.split(`
473
+ `),h=m.some(w=>{let y=w.indexOf("worktree");return y!==-1&&w.indexOf("locked",y+8+1)!==-1}),p=d.includes("index.lock")||d.includes("cannot lock ref")||h||m.some(w=>{let y=w.indexOf("unable to create");return y!==-1&&w.indexOf(".lock",y+16+1)!==-1}),g={schema:"comet.native.recovery.v1",code:"runtime-recovery-required",reason:e.error?.message??(typeof bi(r.recovery).reason=="string"?bi(r.recovery).reason:"Inspect the original execution and its retained evidence."),affectedPaths:[],owner:null,diagnosticArgs:c,recoveryArgs:null,preconditions:["Inspect the original Action before retrying; preserve its receipts."],preserved:{candidateId:bi(l.builder_handoff).candidate_id??r.candidateId??null,shapeConfirmationHash:l.shape_confirmation_hash??r.shapeConfirmationHash??null}},v=bi(r.recovery).schema?r.recovery:bi(n.recovery).schema?n.recovery:void 0;if(p){let w=typeof u.targetRoot=="string"?u.targetRoot:a,y=[];try{/index\.lock/iu.test(f)?y.push(Ig.resolve(w,q(w,["rev-parse","--git-path","index.lock"]))):h&&y.push(Ig.join(Ig.resolve(w,q(w,["rev-parse","--git-dir"])),"locked"))}catch{}v={...g,code:"git-lock",reason:f,affectedPaths:y,owner:null,diagnosticArgs:["git","-C",w,"status","--short"],recoveryArgs:Array.isArray(u.recoveryArgs)?s(u.recoveryArgs):Array.isArray(n.commandArgs)?s(n.commandArgs):e.command==="archive"&&o?s(["comet","native","archive",o]):null,preconditions:["Inspect the original Git command result and resolve its reported Git condition before retrying.","Resolve the reported Git lock or worktree condition, then retry the retained workflow step."]}}else if(!v&&(e.exitCode!==0||n.disposition==="blocked")){let w=Array.isArray(u.recoveryArgs)?u.recoveryArgs:n.commandArgs;v={...g,code:u.status==="blocked"?"workspace-conflict":e.command==="archive"?"archive-blocked":"runtime-recovery-required",reason:typeof u.message=="string"?u.message:g.reason,affectedPaths:Array.isArray(u.blockedPaths)?u.blockedPaths:[],diagnosticArgs:Array.isArray(u.diagnosticArgs)?u.diagnosticArgs:c,recoveryArgs:Array.isArray(w)&&w.every(y=>typeof y=="string")?s(w):null,preconditions:["Resolve the reported file, transaction, or execution conflict, then retry the original step."]}}return v?{...e,data:{...r,recovery:v,...n.schema?{continuation:{...n,recovery:v}}:{}},...e.error?{envelope:{summary:v.reason,next:{command:(v.recoveryArgs??v.diagnosticArgs).map(w=>/^[\w./:=+@-]+$/u.test(w)?w:JSON.stringify(w)).join(" ")}}}:{}}:e}Ze();async function yB(e,t,r=process.argv.slice(2)){let n=r.indexOf("--"),i=n<0?[...r]:r.slice(0,n),o=n<0?[]:r.slice(n),a=i.includes("--json"),s=i.includes("--verbose"),c=i.includes("--compact"),l,u,f,d;try{if(Yo(i,"--json"),Yo(i,"--compact"),c&&!a)throw new xe("--compact requires --json");Yo(i,"--verbose"),l=ki(i,"--project-root");let h=[...i,...o];u=h[0]?.startsWith("--")?void 0:h[0];let p=async()=>{let g=await MD(l);return{executionCwd:g,...await t(h,g)}};d=FD(e,h)?await Wd(p):await p()}catch(h){f=h,d=UD(e,h)}d=await wB(d,{projectRoot:d.executionCwd??l??process.cwd(),name:u,error:f});let m=JD(d,a,s);return m.stdout&&process.stdout.write(vB(m.stdout,c&&a)),m.stderr&&process.stderr.write(m.stderr+(m.stderr.endsWith(`
474
+ `)?"":`
475
+ `)),m.exitCode}process.exitCode=await yB("archive",hB);