@rpamis/comet 0.4.0-rc.6 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +332 -333
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-archive.mjs +56 -51
  5. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +22 -20
  6. package/assets/skills/comet/scripts/comet-guard.mjs +93 -88
  7. package/assets/skills/comet/scripts/comet-handoff.mjs +111 -106
  8. package/assets/skills/comet/scripts/comet-hook-guard.mjs +54 -49
  9. package/assets/skills/comet/scripts/comet-hook-router.mjs +106 -106
  10. package/assets/skills/comet/scripts/comet-intent.mjs +12 -7
  11. package/assets/skills/comet/scripts/comet-resume-probe.mjs +50 -45
  12. package/assets/skills/comet/scripts/comet-runtime.mjs +180 -175
  13. package/assets/skills/comet/scripts/comet-state.mjs +80 -75
  14. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +57 -52
  15. package/assets/skills/comet-classic/reference/scripts.md +1 -1
  16. package/assets/skills/comet-native/SKILL.md +3 -3
  17. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +31 -31
  18. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +51 -51
  19. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +3 -3
  20. package/assets/skills/comet-native/scripts/comet-native-init.mjs +37 -37
  21. package/assets/skills/comet-native/scripts/comet-native-new.mjs +33 -33
  22. package/assets/skills/comet-native/scripts/comet-native-next.mjs +43 -43
  23. package/assets/skills/comet-native/scripts/comet-native-root.mjs +3 -3
  24. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +71 -71
  25. package/assets/skills/comet-native/scripts/comet-native-select.mjs +36 -36
  26. package/assets/skills/comet-native/scripts/comet-native-show.mjs +27 -27
  27. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +23 -23
  28. package/assets/skills/comet-native/scripts/comet-native-status.mjs +39 -39
  29. package/assets/skills-zh/comet-classic/reference/scripts.md +1 -1
  30. package/assets/skills-zh/comet-native/SKILL.md +3 -3
  31. package/bin/fast-runtime-router.js +1 -1
  32. package/dist/app/cli/index.js +7 -1
  33. package/dist/app/cli/index.js.map +1 -1
  34. package/dist/app/commands/classic.js +4 -0
  35. package/dist/app/commands/classic.js.map +1 -1
  36. package/dist/app/commands/doctor.d.ts +1 -1
  37. package/dist/app/commands/doctor.d.ts.map +1 -1
  38. package/dist/app/commands/doctor.js +2 -1
  39. package/dist/app/commands/doctor.js.map +1 -1
  40. package/dist/app/commands/eval.js +2 -2
  41. package/dist/app/commands/eval.js.map +1 -1
  42. package/dist/app/commands/init.d.ts.map +1 -1
  43. package/dist/app/commands/init.js +16 -5
  44. package/dist/app/commands/init.js.map +1 -1
  45. package/dist/app/commands/personal-memory.d.ts.map +1 -1
  46. package/dist/app/commands/personal-memory.js +5 -0
  47. package/dist/app/commands/personal-memory.js.map +1 -1
  48. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  49. package/dist/app/commands/project-knowledge.js +26 -2
  50. package/dist/app/commands/project-knowledge.js.map +1 -1
  51. package/dist/app/commands/status.d.ts.map +1 -1
  52. package/dist/app/commands/status.js +17 -10
  53. package/dist/app/commands/status.js.map +1 -1
  54. package/dist/app/commands/uninstall.d.ts.map +1 -1
  55. package/dist/app/commands/uninstall.js +5 -1
  56. package/dist/app/commands/uninstall.js.map +1 -1
  57. package/dist/app/commands/update.d.ts.map +1 -1
  58. package/dist/app/commands/update.js +10 -4
  59. package/dist/app/commands/update.js.map +1 -1
  60. package/dist/domains/agent-learning/context-director.d.ts.map +1 -1
  61. package/dist/domains/agent-learning/context-director.js +14 -10
  62. package/dist/domains/agent-learning/context-director.js.map +1 -1
  63. package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
  64. package/dist/domains/comet-classic/classic-archive.js +3 -0
  65. package/dist/domains/comet-classic/classic-archive.js.map +1 -1
  66. package/dist/domains/comet-classic/classic-cli-help.d.ts +3 -0
  67. package/dist/domains/comet-classic/classic-cli-help.d.ts.map +1 -0
  68. package/dist/domains/comet-classic/classic-cli-help.js +40 -0
  69. package/dist/domains/comet-classic/classic-cli-help.js.map +1 -0
  70. package/dist/domains/comet-classic/classic-cli.d.ts +1 -0
  71. package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
  72. package/dist/domains/comet-classic/classic-cli.js +5 -0
  73. package/dist/domains/comet-classic/classic-cli.js.map +1 -1
  74. package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
  75. package/dist/domains/comet-classic/classic-guard.js +12 -2
  76. package/dist/domains/comet-classic/classic-guard.js.map +1 -1
  77. package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
  78. package/dist/domains/comet-classic/classic-handoff.js +11 -10
  79. package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
  80. package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
  81. package/dist/domains/comet-classic/classic-script-entry.js +4 -1
  82. package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
  83. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  84. package/dist/domains/comet-classic/classic-state-command.js +37 -18
  85. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  86. package/dist/domains/comet-classic/classic-validate-command.d.ts.map +1 -1
  87. package/dist/domains/comet-classic/classic-validate-command.js +2 -0
  88. package/dist/domains/comet-classic/classic-validate-command.js.map +1 -1
  89. package/dist/domains/comet-classic/classic-workspace.d.ts +1 -0
  90. package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -1
  91. package/dist/domains/comet-classic/classic-workspace.js +2 -1
  92. package/dist/domains/comet-classic/classic-workspace.js.map +1 -1
  93. package/dist/domains/comet-entry/entry-runtime.d.ts.map +1 -1
  94. package/dist/domains/comet-entry/entry-runtime.js +13 -3
  95. package/dist/domains/comet-entry/entry-runtime.js.map +1 -1
  96. package/dist/domains/comet-memory/plugin.js +4 -9
  97. package/dist/domains/comet-memory/plugin.js.map +1 -1
  98. package/dist/domains/comet-memory/repository.d.ts +3 -0
  99. package/dist/domains/comet-memory/repository.d.ts.map +1 -1
  100. package/dist/domains/comet-memory/repository.js +117 -25
  101. package/dist/domains/comet-memory/repository.js.map +1 -1
  102. package/dist/domains/comet-memory/review-contract.d.ts.map +1 -1
  103. package/dist/domains/comet-memory/review-contract.js +4 -2
  104. package/dist/domains/comet-memory/review-contract.js.map +1 -1
  105. package/dist/domains/comet-native/native-check-command.d.ts.map +1 -1
  106. package/dist/domains/comet-native/native-check-command.js +5 -1
  107. package/dist/domains/comet-native/native-check-command.js.map +1 -1
  108. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  109. package/dist/domains/comet-native/native-cli-help.js +7 -2
  110. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  111. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  112. package/dist/domains/comet-native/native-next-command.js +22 -1
  113. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  114. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
  115. package/dist/domains/comet-native/native-output-language.js +3 -1
  116. package/dist/domains/comet-native/native-output-language.js.map +1 -1
  117. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  118. package/dist/domains/comet-native/native-portable-continuation.js +11 -0
  119. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  120. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  121. package/dist/domains/comet-plugin/integration.js +14 -8
  122. package/dist/domains/comet-plugin/integration.js.map +1 -1
  123. package/dist/domains/comet-plugin/plugin-runtime.d.ts +2 -2
  124. package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
  125. package/dist/domains/comet-plugin/plugin-runtime.js +89 -77
  126. package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
  127. package/dist/domains/comet-plugin/types.d.ts +2 -0
  128. package/dist/domains/comet-plugin/types.d.ts.map +1 -1
  129. package/dist/domains/dashboard/server.d.ts.map +1 -1
  130. package/dist/domains/dashboard/server.js +20 -0
  131. package/dist/domains/dashboard/server.js.map +1 -1
  132. package/dist/domains/dashboard/web/index.html +14 -14
  133. package/dist/domains/integrations/openspec.d.ts.map +1 -1
  134. package/dist/domains/integrations/openspec.js +4 -3
  135. package/dist/domains/integrations/openspec.js.map +1 -1
  136. package/dist/domains/integrations/superpowers.js +2 -2
  137. package/dist/domains/integrations/superpowers.js.map +1 -1
  138. package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
  139. package/dist/domains/project-knowledge/corpus.js +5 -2
  140. package/dist/domains/project-knowledge/corpus.js.map +1 -1
  141. package/dist/domains/skill/languages.d.ts +3 -1
  142. package/dist/domains/skill/languages.d.ts.map +1 -1
  143. package/dist/domains/skill/languages.js +26 -1
  144. package/dist/domains/skill/languages.js.map +1 -1
  145. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  146. package/dist/domains/skill/uninstall.js +16 -0
  147. package/dist/domains/skill/uninstall.js.map +1 -1
  148. package/dist/platform/process/git-environment.d.ts +3 -0
  149. package/dist/platform/process/git-environment.d.ts.map +1 -0
  150. package/dist/platform/process/git-environment.js +26 -0
  151. package/dist/platform/process/git-environment.js.map +1 -0
  152. package/eval/langsmith/tests/tasks/test_tasks.py +6 -0
  153. package/eval/local/tests/scaffold/test_langsmith_conftest.py +10 -0
  154. package/package.json +2 -2
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var hN=Object.create;var Dc=Object.defineProperty;var mN=Object.getOwnPropertyDescriptor;var vN=Object.getOwnPropertyNames;var gN=Object.getPrototypeOf,wN=Object.prototype.hasOwnProperty;var Ja=(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 C=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Ga=(e,t)=>{for(var r in t)Dc(e,r,{get:t[r],enumerable:!0})},yN=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vN(t))!wN.call(e,n)&&n!==r&&Dc(e,n,{get:()=>t[n],enumerable:!(i=mN(t,n))||i.enumerable});return e};var nn=(e,t,r)=>(r=e!=null?hN(gN(e)):{},yN(t||!e||!e.__esModule?Dc(r,"default",{value:e,enumerable:!0}):r,e));var O=x(fe=>{"use strict";var Bc=Symbol.for("yaml.alias"),qf=Symbol.for("yaml.document"),Ua=Symbol.for("yaml.map"),Wf=Symbol.for("yaml.pair"),Lc=Symbol.for("yaml.scalar"),Ka=Symbol.for("yaml.seq"),Lt=Symbol.for("yaml.node.type"),NN=e=>!!e&&typeof e=="object"&&e[Lt]===Bc,bN=e=>!!e&&typeof e=="object"&&e[Lt]===qf,kN=e=>!!e&&typeof e=="object"&&e[Lt]===Ua,SN=e=>!!e&&typeof e=="object"&&e[Lt]===Wf,zf=e=>!!e&&typeof e=="object"&&e[Lt]===Lc,EN=e=>!!e&&typeof e=="object"&&e[Lt]===Ka;function Jf(e){if(e&&typeof e=="object")switch(e[Lt]){case Ua:case Ka:return!0}return!1}function xN(e){if(e&&typeof e=="object")switch(e[Lt]){case Bc:case Ua:case Lc:case Ka:return!0}return!1}var CN=e=>(zf(e)||Jf(e))&&!!e.anchor;fe.ALIAS=Bc;fe.DOC=qf;fe.MAP=Ua;fe.NODE_TYPE=Lt;fe.PAIR=Wf;fe.SCALAR=Lc;fe.SEQ=Ka;fe.hasAnchor=CN;fe.isAlias=NN;fe.isCollection=Jf;fe.isDocument=bN;fe.isMap=kN;fe.isNode=xN;fe.isPair=SN;fe.isScalar=zf;fe.isSeq=EN});var an=x(Vc=>{"use strict";var re=O(),Ae=Symbol("break visit"),Gf=Symbol("skip children"),gt=Symbol("remove node");function Ya(e,t){let r=Uf(t);re.isDocument(e)?fi(null,e.contents,r,Object.freeze([e]))===gt&&(e.contents=null):fi(null,e,r,Object.freeze([]))}Ya.BREAK=Ae;Ya.SKIP=Gf;Ya.REMOVE=gt;function fi(e,t,r,i){let n=Kf(e,t,r,i);if(re.isNode(n)||re.isPair(n))return Yf(e,i,n),fi(e,n,r,i);if(typeof n!="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=fi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Ae)return Ae;o===gt&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let a=fi("key",t.key,r,i);if(a===Ae)return Ae;a===gt&&(t.key=null);let o=fi("value",t.value,r,i);if(o===Ae)return Ae;o===gt&&(t.value=null)}}return n}async function Xa(e,t){let r=Uf(t);re.isDocument(e)?await pi(null,e.contents,r,Object.freeze([e]))===gt&&(e.contents=null):await pi(null,e,r,Object.freeze([]))}Xa.BREAK=Ae;Xa.SKIP=Gf;Xa.REMOVE=gt;async function pi(e,t,r,i){let n=await Kf(e,t,r,i);if(re.isNode(n)||re.isPair(n))return Yf(e,i,n),pi(e,n,r,i);if(typeof n!="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await pi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Ae)return Ae;o===gt&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let a=await pi("key",t.key,r,i);if(a===Ae)return Ae;a===gt&&(t.key=null);let o=await pi("value",t.value,r,i);if(o===Ae)return Ae;o===gt&&(t.value=null)}}return n}function Uf(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 Kf(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(re.isMap(t))return r.Map?.(e,t,i);if(re.isSeq(t))return r.Seq?.(e,t,i);if(re.isPair(t))return r.Pair?.(e,t,i);if(re.isScalar(t))return r.Scalar?.(e,t,i);if(re.isAlias(t))return r.Alias?.(e,t,i)}function Yf(e,t,r){let i=t[t.length-1];if(re.isCollection(i))i.items[e]=r;else if(re.isPair(i))e==="key"?i.key=r:i.value=r;else if(re.isDocument(i))i.contents=r;else{let n=re.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Vc.visit=Ya;Vc.visitAsync=Xa});var Mc=x(Qf=>{"use strict";var Xf=O(),PN=an(),RN={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},AN=e=>e.replace(/[!,[\]{}]/g,t=>RN[t]),on=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 i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+AN(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Xf.isNode(t.contents)){let a={};PN.visit(t.contents,(o,s)=>{Xf.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};on.defaultYaml={explicit:!1,version:"1.2"};on.defaultTags={"!!":"tag:yaml.org,2002:"};Qf.Directives=on});var Qa=x(sn=>{"use strict";var Zf=O(),_N=an();function IN(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 ep(e){let t=new Set;return _N.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function tp(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function TN(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=ep(e));let o=tp(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Zf.isScalar(o.node)||Zf.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}sn.anchorIsValid=IN;sn.anchorNames=ep;sn.createNodeAnchors=TN;sn.findNewAnchor=tp});var Fc=x(rp=>{"use strict";function cn(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=cn(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=cn(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=cn(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=cn(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}rp.applyReviver=cn});var ir=x(np=>{"use strict";var jN=O();function ip(e,t,r){if(Array.isArray(e))return e.map((i,n)=>ip(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!jN.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}np.toJS=ip});var Za=x(op=>{"use strict";var $N=Fc(),ap=O(),ON=ir(),qc=class{constructor(t){Object.defineProperty(this,ap.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:i,onAnchor:n,reviver:a}={}){if(!ap.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=ON.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?$N.applyReviver(a,{"":s},"",s):s}};op.NodeBase=qc});var ln=x(sp=>{"use strict";var HN=Qa(),DN=an(),hi=O(),BN=Za(),LN=ir(),Wc=class extends BN.NodeBase{constructor(t){super(hi.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 i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],DN.visit(t,{Node:(a,o)=>{(hi.isAlias(o)||hi.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(LN.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=eo(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(HN.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function eo(e,t,r){if(hi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(hi.isCollection(t)){let i=0;for(let n of t.items){let a=eo(e,n,r);a>i&&(i=a)}return i}else if(hi.isPair(t)){let i=eo(e,t.key,r),n=eo(e,t.value,r);return Math.max(i,n)}return 1}sp.Alias=Wc});var Z=x(zc=>{"use strict";var VN=O(),MN=Za(),FN=ir(),qN=e=>!e||typeof e!="function"&&typeof e!="object",nr=class extends MN.NodeBase{constructor(t){super(VN.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:FN.toJS(this.value,t,r)}toString(){return String(this.value)}};nr.BLOCK_FOLDED="BLOCK_FOLDED";nr.BLOCK_LITERAL="BLOCK_LITERAL";nr.PLAIN="PLAIN";nr.QUOTE_DOUBLE="QUOTE_DOUBLE";nr.QUOTE_SINGLE="QUOTE_SINGLE";zc.Scalar=nr;zc.isScalarValue=qN});var un=x(lp=>{"use strict";var WN=ln(),jr=O(),cp=Z(),zN="tag:yaml.org,2002:";function JN(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function GN(e,t,r){if(jr.isDocument(e)&&(e=e.contents),jr.isNode(e))return e;if(jr.isPair(e)){let u=r.schema[jr.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new WN.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=zN+t.slice(2));let l=JN(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new cp.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[jr.MAP]:Symbol.iterator in Object(e)?o[jr.SEQ]:o[jr.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new cp.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}lp.createNode=GN});var ro=x(to=>{"use strict";var UN=un(),wt=O(),KN=Za();function Jc(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return UN.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var up=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Gc=class extends KN.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(i=>wt.isNode(i)||wt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(up(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(wt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Jc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(wt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&wt.isScalar(a)?a.value:a:wt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!wt.isPair(r))return!1;let i=r.value;return i==null||t&&wt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return wt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(wt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Jc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};to.Collection=Gc;to.collectionFromPath=Jc;to.isEmptyPath=up});var dn=x(io=>{"use strict";var YN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Uc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var XN=(e,t,r)=>e.endsWith(`
4
+ var hN=Object.create;var Dc=Object.defineProperty;var mN=Object.getOwnPropertyDescriptor;var vN=Object.getOwnPropertyNames;var gN=Object.getPrototypeOf,wN=Object.prototype.hasOwnProperty;var Ja=(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 C=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Ga=(e,t)=>{for(var r in t)Dc(e,r,{get:t[r],enumerable:!0})},yN=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vN(t))!wN.call(e,n)&&n!==r&&Dc(e,n,{get:()=>t[n],enumerable:!(i=mN(t,n))||i.enumerable});return e};var nn=(e,t,r)=>(r=e!=null?hN(gN(e)):{},yN(t||!e||!e.__esModule?Dc(r,"default",{value:e,enumerable:!0}):r,e));var O=x(fe=>{"use strict";var Bc=Symbol.for("yaml.alias"),qf=Symbol.for("yaml.document"),Ua=Symbol.for("yaml.map"),Wf=Symbol.for("yaml.pair"),Lc=Symbol.for("yaml.scalar"),Ka=Symbol.for("yaml.seq"),Vt=Symbol.for("yaml.node.type"),NN=e=>!!e&&typeof e=="object"&&e[Vt]===Bc,bN=e=>!!e&&typeof e=="object"&&e[Vt]===qf,kN=e=>!!e&&typeof e=="object"&&e[Vt]===Ua,SN=e=>!!e&&typeof e=="object"&&e[Vt]===Wf,zf=e=>!!e&&typeof e=="object"&&e[Vt]===Lc,EN=e=>!!e&&typeof e=="object"&&e[Vt]===Ka;function Jf(e){if(e&&typeof e=="object")switch(e[Vt]){case Ua:case Ka:return!0}return!1}function xN(e){if(e&&typeof e=="object")switch(e[Vt]){case Bc:case Ua:case Lc:case Ka:return!0}return!1}var CN=e=>(zf(e)||Jf(e))&&!!e.anchor;fe.ALIAS=Bc;fe.DOC=qf;fe.MAP=Ua;fe.NODE_TYPE=Vt;fe.PAIR=Wf;fe.SCALAR=Lc;fe.SEQ=Ka;fe.hasAnchor=CN;fe.isAlias=NN;fe.isCollection=Jf;fe.isDocument=bN;fe.isMap=kN;fe.isNode=xN;fe.isPair=SN;fe.isScalar=zf;fe.isSeq=EN});var an=x(Vc=>{"use strict";var re=O(),Ae=Symbol("break visit"),Gf=Symbol("skip children"),wt=Symbol("remove node");function Ya(e,t){let r=Uf(t);re.isDocument(e)?fi(null,e.contents,r,Object.freeze([e]))===wt&&(e.contents=null):fi(null,e,r,Object.freeze([]))}Ya.BREAK=Ae;Ya.SKIP=Gf;Ya.REMOVE=wt;function fi(e,t,r,i){let n=Kf(e,t,r,i);if(re.isNode(n)||re.isPair(n))return Yf(e,i,n),fi(e,n,r,i);if(typeof n!="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=fi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Ae)return Ae;o===wt&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let a=fi("key",t.key,r,i);if(a===Ae)return Ae;a===wt&&(t.key=null);let o=fi("value",t.value,r,i);if(o===Ae)return Ae;o===wt&&(t.value=null)}}return n}async function Xa(e,t){let r=Uf(t);re.isDocument(e)?await pi(null,e.contents,r,Object.freeze([e]))===wt&&(e.contents=null):await pi(null,e,r,Object.freeze([]))}Xa.BREAK=Ae;Xa.SKIP=Gf;Xa.REMOVE=wt;async function pi(e,t,r,i){let n=await Kf(e,t,r,i);if(re.isNode(n)||re.isPair(n))return Yf(e,i,n),pi(e,n,r,i);if(typeof n!="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await pi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Ae)return Ae;o===wt&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let a=await pi("key",t.key,r,i);if(a===Ae)return Ae;a===wt&&(t.key=null);let o=await pi("value",t.value,r,i);if(o===Ae)return Ae;o===wt&&(t.value=null)}}return n}function Uf(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 Kf(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(re.isMap(t))return r.Map?.(e,t,i);if(re.isSeq(t))return r.Seq?.(e,t,i);if(re.isPair(t))return r.Pair?.(e,t,i);if(re.isScalar(t))return r.Scalar?.(e,t,i);if(re.isAlias(t))return r.Alias?.(e,t,i)}function Yf(e,t,r){let i=t[t.length-1];if(re.isCollection(i))i.items[e]=r;else if(re.isPair(i))e==="key"?i.key=r:i.value=r;else if(re.isDocument(i))i.contents=r;else{let n=re.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Vc.visit=Ya;Vc.visitAsync=Xa});var Mc=x(Qf=>{"use strict";var Xf=O(),PN=an(),RN={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},AN=e=>e.replace(/[!,[\]{}]/g,t=>RN[t]),on=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 i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+AN(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Xf.isNode(t.contents)){let a={};PN.visit(t.contents,(o,s)=>{Xf.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};on.defaultYaml={explicit:!1,version:"1.2"};on.defaultTags={"!!":"tag:yaml.org,2002:"};Qf.Directives=on});var Qa=x(sn=>{"use strict";var Zf=O(),_N=an();function IN(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 ep(e){let t=new Set;return _N.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function tp(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function TN(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=ep(e));let o=tp(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Zf.isScalar(o.node)||Zf.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}sn.anchorIsValid=IN;sn.anchorNames=ep;sn.createNodeAnchors=TN;sn.findNewAnchor=tp});var Fc=x(rp=>{"use strict";function cn(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=cn(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=cn(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=cn(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=cn(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}rp.applyReviver=cn});var ir=x(np=>{"use strict";var jN=O();function ip(e,t,r){if(Array.isArray(e))return e.map((i,n)=>ip(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!jN.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}np.toJS=ip});var Za=x(op=>{"use strict";var $N=Fc(),ap=O(),ON=ir(),qc=class{constructor(t){Object.defineProperty(this,ap.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:i,onAnchor:n,reviver:a}={}){if(!ap.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=ON.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?$N.applyReviver(a,{"":s},"",s):s}};op.NodeBase=qc});var ln=x(sp=>{"use strict";var HN=Qa(),DN=an(),hi=O(),BN=Za(),LN=ir(),Wc=class extends BN.NodeBase{constructor(t){super(hi.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 i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],DN.visit(t,{Node:(a,o)=>{(hi.isAlias(o)||hi.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(LN.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=eo(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(HN.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function eo(e,t,r){if(hi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(hi.isCollection(t)){let i=0;for(let n of t.items){let a=eo(e,n,r);a>i&&(i=a)}return i}else if(hi.isPair(t)){let i=eo(e,t.key,r),n=eo(e,t.value,r);return Math.max(i,n)}return 1}sp.Alias=Wc});var ee=x(zc=>{"use strict";var VN=O(),MN=Za(),FN=ir(),qN=e=>!e||typeof e!="function"&&typeof e!="object",nr=class extends MN.NodeBase{constructor(t){super(VN.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:FN.toJS(this.value,t,r)}toString(){return String(this.value)}};nr.BLOCK_FOLDED="BLOCK_FOLDED";nr.BLOCK_LITERAL="BLOCK_LITERAL";nr.PLAIN="PLAIN";nr.QUOTE_DOUBLE="QUOTE_DOUBLE";nr.QUOTE_SINGLE="QUOTE_SINGLE";zc.Scalar=nr;zc.isScalarValue=qN});var un=x(lp=>{"use strict";var WN=ln(),jr=O(),cp=ee(),zN="tag:yaml.org,2002:";function JN(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function GN(e,t,r){if(jr.isDocument(e)&&(e=e.contents),jr.isNode(e))return e;if(jr.isPair(e)){let u=r.schema[jr.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new WN.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=zN+t.slice(2));let l=JN(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new cp.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[jr.MAP]:Symbol.iterator in Object(e)?o[jr.SEQ]:o[jr.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new cp.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}lp.createNode=GN});var ro=x(to=>{"use strict";var UN=un(),yt=O(),KN=Za();function Jc(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return UN.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var up=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Gc=class extends KN.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(i=>yt.isNode(i)||yt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(up(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(yt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Jc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(yt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&yt.isScalar(a)?a.value:a:yt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!yt.isPair(r))return!1;let i=r.value;return i==null||t&&yt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return yt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(yt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Jc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};to.Collection=Gc;to.collectionFromPath=Jc;to.isEmptyPath=up});var dn=x(io=>{"use strict";var YN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Uc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var XN=(e,t,r)=>e.endsWith(`
6
6
  `)?Uc(r,t):r.includes(`
7
7
  `)?`
8
8
  `+Uc(r,t):(e.endsWith(" ")?"":" ")+r;io.indentComment=Uc;io.lineComment=XN;io.stringifyComment=YN});var fp=x(fn=>{"use strict";var QN="flow",Kc="block",no="quoted";function ZN(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],f={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let d,h,v=!1,p=-1,m=-1,g=-1;r===Kc&&(p=dp(e,p,t.length),p!==-1&&(u=p+c));for(let y;y=e[p+=1];){if(r===no&&y==="\\"){switch(m=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(y===`
@@ -11,7 +11,7 @@ var hN=Object.create;var Dc=Object.defineProperty;var mN=Object.getOwnPropertyDe
11
11
  `&&N!==" "&&(d=p)}if(p>=u)if(d)l.push(d),u=d+c,d=void 0;else if(r===no){for(;h===" "||h===" ";)h=y,y=e[p+=1],v=!0;let N=p>g+1?p-2:m-1;if(f[N])return e;l.push(N),f[N]=!0,u=N+c,d=void 0}else v=!0}h=y}if(v&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let N=l[y],k=l[y+1]||e.length;N===0?w=`
12
12
  ${t}${e.slice(0,k)}`:(r===no&&f[N]&&(w+=`${e[N]}\\`),w+=`
13
13
  ${t}${e.slice(N+1,k)}`)}return w}function dp(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);i=t,n=t+1,a=e[n]}return i}fn.FOLD_BLOCK=Kc;fn.FOLD_FLOW=QN;fn.FOLD_QUOTED=no;fn.foldFlowLines=ZN});var hn=x(pp=>{"use strict";var et=Z(),ar=fp(),oo=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),so=e=>/^(%|---|\.\.\.)/m.test(e);function eb(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
14
+ `);i=t,n=t+1,a=e[n]}return i}fn.FOLD_BLOCK=Kc;fn.FOLD_FLOW=QN;fn.FOLD_QUOTED=no;fn.foldFlowLines=ZN});var hn=x(pp=>{"use strict";var tt=ee(),ar=fp(),oo=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),so=e=>/^(%|---|\.\.\.)/m.test(e);function eb(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
15
  `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function pn(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(so(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
16
16
 
17
17
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
@@ -20,41 +20,41 @@ ${t}${e.slice(N+1,k)}`)}return w}function dp(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
20
20
  ${r}`)+"'";return t.implicitKey?i:ar.foldFlowLines(i,r,ar.FOLD_FLOW,oo(t,!1))}function mi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=pn;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Yc:a&&!n?i=pn:i=r?Yc:pn}return i(e,t)}var Xc;try{Xc=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Xc=/\n+(?!\n|$)/g}function ao({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return mi(r,i);let l=i.indent||(i.forceBlockIndent||so(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===et.Scalar.BLOCK_FOLDED?!1:t===et.Scalar.BLOCK_LITERAL?!0:!eb(r,c,l.length);if(!r)return f?`|
23
+ |$)`,"g")}catch{Xc=/\n+(?!\n|$)/g}function ao({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return mi(r,i);let l=i.indent||(i.forceBlockIndent||so(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===tt.Scalar.BLOCK_FOLDED?!1:t===tt.Scalar.BLOCK_LITERAL?!0:!eb(r,c,l.length);if(!r)return f?`|
24
24
  `:`>
25
25
  `;let u,d;for(d=r.length;d>0;--d){let k=r[d-1];if(k!==`
26
26
  `&&k!==" "&&k!==" ")break}let h=r.substring(d),v=h.indexOf(`
27
27
  `);v===-1?u="-":r===h||v!==h.length-1?(u="+",a&&a()):u="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
28
28
  `&&(h=h.slice(0,-1)),h=h.replace(Xc,`$&${l}`));let p=!1,m,g=-1;for(m=0;m<r.length;++m){let k=r[m];if(k===" ")p=!0;else if(k===`
29
29
  `)g=m;else break}let w=r.substring(0,g<m?g+1:m);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let N=(p?l?"2":"1":"")+u;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let k=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,P=oo(i,!0);o!=="folded"&&t!==et.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{b=!0});let S=ar.foldFlowLines(`${w}${k}${h}`,l,ar.FOLD_BLOCK,P);if(!b)return`>${N}
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,P=oo(i,!0);o!=="folded"&&t!==tt.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{b=!0});let S=ar.foldFlowLines(`${w}${k}${h}`,l,ar.FOLD_BLOCK,P);if(!b)return`>${N}
31
31
  ${l}${S}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
32
32
  ${l}${w}${r}${h}`}function tb(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
33
  `)||f&&/[[\]{},]/.test(a))return mi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
- `)?mi(a,t):ao(e,t,r,i);if(!s&&!f&&n!==et.Scalar.PLAIN&&a.includes(`
34
+ `)?mi(a,t):ao(e,t,r,i);if(!s&&!f&&n!==tt.Scalar.PLAIN&&a.includes(`
35
35
  `))return ao(e,t,r,i);if(so(a)){if(c==="")return t.forceBlockIndent=!0,ao(e,t,r,i);if(s&&c===l)return mi(a,t)}let u=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:v}=t.doc.schema;if(v.some(d)||h?.some(d))return mi(a,t)}return s?u:ar.foldFlowLines(u,c,ar.FOLD_FLOW,oo(t,!1))}function rb(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==et.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=et.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case et.Scalar.BLOCK_FOLDED:case et.Scalar.BLOCK_LITERAL:return n||a?mi(o.value,t):ao(o,t,r,i);case et.Scalar.QUOTE_DOUBLE:return pn(o.value,t);case et.Scalar.QUOTE_SINGLE:return Yc(o.value,t);case et.Scalar.PLAIN:return tb(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}pp.stringifyString=rb});var mn=x(Qc=>{"use strict";var ib=Qa(),or=O(),nb=dn(),ab=hn();function ob(e,t){let r=Object.assign({blockQuote:!0,commentString:nb.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),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function sb(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(or.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function cb(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(or.isScalar(e)||or.isCollection(e))&&e.anchor;a&&ib.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function lb(e,t,r,i){if(or.isPair(e))return e.toString(t,r,i);if(or.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 n,a=or.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=sb(t.doc.schema.tags,a));let o=cb(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):or.isScalar(a)?ab.stringifyString(a,t,r,i):a.toString(t,r,i);return o?or.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Qc.createStringifyContext=ob;Qc.stringify=lb});var gp=x(vp=>{"use strict";var Vt=O(),hp=Z(),mp=mn(),vn=dn();function ub({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=r,d=Vt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Vt.isCollection(e)||!Vt.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let h=!u&&(!e||d&&t==null&&!r.inFlow||Vt.isCollection(e)||(Vt.isScalar(e)?e.type===hp.Scalar.BLOCK_FOLDED||e.type===hp.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(u||!a),indent:s+c});let v=!1,p=!1,m=mp.stringify(e,r,()=>v=!0,()=>p=!0);if(!h&&!r.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(a&&!u||t==null&&h)return m=`? ${m}`,d&&!v?m+=vn.lineComment(m,r.indent,l(d)):p&&n&&n(),m;v&&(d=null),h?(d&&(m+=vn.lineComment(m,r.indent,l(d))),m=`? ${m}
38
- ${s}:`):(m=`${m}:`,d&&(m+=vn.lineComment(m,r.indent,l(d))));let g,w,y;Vt.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,y=t.comment):(g=!1,w=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!h&&!d&&Vt.isScalar(t)&&(r.indentAtStart=m.length+1),p=!1,!f&&c.length>=2&&!r.inFlow&&!h&&Vt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,k=mp.stringify(t,r,()=>N=!0,()=>p=!0),b=" ";if(d||g||w){if(b=g?`
36
+ ${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:v}=t.doc.schema;if(v.some(d)||h?.some(d))return mi(a,t)}return s?u:ar.foldFlowLines(u,c,ar.FOLD_FLOW,oo(t,!1))}function rb(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==tt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=tt.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case tt.Scalar.BLOCK_FOLDED:case tt.Scalar.BLOCK_LITERAL:return n||a?mi(o.value,t):ao(o,t,r,i);case tt.Scalar.QUOTE_DOUBLE:return pn(o.value,t);case tt.Scalar.QUOTE_SINGLE:return Yc(o.value,t);case tt.Scalar.PLAIN:return tb(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}pp.stringifyString=rb});var mn=x(Qc=>{"use strict";var ib=Qa(),or=O(),nb=dn(),ab=hn();function ob(e,t){let r=Object.assign({blockQuote:!0,commentString:nb.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),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function sb(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(or.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function cb(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(or.isScalar(e)||or.isCollection(e))&&e.anchor;a&&ib.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function lb(e,t,r,i){if(or.isPair(e))return e.toString(t,r,i);if(or.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 n,a=or.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=sb(t.doc.schema.tags,a));let o=cb(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):or.isScalar(a)?ab.stringifyString(a,t,r,i):a.toString(t,r,i);return o?or.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Qc.createStringifyContext=ob;Qc.stringify=lb});var gp=x(vp=>{"use strict";var Mt=O(),hp=ee(),mp=mn(),vn=dn();function ub({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=r,d=Mt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Mt.isCollection(e)||!Mt.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let h=!u&&(!e||d&&t==null&&!r.inFlow||Mt.isCollection(e)||(Mt.isScalar(e)?e.type===hp.Scalar.BLOCK_FOLDED||e.type===hp.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(u||!a),indent:s+c});let v=!1,p=!1,m=mp.stringify(e,r,()=>v=!0,()=>p=!0);if(!h&&!r.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(a&&!u||t==null&&h)return m=`? ${m}`,d&&!v?m+=vn.lineComment(m,r.indent,l(d)):p&&n&&n(),m;v&&(d=null),h?(d&&(m+=vn.lineComment(m,r.indent,l(d))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,d&&(m+=vn.lineComment(m,r.indent,l(d))));let g,w,y;Mt.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,y=t.comment):(g=!1,w=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!h&&!d&&Mt.isScalar(t)&&(r.indentAtStart=m.length+1),p=!1,!f&&c.length>=2&&!r.inFlow&&!h&&Mt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,k=mp.stringify(t,r,()=>N=!0,()=>p=!0),b=" ";if(d||g||w){if(b=g?`
39
39
  `:"",w){let P=l(w);b+=`
40
40
  ${vn.indentComment(P,r.indent)}`}k===""&&!r.inFlow?b===`
41
41
  `&&y&&(b=`
42
42
 
43
43
  `):b+=`
44
- ${r.indent}`}else if(!h&&Vt.isCollection(t)){let P=k[0],S=k.indexOf(`
44
+ ${r.indent}`}else if(!h&&Mt.isCollection(t)){let P=k[0],S=k.indexOf(`
45
45
  `),E=S!==-1,A=r.inFlow??t.flow??t.items.length===0;if(E||!A){let M=!1;if(E&&(P==="&"||P==="!")){let $=k.indexOf(" ");P==="&"&&$!==-1&&$<S&&k[$+1]==="!"&&($=k.indexOf(" ",$+1)),($===-1||S<$)&&(M=!0)}M||(b=`
46
46
  ${r.indent}`)}}else(k===""||k[0]===`
47
- `)&&(b="");return m+=b+k,r.inFlow?N&&i&&i():y&&!N?m+=vn.lineComment(m,r.indent,l(y)):p&&n&&n(),m}vp.stringifyPair=ub});var el=x(Zc=>{"use strict";var wp=Ja("process");function db(e,...t){e==="debug"&&console.log(...t)}function fb(e,t){(e==="debug"||e==="warn")&&(typeof wp.emitWarning=="function"?wp.emitWarning(t):console.warn(t))}Zc.debug=db;Zc.warn=fb});var po=x(fo=>{"use strict";var uo=O(),yp=Z(),co="<<",lo={identify:e=>e===co||typeof e=="symbol"&&e.description===co,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new yp.Scalar(Symbol(co)),{addToJSMap:Np}),stringify:()=>co},pb=(e,t)=>(lo.identify(t)||uo.isScalar(t)&&(!t.type||t.type===yp.Scalar.PLAIN)&&lo.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===lo.tag&&r.default);function Np(e,t,r){let i=bp(e,r);if(uo.isSeq(i))for(let n of i.items)tl(e,t,n);else if(Array.isArray(i))for(let n of i)tl(e,t,n);else tl(e,t,i)}function tl(e,t,r){let i=bp(e,r);if(!uo.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function bp(e,t){return e&&uo.isAlias(t)?t.resolve(e.doc,e):t}fo.addMergeToJSMap=Np;fo.isMergeKey=pb;fo.merge=lo});var il=x(Ep=>{"use strict";var hb=el(),kp=po(),mb=mn(),Sp=O(),rl=ir();function vb(e,t,{key:r,value:i}){if(Sp.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(kp.isMergeKey(e,r))kp.addMergeToJSMap(e,t,i);else{let n=rl.toJS(r,"",e);if(t instanceof Map)t.set(n,rl.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=gb(r,n,e),o=rl.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function gb(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Sp.isNode(e)&&r?.doc){let i=mb.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),hb.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Ep.addPairToJSMap=vb});var sr=x(nl=>{"use strict";var xp=un(),wb=gp(),yb=il(),ho=O();function Nb(e,t,r){let i=xp.createNode(e,void 0,r),n=xp.createNode(t,void 0,r);return new mo(i,n)}var mo=class e{constructor(t,r=null){Object.defineProperty(this,ho.NODE_TYPE,{value:ho.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return ho.isNode(r)&&(r=r.clone(t)),ho.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return yb.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?wb.stringifyPair(this,t,r,i):JSON.stringify(this)}};nl.Pair=mo;nl.createPair=Nb});var al=x(Pp=>{"use strict";var $r=O(),Cp=mn(),vo=dn();function bb(e,t,r){return(t.inFlow??e.flow?Sb:kb)(e,t,r)}function kb({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if($r.isNode(p))!u&&p.spaceBefore&&d.push(""),go(r,d,p.commentBefore,u),p.comment&&(m=p.comment);else if($r.isPair(p)){let w=$r.isNode(p.key)?p.key:null;w&&(!u&&w.spaceBefore&&d.push(""),go(r,d,w.commentBefore,u))}u=!1;let g=Cp.stringify(p,f,()=>m=null,()=>u=!0);m&&(g+=vo.lineComment(g,a,l(m))),u&&m&&(u=!1),d.push(i+g)}let h;if(d.length===0)h=n.start+n.end;else{h=d[0];for(let v=1;v<d.length;++v){let p=d[v];h+=p?`
47
+ `)&&(b="");return m+=b+k,r.inFlow?N&&i&&i():y&&!N?m+=vn.lineComment(m,r.indent,l(y)):p&&n&&n(),m}vp.stringifyPair=ub});var el=x(Zc=>{"use strict";var wp=Ja("process");function db(e,...t){e==="debug"&&console.log(...t)}function fb(e,t){(e==="debug"||e==="warn")&&(typeof wp.emitWarning=="function"?wp.emitWarning(t):console.warn(t))}Zc.debug=db;Zc.warn=fb});var po=x(fo=>{"use strict";var uo=O(),yp=ee(),co="<<",lo={identify:e=>e===co||typeof e=="symbol"&&e.description===co,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new yp.Scalar(Symbol(co)),{addToJSMap:Np}),stringify:()=>co},pb=(e,t)=>(lo.identify(t)||uo.isScalar(t)&&(!t.type||t.type===yp.Scalar.PLAIN)&&lo.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===lo.tag&&r.default);function Np(e,t,r){let i=bp(e,r);if(uo.isSeq(i))for(let n of i.items)tl(e,t,n);else if(Array.isArray(i))for(let n of i)tl(e,t,n);else tl(e,t,i)}function tl(e,t,r){let i=bp(e,r);if(!uo.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function bp(e,t){return e&&uo.isAlias(t)?t.resolve(e.doc,e):t}fo.addMergeToJSMap=Np;fo.isMergeKey=pb;fo.merge=lo});var il=x(Ep=>{"use strict";var hb=el(),kp=po(),mb=mn(),Sp=O(),rl=ir();function vb(e,t,{key:r,value:i}){if(Sp.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(kp.isMergeKey(e,r))kp.addMergeToJSMap(e,t,i);else{let n=rl.toJS(r,"",e);if(t instanceof Map)t.set(n,rl.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=gb(r,n,e),o=rl.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function gb(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Sp.isNode(e)&&r?.doc){let i=mb.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),hb.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Ep.addPairToJSMap=vb});var sr=x(nl=>{"use strict";var xp=un(),wb=gp(),yb=il(),ho=O();function Nb(e,t,r){let i=xp.createNode(e,void 0,r),n=xp.createNode(t,void 0,r);return new mo(i,n)}var mo=class e{constructor(t,r=null){Object.defineProperty(this,ho.NODE_TYPE,{value:ho.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return ho.isNode(r)&&(r=r.clone(t)),ho.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return yb.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?wb.stringifyPair(this,t,r,i):JSON.stringify(this)}};nl.Pair=mo;nl.createPair=Nb});var al=x(Pp=>{"use strict";var $r=O(),Cp=mn(),vo=dn();function bb(e,t,r){return(t.inFlow??e.flow?Sb:kb)(e,t,r)}function kb({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if($r.isNode(p))!u&&p.spaceBefore&&d.push(""),go(r,d,p.commentBefore,u),p.comment&&(m=p.comment);else if($r.isPair(p)){let w=$r.isNode(p.key)?p.key:null;w&&(!u&&w.spaceBefore&&d.push(""),go(r,d,w.commentBefore,u))}u=!1;let g=Cp.stringify(p,f,()=>m=null,()=>u=!0);m&&(g+=vo.lineComment(g,a,l(m))),u&&m&&(u=!1),d.push(i+g)}let h;if(d.length===0)h=n.start+n.end;else{h=d[0];for(let v=1;v<d.length;++v){let p=d[v];h+=p?`
48
48
  ${c}${p}`:`
49
49
  `}}return e?(h+=`
50
50
  `+vo.indentComment(l(e),c),s&&s()):u&&o&&o(),h}function Sb({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let v=0;v<e.length;++v){let p=e[v],m=null;if($r.isNode(p))p.spaceBefore&&u.push(""),go(t,u,p.commentBefore,!1),p.comment&&(m=p.comment);else if($r.isPair(p)){let w=$r.isNode(p.key)?p.key:null;w&&(w.spaceBefore&&u.push(""),go(t,u,w.commentBefore,!1),w.comment&&(l=!0));let y=$r.isNode(p.value)?p.value:null;y?(y.comment&&(m=y.comment),y.commentBefore&&(l=!0)):p.value==null&&w?.comment&&(m=w.comment)}m&&(l=!0);let g=Cp.stringify(p,c,()=>m=null);l||(l=u.length>f||g.includes(`
51
51
  `)),v<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((w,y)=>w+y.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),m&&(g+=vo.lineComment(g,i,s(m))),u.push(g),f=u.length}let{start:d,end:h}=r;if(u.length===0)return d+h;if(!l){let v=u.reduce((p,m)=>p+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=d;for(let p of u)v+=p?`
52
52
  ${a}${n}${p}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function go({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=vo.indentComment(t(i),e);r.push(a.trimStart())}}Pp.stringifyCollection=bb});var lr=x(sl=>{"use strict";var Eb=al(),xb=il(),Cb=ro(),cr=O(),wo=sr(),Pb=Z();function gn(e,t){let r=cr.isScalar(t)?t.value:t;for(let i of e)if(cr.isPair(i)&&(i.key===t||i.key===r||cr.isScalar(i.key)&&i.key.value===r))return i}var ol=class extends Cb.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(cr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(wo.createPair(c,l,i))};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"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;cr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new wo.Pair(t,t?.value):i=new wo.Pair(t.key,t.value);let n=gn(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);cr.isScalar(n.value)&&Pb.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=gn(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=gn(this.items,t)?.value;return(!r&&cr.isScalar(n)?n.value:n)??void 0}has(t){return!!gn(this.items,t)}set(t,r){this.add(new wo.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)xb.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!cr.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Eb.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};sl.YAMLMap=ol;sl.findPair=gn});var vi=x(Ap=>{"use strict";var Rb=O(),Rp=lr(),Ab={collection:"map",default:!0,nodeClass:Rp.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Rb.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Rp.YAMLMap.from(e,t,r)};Ap.map=Ab});var ur=x(_p=>{"use strict";var _b=un(),Ib=al(),Tb=ro(),No=O(),jb=Z(),$b=ir(),cl=class extends Tb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(No.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=yo(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=yo(t);if(typeof i!="number")return;let n=this.items[i];return!r&&No.isScalar(n)?n.value:n}has(t){let r=yo(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=yo(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];No.isScalar(n)&&jb.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push($b.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Ib.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(_b.createNode(s,void 0,i))}}return a}};function yo(e){let t=No.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}_p.YAMLSeq=cl});var gi=x(Tp=>{"use strict";var Ob=O(),Ip=ur(),Hb={collection:"seq",default:!0,nodeClass:Ip.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Ob.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Ip.YAMLSeq.from(e,t,r)};Tp.seq=Hb});var wn=x(jp=>{"use strict";var Db=hn(),Bb={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),Db.stringifyString(e,t,r,i)}};jp.string=Bb});var bo=x(Hp=>{"use strict";var $p=Z(),Op={identify:e=>e==null,createNode:()=>new $p.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new $p.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Op.test.test(e)?e:t.options.nullStr};Hp.nullTag=Op});var ll=x(Bp=>{"use strict";var Lb=Z(),Dp={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Lb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Dp.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Bp.boolTag=Dp});var wi=x(Lp=>{"use strict";function Vb({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Lp.stringifyNumber=Vb});var dl=x(ko=>{"use strict";var Mb=Z(),ul=wi(),Fb={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:ul.stringifyNumber},qb={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():ul.stringifyNumber(e)}},Wb={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 Mb.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:ul.stringifyNumber};ko.float=Wb;ko.floatExp=qb;ko.floatNaN=Fb});var pl=x(Eo=>{"use strict";var Vp=wi(),So=e=>typeof e=="bigint"||Number.isInteger(e),fl=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Mp(e,t,r){let{value:i}=e;return So(i)&&i>=0?r+i.toString(t):Vp.stringifyNumber(e)}var zb={identify:e=>So(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>fl(e,2,8,r),stringify:e=>Mp(e,8,"0o")},Jb={identify:So,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>fl(e,0,10,r),stringify:Vp.stringifyNumber},Gb={identify:e=>So(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>fl(e,2,16,r),stringify:e=>Mp(e,16,"0x")};Eo.int=Jb;Eo.intHex=Gb;Eo.intOct=zb});var qp=x(Fp=>{"use strict";var Ub=vi(),Kb=bo(),Yb=gi(),Xb=wn(),Qb=ll(),hl=dl(),ml=pl(),Zb=[Ub.map,Yb.seq,Xb.string,Kb.nullTag,Qb.boolTag,ml.intOct,ml.int,ml.intHex,hl.floatNaN,hl.floatExp,hl.float];Fp.schema=Zb});var Jp=x(zp=>{"use strict";var ek=Z(),tk=vi(),rk=gi();function Wp(e){return typeof e=="bigint"||Number.isInteger(e)}var xo=({value:e})=>JSON.stringify(e),ik=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:xo},{identify:e=>e==null,createNode:()=>new ek.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:xo},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:xo},{identify:Wp,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})=>Wp(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:xo}],nk={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ak=[tk.map,rk.seq].concat(ik,nk);zp.schema=ak});var gl=x(Gp=>{"use strict";var yn=Ja("buffer"),vl=Z(),ok=hn(),sk={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof yn.Buffer=="function")return yn.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}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},i,n,a){if(!r)return"";let o=r,s;if(typeof yn.Buffer=="function")s=o instanceof yn.Buffer?o.toString("base64"):yn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[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=vl.Scalar.BLOCK_LITERAL),t!==vl.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(t===vl.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return ok.stringifyString({comment:e,type:t,value:s},i,n,a)}};Gp.binary=sk});var Ro=x(Po=>{"use strict";var Co=O(),wl=sr(),ck=Z(),lk=ur();function Up(e,t){if(Co.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Co.isPair(i)){if(Co.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new wl.Pair(new ck.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
54
+ ${n}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function go({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=vo.indentComment(t(i),e);r.push(a.trimStart())}}Pp.stringifyCollection=bb});var lr=x(sl=>{"use strict";var Eb=al(),xb=il(),Cb=ro(),cr=O(),wo=sr(),Pb=ee();function gn(e,t){let r=cr.isScalar(t)?t.value:t;for(let i of e)if(cr.isPair(i)&&(i.key===t||i.key===r||cr.isScalar(i.key)&&i.key.value===r))return i}var ol=class extends Cb.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(cr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(wo.createPair(c,l,i))};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"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;cr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new wo.Pair(t,t?.value):i=new wo.Pair(t.key,t.value);let n=gn(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);cr.isScalar(n.value)&&Pb.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=gn(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=gn(this.items,t)?.value;return(!r&&cr.isScalar(n)?n.value:n)??void 0}has(t){return!!gn(this.items,t)}set(t,r){this.add(new wo.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)xb.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!cr.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Eb.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};sl.YAMLMap=ol;sl.findPair=gn});var vi=x(Ap=>{"use strict";var Rb=O(),Rp=lr(),Ab={collection:"map",default:!0,nodeClass:Rp.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Rb.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Rp.YAMLMap.from(e,t,r)};Ap.map=Ab});var ur=x(_p=>{"use strict";var _b=un(),Ib=al(),Tb=ro(),No=O(),jb=ee(),$b=ir(),cl=class extends Tb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(No.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=yo(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=yo(t);if(typeof i!="number")return;let n=this.items[i];return!r&&No.isScalar(n)?n.value:n}has(t){let r=yo(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=yo(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];No.isScalar(n)&&jb.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push($b.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Ib.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(_b.createNode(s,void 0,i))}}return a}};function yo(e){let t=No.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}_p.YAMLSeq=cl});var gi=x(Tp=>{"use strict";var Ob=O(),Ip=ur(),Hb={collection:"seq",default:!0,nodeClass:Ip.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Ob.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Ip.YAMLSeq.from(e,t,r)};Tp.seq=Hb});var wn=x(jp=>{"use strict";var Db=hn(),Bb={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),Db.stringifyString(e,t,r,i)}};jp.string=Bb});var bo=x(Hp=>{"use strict";var $p=ee(),Op={identify:e=>e==null,createNode:()=>new $p.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new $p.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Op.test.test(e)?e:t.options.nullStr};Hp.nullTag=Op});var ll=x(Bp=>{"use strict";var Lb=ee(),Dp={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Lb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Dp.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Bp.boolTag=Dp});var wi=x(Lp=>{"use strict";function Vb({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Lp.stringifyNumber=Vb});var dl=x(ko=>{"use strict";var Mb=ee(),ul=wi(),Fb={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:ul.stringifyNumber},qb={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():ul.stringifyNumber(e)}},Wb={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 Mb.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:ul.stringifyNumber};ko.float=Wb;ko.floatExp=qb;ko.floatNaN=Fb});var pl=x(Eo=>{"use strict";var Vp=wi(),So=e=>typeof e=="bigint"||Number.isInteger(e),fl=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Mp(e,t,r){let{value:i}=e;return So(i)&&i>=0?r+i.toString(t):Vp.stringifyNumber(e)}var zb={identify:e=>So(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>fl(e,2,8,r),stringify:e=>Mp(e,8,"0o")},Jb={identify:So,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>fl(e,0,10,r),stringify:Vp.stringifyNumber},Gb={identify:e=>So(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>fl(e,2,16,r),stringify:e=>Mp(e,16,"0x")};Eo.int=Jb;Eo.intHex=Gb;Eo.intOct=zb});var qp=x(Fp=>{"use strict";var Ub=vi(),Kb=bo(),Yb=gi(),Xb=wn(),Qb=ll(),hl=dl(),ml=pl(),Zb=[Ub.map,Yb.seq,Xb.string,Kb.nullTag,Qb.boolTag,ml.intOct,ml.int,ml.intHex,hl.floatNaN,hl.floatExp,hl.float];Fp.schema=Zb});var Jp=x(zp=>{"use strict";var ek=ee(),tk=vi(),rk=gi();function Wp(e){return typeof e=="bigint"||Number.isInteger(e)}var xo=({value:e})=>JSON.stringify(e),ik=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:xo},{identify:e=>e==null,createNode:()=>new ek.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:xo},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:xo},{identify:Wp,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})=>Wp(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:xo}],nk={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ak=[tk.map,rk.seq].concat(ik,nk);zp.schema=ak});var gl=x(Gp=>{"use strict";var yn=Ja("buffer"),vl=ee(),ok=hn(),sk={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof yn.Buffer=="function")return yn.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}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},i,n,a){if(!r)return"";let o=r,s;if(typeof yn.Buffer=="function")s=o instanceof yn.Buffer?o.toString("base64"):yn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[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=vl.Scalar.BLOCK_LITERAL),t!==vl.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(t===vl.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return ok.stringifyString({comment:e,type:t,value:s},i,n,a)}};Gp.binary=sk});var Ro=x(Po=>{"use strict";var Co=O(),wl=sr(),ck=ee(),lk=ur();function Up(e,t){if(Co.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Co.isPair(i)){if(Co.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new wl.Pair(new ck.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
56
56
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
57
- ${a.comment}`:i.comment}i=n}e.items[r]=Co.isPair(i)?i:new wl.Pair(i)}}else t("Expected a sequence for this tag");return e}function Kp(e,t,r){let{replacer:i}=r,n=new lk.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(wl.createPair(s,c,r))}return n}var uk={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Up,createNode:Kp};Po.createPairs=Kp;Po.pairs=uk;Po.resolvePairs=Up});var bl=x(Nl=>{"use strict";var Yp=O(),yl=ir(),Nn=lr(),dk=ur(),Xp=Ro(),Or=class e extends dk.YAMLSeq{constructor(){super(),this.add=Nn.YAMLMap.prototype.add.bind(this),this.delete=Nn.YAMLMap.prototype.delete.bind(this),this.get=Nn.YAMLMap.prototype.get.bind(this),this.has=Nn.YAMLMap.prototype.has.bind(this),this.set=Nn.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Yp.isPair(n)?(a=yl.toJS(n.key,"",r),o=yl.toJS(n.value,a,r)):a=yl.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Xp.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Or.tag="tag:yaml.org,2002:omap";var fk={collection:"seq",identify:e=>e instanceof Map,nodeClass:Or,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Xp.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Yp.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Or,r)},createNode:(e,t,r)=>Or.from(e,t,r)};Nl.YAMLOMap=Or;Nl.omap=fk});var rh=x(kl=>{"use strict";var Qp=Z();function Zp({value:e,source:t},r){return t&&(e?eh:th).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var eh={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 Qp.Scalar(!0),stringify:Zp},th={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 Qp.Scalar(!1),stringify:Zp};kl.falseTag=th;kl.trueTag=eh});var ih=x(Ao=>{"use strict";var pk=Z(),Sl=wi(),hk={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:Sl.stringifyNumber},mk={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():Sl.stringifyNumber(e)}},vk={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 pk.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Sl.stringifyNumber};Ao.float=vk;Ao.floatExp=mk;Ao.floatNaN=hk});var ah=x(kn=>{"use strict";var nh=wi(),bn=e=>typeof e=="bigint"||Number.isInteger(e);function _o(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function El(e,t,r){let{value:i}=e;if(bn(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return nh.stringifyNumber(e)}var gk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>_o(e,2,2,r),stringify:e=>El(e,2,"0b")},wk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>_o(e,1,8,r),stringify:e=>El(e,8,"0")},yk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>_o(e,0,10,r),stringify:nh.stringifyNumber},Nk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>_o(e,2,16,r),stringify:e=>El(e,16,"0x")};kn.int=yk;kn.intBin=gk;kn.intHex=Nk;kn.intOct=wk});var Cl=x(xl=>{"use strict";var jo=O(),Io=sr(),To=lr(),Hr=class e extends To.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;jo.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Io.Pair(t.key,null):r=new Io.Pair(t,null),To.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=To.findPair(this.items,t);return!r&&jo.isPair(i)?jo.isScalar(i.key)?i.key.value:i.key:i}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 i=To.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Io.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Io.createPair(o,null,i));return a}};Hr.tag="tag:yaml.org,2002:set";var bk={collection:"map",identify:e=>e instanceof Set,nodeClass:Hr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Hr.from(e,t,r),resolve(e,t){if(jo.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Hr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};xl.YAMLSet=Hr;xl.set=bk});var Rl=x($o=>{"use strict";var kk=wi();function Pl(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function oh(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return kk.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Sk={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})=>Pl(e,r),stringify:oh},Ek={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=>Pl(e,!1),stringify:oh},sh={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(sh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=Pl(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};$o.floatTime=Ek;$o.intTime=Sk;$o.timestamp=sh});var uh=x(lh=>{"use strict";var xk=vi(),Ck=bo(),Pk=gi(),Rk=wn(),Ak=gl(),ch=rh(),Al=ih(),Oo=ah(),_k=po(),Ik=bl(),Tk=Ro(),jk=Cl(),_l=Rl(),$k=[xk.map,Pk.seq,Rk.string,Ck.nullTag,ch.trueTag,ch.falseTag,Oo.intBin,Oo.intOct,Oo.int,Oo.intHex,Al.floatNaN,Al.floatExp,Al.float,Ak.binary,_k.merge,Ik.omap,Tk.pairs,jk.set,_l.intTime,_l.floatTime,_l.timestamp];lh.schema=$k});var Nh=x(jl=>{"use strict";var hh=vi(),Ok=bo(),mh=gi(),Hk=wn(),Dk=ll(),Il=dl(),Tl=pl(),Bk=qp(),Lk=Jp(),vh=gl(),Sn=po(),gh=bl(),wh=Ro(),dh=uh(),yh=Cl(),Ho=Rl(),fh=new Map([["core",Bk.schema],["failsafe",[hh.map,mh.seq,Hk.string]],["json",Lk.schema],["yaml11",dh.schema],["yaml-1.1",dh.schema]]),ph={binary:vh.binary,bool:Dk.boolTag,float:Il.float,floatExp:Il.floatExp,floatNaN:Il.floatNaN,floatTime:Ho.floatTime,int:Tl.int,intHex:Tl.intHex,intOct:Tl.intOct,intTime:Ho.intTime,map:hh.map,merge:Sn.merge,null:Ok.nullTag,omap:gh.omap,pairs:wh.pairs,seq:mh.seq,set:yh.set,timestamp:Ho.timestamp},Vk={"tag:yaml.org,2002:binary":vh.binary,"tag:yaml.org,2002:merge":Sn.merge,"tag:yaml.org,2002:omap":gh.omap,"tag:yaml.org,2002:pairs":wh.pairs,"tag:yaml.org,2002:set":yh.set,"tag:yaml.org,2002:timestamp":Ho.timestamp};function Mk(e,t,r){let i=fh.get(t);if(i&&!e)return r&&!i.includes(Sn.merge)?i.concat(Sn.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(fh.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(Sn.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?ph[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(ph).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}jl.coreKnownTags=Vk;jl.getTags=Mk});var Hl=x(bh=>{"use strict";var $l=O(),Fk=vi(),qk=gi(),Wk=wn(),Do=Nh(),zk=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Ol=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Do.getTags(t,"compat"):t?Do.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Do.coreKnownTags:{},this.tags=Do.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,$l.MAP,{value:Fk.map}),Object.defineProperty(this,$l.SCALAR,{value:Wk.string}),Object.defineProperty(this,$l.SEQ,{value:qk.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?zk:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};bh.Schema=Ol});var Sh=x(kh=>{"use strict";var Jk=O(),Dl=mn(),En=dn();function Gk(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Dl.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(En.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Jk.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(En.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Dl.stringify(e.contents,n,()=>s=null,c);s&&(l+=En.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Dl.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
57
+ ${a.comment}`:i.comment}i=n}e.items[r]=Co.isPair(i)?i:new wl.Pair(i)}}else t("Expected a sequence for this tag");return e}function Kp(e,t,r){let{replacer:i}=r,n=new lk.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(wl.createPair(s,c,r))}return n}var uk={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Up,createNode:Kp};Po.createPairs=Kp;Po.pairs=uk;Po.resolvePairs=Up});var bl=x(Nl=>{"use strict";var Yp=O(),yl=ir(),Nn=lr(),dk=ur(),Xp=Ro(),Or=class e extends dk.YAMLSeq{constructor(){super(),this.add=Nn.YAMLMap.prototype.add.bind(this),this.delete=Nn.YAMLMap.prototype.delete.bind(this),this.get=Nn.YAMLMap.prototype.get.bind(this),this.has=Nn.YAMLMap.prototype.has.bind(this),this.set=Nn.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Yp.isPair(n)?(a=yl.toJS(n.key,"",r),o=yl.toJS(n.value,a,r)):a=yl.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Xp.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Or.tag="tag:yaml.org,2002:omap";var fk={collection:"seq",identify:e=>e instanceof Map,nodeClass:Or,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Xp.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Yp.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Or,r)},createNode:(e,t,r)=>Or.from(e,t,r)};Nl.YAMLOMap=Or;Nl.omap=fk});var rh=x(kl=>{"use strict";var Qp=ee();function Zp({value:e,source:t},r){return t&&(e?eh:th).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var eh={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 Qp.Scalar(!0),stringify:Zp},th={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 Qp.Scalar(!1),stringify:Zp};kl.falseTag=th;kl.trueTag=eh});var ih=x(Ao=>{"use strict";var pk=ee(),Sl=wi(),hk={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:Sl.stringifyNumber},mk={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():Sl.stringifyNumber(e)}},vk={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 pk.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Sl.stringifyNumber};Ao.float=vk;Ao.floatExp=mk;Ao.floatNaN=hk});var ah=x(kn=>{"use strict";var nh=wi(),bn=e=>typeof e=="bigint"||Number.isInteger(e);function _o(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function El(e,t,r){let{value:i}=e;if(bn(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return nh.stringifyNumber(e)}var gk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>_o(e,2,2,r),stringify:e=>El(e,2,"0b")},wk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>_o(e,1,8,r),stringify:e=>El(e,8,"0")},yk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>_o(e,0,10,r),stringify:nh.stringifyNumber},Nk={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>_o(e,2,16,r),stringify:e=>El(e,16,"0x")};kn.int=yk;kn.intBin=gk;kn.intHex=Nk;kn.intOct=wk});var Cl=x(xl=>{"use strict";var jo=O(),Io=sr(),To=lr(),Hr=class e extends To.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;jo.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Io.Pair(t.key,null):r=new Io.Pair(t,null),To.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=To.findPair(this.items,t);return!r&&jo.isPair(i)?jo.isScalar(i.key)?i.key.value:i.key:i}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 i=To.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Io.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Io.createPair(o,null,i));return a}};Hr.tag="tag:yaml.org,2002:set";var bk={collection:"map",identify:e=>e instanceof Set,nodeClass:Hr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Hr.from(e,t,r),resolve(e,t){if(jo.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Hr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};xl.YAMLSet=Hr;xl.set=bk});var Rl=x($o=>{"use strict";var kk=wi();function Pl(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function oh(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return kk.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Sk={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})=>Pl(e,r),stringify:oh},Ek={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=>Pl(e,!1),stringify:oh},sh={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(sh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=Pl(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};$o.floatTime=Ek;$o.intTime=Sk;$o.timestamp=sh});var uh=x(lh=>{"use strict";var xk=vi(),Ck=bo(),Pk=gi(),Rk=wn(),Ak=gl(),ch=rh(),Al=ih(),Oo=ah(),_k=po(),Ik=bl(),Tk=Ro(),jk=Cl(),_l=Rl(),$k=[xk.map,Pk.seq,Rk.string,Ck.nullTag,ch.trueTag,ch.falseTag,Oo.intBin,Oo.intOct,Oo.int,Oo.intHex,Al.floatNaN,Al.floatExp,Al.float,Ak.binary,_k.merge,Ik.omap,Tk.pairs,jk.set,_l.intTime,_l.floatTime,_l.timestamp];lh.schema=$k});var Nh=x(jl=>{"use strict";var hh=vi(),Ok=bo(),mh=gi(),Hk=wn(),Dk=ll(),Il=dl(),Tl=pl(),Bk=qp(),Lk=Jp(),vh=gl(),Sn=po(),gh=bl(),wh=Ro(),dh=uh(),yh=Cl(),Ho=Rl(),fh=new Map([["core",Bk.schema],["failsafe",[hh.map,mh.seq,Hk.string]],["json",Lk.schema],["yaml11",dh.schema],["yaml-1.1",dh.schema]]),ph={binary:vh.binary,bool:Dk.boolTag,float:Il.float,floatExp:Il.floatExp,floatNaN:Il.floatNaN,floatTime:Ho.floatTime,int:Tl.int,intHex:Tl.intHex,intOct:Tl.intOct,intTime:Ho.intTime,map:hh.map,merge:Sn.merge,null:Ok.nullTag,omap:gh.omap,pairs:wh.pairs,seq:mh.seq,set:yh.set,timestamp:Ho.timestamp},Vk={"tag:yaml.org,2002:binary":vh.binary,"tag:yaml.org,2002:merge":Sn.merge,"tag:yaml.org,2002:omap":gh.omap,"tag:yaml.org,2002:pairs":wh.pairs,"tag:yaml.org,2002:set":yh.set,"tag:yaml.org,2002:timestamp":Ho.timestamp};function Mk(e,t,r){let i=fh.get(t);if(i&&!e)return r&&!i.includes(Sn.merge)?i.concat(Sn.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(fh.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(Sn.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?ph[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(ph).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}jl.coreKnownTags=Vk;jl.getTags=Mk});var Hl=x(bh=>{"use strict";var $l=O(),Fk=vi(),qk=gi(),Wk=wn(),Do=Nh(),zk=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Ol=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Do.getTags(t,"compat"):t?Do.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Do.coreKnownTags:{},this.tags=Do.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,$l.MAP,{value:Fk.map}),Object.defineProperty(this,$l.SCALAR,{value:Wk.string}),Object.defineProperty(this,$l.SEQ,{value:qk.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?zk:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};bh.Schema=Ol});var Sh=x(kh=>{"use strict";var Jk=O(),Dl=mn(),En=dn();function Gk(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Dl.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(En.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Jk.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(En.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Dl.stringify(e.contents,n,()=>s=null,c);s&&(l+=En.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Dl.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
58
  `)?(r.push("..."),r.push(En.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(En.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
60
  `}kh.stringifyDocument=Gk});var xn=x(Eh=>{"use strict";var Uk=ln(),yi=ro(),We=O(),Kk=sr(),Yk=ir(),Xk=Hl(),Qk=Sh(),Bl=Qa(),Zk=Fc(),eS=un(),Ll=Mc(),Vl=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,We.NODE_TYPE,{value:We.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ll.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[We.NODE_TYPE]:{value:We.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=We.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ni(this.contents)&&this.contents.add(t)}addIn(t,r){Ni(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Bl.anchorNames(this);t.anchor=!r||i.has(r)?Bl.findNewAnchor(r||"a",i):r}return new Uk.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let m=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=r.filter(m).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:h}=Bl.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=eS.createNode(t,f,v);return s&&We.isCollection(p)&&(p.flow=!0),d(),p}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Kk.Pair(n,a)}delete(t){return Ni(this.contents)?this.contents.delete(t):!1}deleteIn(t){return yi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ni(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return We.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return yi.isEmptyPath(t)?!r&&We.isScalar(this.contents)?this.contents.value:this.contents:We.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return We.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return yi.isEmptyPath(t)?this.contents!==void 0:We.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=yi.collectionFromPath(this.schema,[t],r):Ni(this.contents)&&this.contents.set(t,r)}setIn(t,r){yi.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=yi.collectionFromPath(this.schema,Array.from(t),r):Ni(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ll.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Ll.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Xk.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Yk.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Zk.applyReviver(o,{"":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 Qk.stringifyDocument(this,t)}};function Ni(e){if(We.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Eh.Document=Vl});var Rn=x(Pn=>{"use strict";var Cn=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Ml=class extends Cn{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Fl=class extends Cn{constructor(t,r,i){super("YAMLWarning",t,r,i)}},tS=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
@@ -69,7 +69,7 @@ ${l}
69
69
  `+b.comment:l.comment=b.comment),u=b.end;continue}!o&&r.options.strict&&yS.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let P="";e:for(let S of w)switch(S.type){case"comma":case"space":break;case"comment":P=S.source.substring(1);break e;default:break e}if(P){let S=l.items[l.items.length-1];mS.isPair(S)&&(S=S.value??S.key),S.comment?S.comment+=`
70
70
  `+P:S.comment=P,b.comment=b.comment.substring(P.length+1)}}if(!o&&!N&&!b.found){let P=k?e(r,k,b,n):t(r,b.end,N,null,b,n);l.items.push(P),u=P.range[2],Gl(k)&&n(P.range,"BLOCK_IN_FLOW",Jl)}else{r.atKey=!0;let P=b.end,S=y?e(r,y,b,n):t(r,P,w,null,b,n);Gl(y)&&n(S.range,"BLOCK_IN_FLOW",Jl),r.atKey=!1;let E=Vh.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:k,offset:S.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(E.found){if(!o&&!b.found&&r.options.strict){if(N)for(let $ of N){if($===E.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<E.found.offset-1024&&n(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(E.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let A=k?e(r,k,E,n):E.found?t(r,E.end,N,null,E,n):null;A?Gl(k)&&n(A.range,"BLOCK_IN_FLOW",Jl):E.comment&&(S.comment?S.comment+=`
71
71
  `+E.comment:S.comment=E.comment);let M=new vS.Pair(S,A);if(r.options.keepSourceTokens&&(M.srcToken=g),o){let $=l;NS.mapIncludes(r,$.items,S)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(M)}else{let $=new Lh.YAMLMap(r.schema);$.flow=!0,$.items.push(M);let de=(A??S).range;$.range=[S.range[0],de[1],de[2]],l.items.push($)}u=A?A.range[2]:E.end}}let d=o?"}":"]",[h,...v]=i.end,p=u;if(h?.source===d)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),g=f?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;n(u,f?"MISSING_CHAR":"BAD_INDENT",g),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=wS.resolveEnd(v,p,r.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
- `+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}Mh.resolveFlowCollection=bS});var Wh=x(qh=>{"use strict";var kS=O(),SS=Z(),ES=lr(),xS=ur(),CS=Oh(),PS=Dh(),RS=Fh();function Ul(e,t,r,i,n,a){let o=r.type==="block-map"?CS.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?PS.resolveBlockSeq(e,t,r,i,a):RS.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function AS(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!h||h.offset<v.offset)&&n(v,"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(!a||!o||o==="!"||o===ES.YAMLMap.tagName&&s==="map"||o===xS.YAMLSeq.tagName&&s==="seq")return Ul(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ul(e,t,r,n,o)}let l=Ul(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=kS.isNode(f)?f:new SS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}qh.composeCollection=AS});var Yl=x(zh=>{"use strict";var Kl=Z();function _S(e,t,r){let i=t.offset,n=IS(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Kl.Scalar.BLOCK_FOLDED:Kl.Scalar.BLOCK_LITERAL,o=t.source?TS(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
72
+ `+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}Mh.resolveFlowCollection=bS});var Wh=x(qh=>{"use strict";var kS=O(),SS=ee(),ES=lr(),xS=ur(),CS=Oh(),PS=Dh(),RS=Fh();function Ul(e,t,r,i,n,a){let o=r.type==="block-map"?CS.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?PS.resolveBlockSeq(e,t,r,i,a):RS.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function AS(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!h||h.offset<v.offset)&&n(v,"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(!a||!o||o==="!"||o===ES.YAMLMap.tagName&&s==="map"||o===xS.YAMLSeq.tagName&&s==="seq")return Ul(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ul(e,t,r,n,o)}let l=Ul(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=kS.isNode(f)?f:new SS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}qh.composeCollection=AS});var Yl=x(zh=>{"use strict";var Kl=ee();function _S(e,t,r){let i=t.offset,n=IS(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Kl.Scalar.BLOCK_FOLDED:Kl.Scalar.BLOCK_LITERAL,o=t.source?TS(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",m=i+n.length;return t.source&&(m+=t.source.length),{value:p,type:a,comment:n.comment,range:[i,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let p=0;p<s;++p){let[m,g]=o[p];if(g===""||g==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&r(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),f=p,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+g.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let u="",d="",h=!1;for(let p=0;p<f;++p)u+=o[p][0].slice(c)+`
74
74
  `;for(let p=f;p<s;++p){let[m,g]=o[p];l+=m.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&m.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(w?2:1),"BAD_INDENT",N),m=""}a===Kl.Scalar.BLOCK_LITERAL?(u+=d+m.slice(c)+g,d=`
75
75
  `):m.length>c||g[0]===" "?(d===" "?d=`
@@ -84,7 +84,7 @@ ${l}
84
84
  `+o[p][0].slice(c);u[u.length-1]!==`
85
85
  `&&(u+=`
86
86
  `);break;default:u+=`
87
- `}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function IS({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let h=n[d];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",u=n.length;for(let d=1;d<t.length;++d){let h=t[d];switch(h.type){case"space":l=!0;case"newline":u+=h.source.length;break;case"comment":r&&!l&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=h.source.length,f=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),u+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(u+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function TS(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}zh.resolveBlockScalar=_S});var Ql=x(Gh=>{"use strict";var Xl=Z(),jS=bi();function $S(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,h,v)=>r(i+d,h,v);switch(n){case"scalar":s=Xl.Scalar.PLAIN,c=OS(a,l);break;case"single-quoted-scalar":s=Xl.Scalar.QUOTE_SINGLE,c=HS(a,l);break;case"double-quoted-scalar":s=Xl.Scalar.QUOTE_DOUBLE,c=DS(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,u=jS.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function OS(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}`),Jh(e)}function HS(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Jh(e.slice(1,-1)).replace(/''/g,"'")}function Jh(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function IS({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let h=n[d];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",u=n.length;for(let d=1;d<t.length;++d){let h=t[d];switch(h.type){case"space":l=!0;case"newline":u+=h.source.length;break;case"comment":r&&!l&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=h.source.length,f=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),u+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(u+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function TS(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}zh.resolveBlockScalar=_S});var Ql=x(Gh=>{"use strict";var Xl=ee(),jS=bi();function $S(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,h,v)=>r(i+d,h,v);switch(n){case"scalar":s=Xl.Scalar.PLAIN,c=OS(a,l);break;case"single-quoted-scalar":s=Xl.Scalar.QUOTE_SINGLE,c=HS(a,l);break;case"double-quoted-scalar":s=Xl.Scalar.QUOTE_DOUBLE,c=DS(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,u=jS.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function OS(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}`),Jh(e)}function HS(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Jh(e.slice(1,-1)).replace(/''/g,"'")}function Jh(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
90
90
  `?n+=a:a=`
@@ -99,7 +99,7 @@ ${l}
99
99
  `);)i===`
100
100
  `&&(r+=`
101
101
  `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var LS={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function VS(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Gh.resolveFlowScalar=$S});var Yh=x(Kh=>{"use strict";var Dr=O(),Uh=Z(),MS=Yl(),FS=Ql();function qS(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?MS.resolveBlockScalar(e,t,i):FS.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,u=>i(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Dr.SCALAR]:c?l=WS(e.schema,n,c,r,i):t.type==="scalar"?l=zS(e,n,t,i):l=e.schema[Dr.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=Dr.isScalar(u)?u:new Uh.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new Uh.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function WS(e,t,r,i,n){if(r==="!")return e[Dr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Dr.SCALAR])}function zS({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Dr.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Dr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Kh.composeScalar=qS});var Qh=x(Xh=>{"use strict";function JS(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Xh.emptyScalarPosition=JS});var tm=x(eu=>{"use strict";var GS=ln(),US=O(),KS=Wh(),Zh=Yh(),YS=bi(),XS=Qh(),QS={composeNode:em,composeEmptyNode:Zl};function em(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=ZS(e,t,i),(s||c)&&i(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=Zh.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=KS.composeCollection(QS,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Zl(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!US.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Zl(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:XS.emptyScalarPosition(t,r,i),indent:-1,source:""},u=Zh.composeScalar(e,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function ZS({options:e},{offset:t,source:r,end:i},n){let a=new GS.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=YS.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}eu.composeEmptyNode=Zl;eu.composeNode=em});var nm=x(im=>{"use strict";var eE=xn(),rm=tm(),tE=bi(),rE=An();function iE(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new eE.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=rE.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?rm.composeNode(l,n,f,o):rm.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=tE.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}im.composeDoc=iE});var ru=x(sm=>{"use strict";var nE=Ja("process"),aE=Mc(),oE=xn(),_n=Rn(),am=O(),sE=nm(),cE=bi();function In(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 om(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function VS(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Gh.resolveFlowScalar=$S});var Yh=x(Kh=>{"use strict";var Dr=O(),Uh=ee(),MS=Yl(),FS=Ql();function qS(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?MS.resolveBlockScalar(e,t,i):FS.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,u=>i(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Dr.SCALAR]:c?l=WS(e.schema,n,c,r,i):t.type==="scalar"?l=zS(e,n,t,i):l=e.schema[Dr.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=Dr.isScalar(u)?u:new Uh.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new Uh.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function WS(e,t,r,i,n){if(r==="!")return e[Dr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Dr.SCALAR])}function zS({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Dr.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Dr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Kh.composeScalar=qS});var Qh=x(Xh=>{"use strict";function JS(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Xh.emptyScalarPosition=JS});var tm=x(eu=>{"use strict";var GS=ln(),US=O(),KS=Wh(),Zh=Yh(),YS=bi(),XS=Qh(),QS={composeNode:em,composeEmptyNode:Zl};function em(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=ZS(e,t,i),(s||c)&&i(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=Zh.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=KS.composeCollection(QS,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Zl(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!US.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Zl(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:XS.emptyScalarPosition(t,r,i),indent:-1,source:""},u=Zh.composeScalar(e,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function ZS({options:e},{offset:t,source:r,end:i},n){let a=new GS.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=YS.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}eu.composeEmptyNode=Zl;eu.composeNode=em});var nm=x(im=>{"use strict";var eE=xn(),rm=tm(),tE=bi(),rE=An();function iE(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new eE.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=rE.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?rm.composeNode(l,n,f,o):rm.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=tE.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}im.composeDoc=iE});var ru=x(sm=>{"use strict";var nE=Ja("process"),aE=Mc(),oE=xn(),_n=Rn(),am=O(),sE=nm(),cE=bi();function In(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 om(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
103
103
 
104
104
  `:`
105
105
  `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var tu=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=In(r);a?this.warnings.push(new _n.YAMLWarning(o,i,n)):this.errors.push(new _n.YAMLParseError(o,i,n))},this.directives=new aE.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=om(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
@@ -116,34 +116,34 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
116
116
  `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function lm(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 iu(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 i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
117
  `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Lo.createScalarToken=pE;Lo.resolveAsScalar=fE;Lo.setScalarValue=hE});var fm=x(dm=>{"use strict";var vE=e=>"type"in e?Mo(e):Vo(e);function Mo(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Mo(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Vo(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Vo(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Vo(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 Vo({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Mo(t)),r)for(let a of r)n+=a.source;return i&&(n+=Mo(i)),n}dm.stringify=vE});var vm=x(mm=>{"use strict";var nu=Symbol("break visit"),gE=Symbol("skip children"),pm=Symbol("remove item");function Br(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),hm(Object.freeze([]),e,t)}Br.BREAK=nu;Br.SKIP=gE;Br.REMOVE=pm;Br.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Br.parentCollection=(e,t)=>{let r=Br.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function hm(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=hm(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===nu)return nu;s===pm&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}mm.visit=Br});var Fo=x(_e=>{"use strict";var au=um(),wE=fm(),yE=vm(),ou="\uFEFF",su="",cu="",lu="",NE=e=>!!e&&"items"in e,bE=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function kE(e){switch(e){case ou:return"<BOM>";case su:return"<DOC>";case cu:return"<FLOW_END>";case lu:return"<SCALAR>";default:return JSON.stringify(e)}}function SE(e){switch(e){case ou:return"byte-order-mark";case su:return"doc-mode";case cu:return"flow-error-end";case lu:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `: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}_e.createScalarToken=au.createScalarToken;_e.resolveAsScalar=au.resolveAsScalar;_e.setScalarValue=au.setScalarValue;_e.stringify=wE.stringify;_e.visit=yE.visit;_e.BOM=ou;_e.DOCUMENT=su;_e.FLOW_END=cu;_e.SCALAR=lu;_e.isCollection=NE;_e.isScalar=bE;_e.prettyToken=kE;_e.tokenType=SE});var fu=x(wm=>{"use strict";var Tn=Fo();function tt(e){switch(e){case void 0:case" ":case`
119
+ `: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}_e.createScalarToken=au.createScalarToken;_e.resolveAsScalar=au.resolveAsScalar;_e.setScalarValue=au.setScalarValue;_e.stringify=wE.stringify;_e.visit=yE.visit;_e.BOM=ou;_e.DOCUMENT=su;_e.FLOW_END=cu;_e.SCALAR=lu;_e.isCollection=NE;_e.isScalar=bE;_e.prettyToken=kE;_e.tokenType=SE});var fu=x(wm=>{"use strict";var Tn=Fo();function rt(e){switch(e){case void 0:case" ":case`
120
120
  `:case"\r":case" ":return!0;default:return!1}}var gm=new Set("0123456789ABCDEFabcdef"),EE=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qo=new Set(",[]{}"),xE=new Set(` ,[]{}
121
121
  \r `),uu=e=>!e||xE.has(e),du=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 i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+i+1}return r===`
125
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&tt(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(`
126
- `,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]===Tn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),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 Tn.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==="...")&&tt(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&&!tt(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===":")&&tt(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"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(uu),"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,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&tt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Tn.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"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(uu),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||tt(o)||o===",")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 a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
125
+ `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&rt(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(`
126
+ `,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]===Tn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),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 Tn.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==="...")&&rt(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&&!rt(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===":")&&rt(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"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(uu),"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,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&rt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Tn.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"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(uu),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||rt(o)||o===",")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 a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
- `,a)}n!==-1&&(r=n-(i[n-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=>tt(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
128
+ `,a)}n!==-1&&(r=n-(i[n-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=>rt(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
129
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
130
  `)break}default:break e}if(!i&&!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 a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
131
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
132
132
  `;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Tn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(tt(a)||t&&qo.has(a))break;r=i}else if(tt(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Tn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(rt(a)||t&&qo.has(a))break;r=i}else if(rt(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
134
  `?(i+=1,n=`
135
135
  `,a=this.buffer[i+1]):r=i),a==="#"||t&&qo.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&qo.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Tn.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 i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.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(uu),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(tt(i)||r&&qo.has(i)){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(;!tt(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(EE.has(r))r=this.buffer[++t];else if(r==="%"&&gm.has(this.buffer[t+1])&&gm.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===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&qo.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Tn.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 i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.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(uu),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(rt(i)||r&&qo.has(i)){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(;!rt(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(EE.has(r))r=this.buffer[++t];else if(r==="%"&&gm.has(this.buffer[t+1])&&gm.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===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
138
  `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};wm.Lexer=du});var hu=x(ym=>{"use strict";var pu=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};ym.LineCounter=pu});var vu=x(Em=>{"use strict";var CE=Ja("process"),Nm=Fo(),PE=fu();function dr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function bm(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 Sm(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 Wo(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 ki(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 zo(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 km(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!dr(t.start,"explicit-key-ind")&&!dr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Sm(t.value)?t.value.end?zo(t.value.end,t.sep):t.value.end=t.sep:zo(t.start,t.sep),delete t.sep)}var mu=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 PE.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,CE.env.LOG_TOKENS&&console.log("|",Nm.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Nm.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 i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,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 i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&km(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&bm(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.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":{bm(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=Wo(this.peek(2)),i=ki(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}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(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
140
  `,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 i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.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 n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zo(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),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):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,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(dr(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Sm(r.key)&&!dr(r.sep,"newline")){let o=ki(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:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(dr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=ki(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):dr(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 o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!dr(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 i&&t.items.push({start:a});this.stack.push(o);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 i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.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 n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zo(n,r.start),n.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||dr(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.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 n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Wo(i),a=ki(n);km(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};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(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,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=Wo(t),i=ki(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Wo(t),i=ki(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.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())}}};Em.Parser=mu});var Am=x($n=>{"use strict";var xm=ru(),RE=xn(),jn=Rn(),AE=el(),_E=O(),IE=hu(),Cm=vu();function Pm(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new IE.LineCounter||null,prettyErrors:t}}function TE(e,t={}){let{lineCounter:r,prettyErrors:i}=Pm(t),n=new Cm.Parser(r?.addNewLine),a=new xm.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(jn.prettifyError(e,r)),s.warnings.forEach(jn.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Rm(e,t={}){let{lineCounter:r,prettyErrors:i}=Pm(t),n=new Cm.Parser(r?.addNewLine),a=new xm.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new jn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(jn.prettifyError(e,r)),o.warnings.forEach(jn.prettifyError(e,r))),o}function jE(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Rm(e,r);if(!n)return null;if(n.warnings.forEach(a=>AE.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function $E(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return _E.isDocument(e)&&!i?e.toString(r):new RE.Document(e,i,r).toString(r)}$n.parse=jE;$n.parseAllDocuments=TE;$n.parseDocument=Rm;$n.stringify=$E});var Si=x(V=>{"use strict";var OE=ru(),HE=xn(),DE=Hl(),gu=Rn(),BE=ln(),fr=O(),LE=sr(),VE=Z(),ME=lr(),FE=ur(),qE=Fo(),WE=fu(),zE=hu(),JE=vu(),Jo=Am(),_m=an();V.Composer=OE.Composer;V.Document=HE.Document;V.Schema=DE.Schema;V.YAMLError=gu.YAMLError;V.YAMLParseError=gu.YAMLParseError;V.YAMLWarning=gu.YAMLWarning;V.Alias=BE.Alias;V.isAlias=fr.isAlias;V.isCollection=fr.isCollection;V.isDocument=fr.isDocument;V.isMap=fr.isMap;V.isNode=fr.isNode;V.isPair=fr.isPair;V.isScalar=fr.isScalar;V.isSeq=fr.isSeq;V.Pair=LE.Pair;V.Scalar=VE.Scalar;V.YAMLMap=ME.YAMLMap;V.YAMLSeq=FE.YAMLSeq;V.CST=qE;V.Lexer=WE.Lexer;V.LineCounter=zE.LineCounter;V.Parser=JE.Parser;V.parse=Jo.parse;V.parseAllDocuments=Jo.parseAllDocuments;V.parseDocument=Jo.parseDocument;V.stringify=Jo.stringify;V.visit=_m.visit;V.visitAsync=_m.visitAsync});import{execFileSync as GE}from"child_process";import On from"path";function pr(e,t){return GE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function UE(e,t){let r=On.normalize(e),i=On.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function X(e){try{let t=On.resolve(pr(e,["rev-parse","--show-toplevel"])),i=pr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?On.resolve(i.slice(9)):t,a=null;try{a=pr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!UE(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Go(e){try{pr(e,["rev-parse","--is-inside-work-tree"]);let t=pr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:On.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Lr(e){return Go(e).map(t=>t.root)}function Ei(e,t){try{return pr(e,["check-ref-format","--branch",t]),pr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function xi(e,t){try{let r=pr(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 rt=C(()=>{"use strict"});import{execFileSync as KE}from"node:child_process";function Im(e,t){try{return KE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:YE,maxBuffer:XE,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new wu(e,t,i)}}function T(e,t){return Im(e,t).trim()}function Tm(e){return T(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function yu(e,t){T(e,["check-ref-format","--branch",t])}function jm(e){let t=Im(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var YE,XE,wu,Vr=C(()=>{"use strict";YE=3e4,XE=8*1024*1024,wu=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function ex(e){return e.toLowerCase().startsWith(".env")}function Ci(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>ex(i))?"environment-file":r.some(i=>ZE.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>QE.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var QE,ZE,Hn=C(()=>{"use strict";QE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ZE=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function hr(e){return e!==0&&e!==0n&&e!=="0"}function it(e,t){return hr(e.dev)&&hr(t.dev)&&hr(e.ino)&&hr(t.ino)}function J(e,t){let r=hr(e.dev)&&hr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=hr(e.ino)&&hr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Dn=C(()=>{"use strict"});var yt=C(()=>{"use strict";Dn()});import{createHash as tx}from"node:crypto";import{promises as nt}from"node:fs";import ze from"node:path";import{TextDecoder as rx}from"node:util";function Nu(e,t){let r=ze.relative(e,t);return r===""||!ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ze.sep}`)}function ix(e){let t=ze.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ze.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(),i=Ci(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function nx(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ax(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Uo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return it(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function $m(e){let t=await nt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await nt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ox(e,t){let r=ze.resolve(e),i=ze.resolve(t);if(!Nu(r,i))throw new Error("Native artifact path is outside its root");let n=[await $m(r)],a=r;for(let o of ze.relative(r,i).split(ze.sep).filter(Boolean)){a=ze.join(a,o);let s=await $m(a);if(!Nu(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Om(e){for(let t of e){let r=await nt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ax(t,r)||await nt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ie(e){let t=ix(e.ref),r=e.maxBytes===null?null:nx(e.maxBytes??Ko),i=ze.resolve(e.root,...t.split("/")),n=await ox(e.root,ze.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await nt.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await nt.realpath(i);if(!Nu(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await nt.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),nt.lstat(i),nt.realpath(i)]);if(await Om(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Uo(a,c)||!Uo(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?h.length:r+1-d,N=await s.read(h,0,Math.min(h.length,y),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(h.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),nt.lstat(i),nt.realpath(i)]);if(await Om(n),!p.isFile()||p.isSymbolicLink()||m!==o||!Uo(c,v)||!Uo(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(u,d),w;try{w=new rx("utf-8",{fatal:!0}).decode(g)}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:tx("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Ko,at=C(()=>{"use strict";Hn();yt();Ko=1024*1024});import{createHash as sx}from"crypto";function ot(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function cx(e,t){t.has(e)&&ot("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||ot("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&ot("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ot("symbol properties are not supported"),`[${e.map(i=>bu(i,t)).join(",")}]`}finally{t.delete(e)}}function lx(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&ot("only plain objects are supported"),t.has(e)&&ot("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ot("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&ot("accessor properties are not supported"),`${JSON.stringify(o)}:${bu(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function bu(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)||ot("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?cx(e,t):lx(e,t);case"bigint":case"function":case"symbol":case"undefined":return ot(`${typeof e} values are not supported`)}return ot("unsupported value type")}function Yo(e){return bu(e,new Set)}function _(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 sx("sha256").update(`${e}
142
+ `,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=Wo(t),i=ki(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Wo(t),i=ki(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.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())}}};Em.Parser=mu});var Am=x($n=>{"use strict";var xm=ru(),RE=xn(),jn=Rn(),AE=el(),_E=O(),IE=hu(),Cm=vu();function Pm(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new IE.LineCounter||null,prettyErrors:t}}function TE(e,t={}){let{lineCounter:r,prettyErrors:i}=Pm(t),n=new Cm.Parser(r?.addNewLine),a=new xm.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(jn.prettifyError(e,r)),s.warnings.forEach(jn.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Rm(e,t={}){let{lineCounter:r,prettyErrors:i}=Pm(t),n=new Cm.Parser(r?.addNewLine),a=new xm.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new jn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(jn.prettifyError(e,r)),o.warnings.forEach(jn.prettifyError(e,r))),o}function jE(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Rm(e,r);if(!n)return null;if(n.warnings.forEach(a=>AE.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function $E(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return _E.isDocument(e)&&!i?e.toString(r):new RE.Document(e,i,r).toString(r)}$n.parse=jE;$n.parseAllDocuments=TE;$n.parseDocument=Rm;$n.stringify=$E});var Si=x(V=>{"use strict";var OE=ru(),HE=xn(),DE=Hl(),gu=Rn(),BE=ln(),fr=O(),LE=sr(),VE=ee(),ME=lr(),FE=ur(),qE=Fo(),WE=fu(),zE=hu(),JE=vu(),Jo=Am(),_m=an();V.Composer=OE.Composer;V.Document=HE.Document;V.Schema=DE.Schema;V.YAMLError=gu.YAMLError;V.YAMLParseError=gu.YAMLParseError;V.YAMLWarning=gu.YAMLWarning;V.Alias=BE.Alias;V.isAlias=fr.isAlias;V.isCollection=fr.isCollection;V.isDocument=fr.isDocument;V.isMap=fr.isMap;V.isNode=fr.isNode;V.isPair=fr.isPair;V.isScalar=fr.isScalar;V.isSeq=fr.isSeq;V.Pair=LE.Pair;V.Scalar=VE.Scalar;V.YAMLMap=ME.YAMLMap;V.YAMLSeq=FE.YAMLSeq;V.CST=qE;V.Lexer=WE.Lexer;V.LineCounter=zE.LineCounter;V.Parser=JE.Parser;V.parse=Jo.parse;V.parseAllDocuments=Jo.parseAllDocuments;V.parseDocument=Jo.parseDocument;V.stringify=Jo.stringify;V.visit=_m.visit;V.visitAsync=_m.visitAsync});import{execFileSync as GE}from"child_process";import On from"path";function pr(e,t){return GE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function UE(e,t){let r=On.normalize(e),i=On.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function X(e){try{let t=On.resolve(pr(e,["rev-parse","--show-toplevel"])),i=pr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?On.resolve(i.slice(9)):t,a=null;try{a=pr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!UE(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Go(e){try{pr(e,["rev-parse","--is-inside-work-tree"]);let t=pr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:On.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Lr(e){return Go(e).map(t=>t.root)}function Ei(e,t){try{return pr(e,["check-ref-format","--branch",t]),pr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function xi(e,t){try{let r=pr(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 it=C(()=>{"use strict"});import{execFileSync as KE}from"node:child_process";function Im(e,t){try{return KE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:YE,maxBuffer:XE,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new wu(e,t,i)}}function T(e,t){return Im(e,t).trim()}function Tm(e){return T(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function yu(e,t){T(e,["check-ref-format","--branch",t])}function jm(e){let t=Im(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var YE,XE,wu,Vr=C(()=>{"use strict";YE=3e4,XE=8*1024*1024,wu=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function ex(e){return e.toLowerCase().startsWith(".env")}function Ci(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>ex(i))?"environment-file":r.some(i=>ZE.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>QE.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var QE,ZE,Hn=C(()=>{"use strict";QE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ZE=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function hr(e){return e!==0&&e!==0n&&e!=="0"}function nt(e,t){return hr(e.dev)&&hr(t.dev)&&hr(e.ino)&&hr(t.ino)}function J(e,t){let r=hr(e.dev)&&hr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=hr(e.ino)&&hr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Dn=C(()=>{"use strict"});var Nt=C(()=>{"use strict";Dn()});import{createHash as tx}from"node:crypto";import{promises as at}from"node:fs";import ze from"node:path";import{TextDecoder as rx}from"node:util";function Nu(e,t){let r=ze.relative(e,t);return r===""||!ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ze.sep}`)}function ix(e){let t=ze.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ze.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(),i=Ci(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function nx(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ax(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Uo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return nt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function $m(e){let t=await at.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await at.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ox(e,t){let r=ze.resolve(e),i=ze.resolve(t);if(!Nu(r,i))throw new Error("Native artifact path is outside its root");let n=[await $m(r)],a=r;for(let o of ze.relative(r,i).split(ze.sep).filter(Boolean)){a=ze.join(a,o);let s=await $m(a);if(!Nu(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Om(e){for(let t of e){let r=await at.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ax(t,r)||await at.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ie(e){let t=ix(e.ref),r=e.maxBytes===null?null:nx(e.maxBytes??Ko),i=ze.resolve(e.root,...t.split("/")),n=await ox(e.root,ze.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await at.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await at.realpath(i);if(!Nu(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await at.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),at.lstat(i),at.realpath(i)]);if(await Om(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Uo(a,c)||!Uo(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?h.length:r+1-d,N=await s.read(h,0,Math.min(h.length,y),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(h.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),at.lstat(i),at.realpath(i)]);if(await Om(n),!p.isFile()||p.isSymbolicLink()||m!==o||!Uo(c,v)||!Uo(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(u,d),w;try{w=new rx("utf-8",{fatal:!0}).decode(g)}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:tx("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Ko,ot=C(()=>{"use strict";Hn();Nt();Ko=1024*1024});import{createHash as sx}from"crypto";function st(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function cx(e,t){t.has(e)&&st("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||st("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&st("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&st("symbol properties are not supported"),`[${e.map(i=>bu(i,t)).join(",")}]`}finally{t.delete(e)}}function lx(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&st("only plain objects are supported"),t.has(e)&&st("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&st("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&st("accessor properties are not supported"),`${JSON.stringify(o)}:${bu(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function bu(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)||st("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?cx(e,t):lx(e,t);case"bigint":case"function":case"symbol":case"undefined":return st(`${typeof e} values are not supported`)}return st("unsupported value type")}function Yo(e){return bu(e,new Set)}function _(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 sx("sha256").update(`${e}
143
143
  ${Yo(t)}`).digest("hex")}var ve=C(()=>{"use strict"});import mr from"path";function Vm(e,t){return Pi[t][e]}function hx(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Pi.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Pi.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Pi.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Pi.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Pi.en)return s}return null}function Mn(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,Ln.stringify)(e).trimEnd().split(`
144
144
  `)){let s=hx(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Vm(s,t).split(`
145
145
  `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
146
- `)}function mx(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||mr.posix.isAbsolute(r)||mr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Mr(e){let t=mx(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Mm(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 Zo(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||mr.posix.isAbsolute(i)||mr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Mt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Fm(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function es(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Xo)throw new Error(`${t} exceeds ${Xo} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Qo)throw new Error(`${t} contains more than ${Qo} wildcard tokens`);return e}function Lm(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>es(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function ku(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function vx(e){if(e===void 0)return{...De,include:[...De.include],exclude:[...De.exclude]};let t=Mt(e,"native.snapshot");return{include:Lm(t.include,"native.snapshot.include",De.include),exclude:Lm(t.exclude,"native.snapshot.exclude",De.exclude),max_files:ku(t.max_files,De.max_files,"native.snapshot.max_files"),max_total_bytes:ku(t.max_total_bytes,De.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ku(t.max_duration_ms,De.max_duration_ms,"native.snapshot.max_duration_ms")}}function gx(e){if(e===void 0)return;let t=Mt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=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 i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Mt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=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 f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:Mr(i),toArtifactRoot:Mr(n),stage:a,...o?{cleanup:o}:{}}}function wx(e){if(e===void 0)return;let t=Mt(e,"native.finish");if(t.pull_request===void 0)return{};let r=Mt(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 i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(mr.posix.isAbsolute(i[0])||mr.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??ux;if(!Number.isSafeInteger(n)||n<1||n>Bm)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Bm}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function yx(e,t={}){let r=Mt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Su;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=gx(r.pending_root_move),c=wx(r.finish);return{artifact_root:Mr(i),language:Fm(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:vx(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Nx(e){let t=Mt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Mm(t.artifact_layout),language:Fm(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function bx(e){let r=Mt(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((i,n)=>Zo(i,`hook.allow_paths[${n}]`)))]}}function kx(e){if(e===void 0)return{...Bn};let t=Mt(e,"memory"),r=t.learning??Bn.learning,i=t.retrieval??Bn.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function xu(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Sx(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")||mr.posix.isAbsolute(r)||mr.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))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>Hm)throw new Error(`${t} exceeds ${Hm} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Dm)throw new Error(`${t} contains more than ${Dm} wildcard tokens`);return r}function Ex(e){let r=xu(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>Sx(i,`knowledge.local.include[${n}]`)))]}}function xx(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,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function Cx(e){let t=xu(e,"knowledge.remote"),r=xx(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function Px(e){if(e===void 0)return{...Eu};let t=xu(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:Ex(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Cx(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function Rx(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Ax(e,t,r,i,n,a,o,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 f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(f)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Ri(e,t={}){let r=(0,Ln.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=Rx(n.ambient_resume),o=n.hook===void 0?void 0:bx(n.hook),s=kx(n.memory),c=Px(n.knowledge),l=n.native===void 0?void 0:yx(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:Nx(n.classic),u=Ax(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function qm(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 Wm(e){let t=e.knowledge??{...Eu};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Bn},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...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,...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:qm(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}}:{}}}function He(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Fn(e,t){let r=Wm(t),i=Ri((0,Ln.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...He(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=He(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=He(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...He(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...He(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=He(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=He(a.finish);o.finish={...s,pull_request:{...He(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...He(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=He(a.pending_root_move),c=qm(i.native.pending_root_move),l=He(s.cleanup),f=He(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...He(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function ts(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Bn},knowledge:{...Eu},native:{artifact_root:Mr(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Su,snapshot:{...De,include:[...De.include],exclude:[...De.exclude]}}}}var Ln,Vn,Xo,Qo,Hm,Dm,Su,Bn,Eu,ux,Bm,dx,fx,px,De,Pi,vr=C(()=>{"use strict";Ln=nn(Si(),1),Vn=64*1024,Xo=1024,Qo=64,Hm=1024,Dm=64,Su=5,Bn={learning:!0,retrieval:!0},Eu={provider:"local"},ux=12e4,Bm=6e5,dx=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],fx=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],px=[...dx,...fx].sort((e,t)=>e.localeCompare(t,"en")),De={include:["**/*"],exclude:[...px],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Pi={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.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
146
+ `)}function mx(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||mr.posix.isAbsolute(r)||mr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Mr(e){let t=mx(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Mm(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 Zo(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||mr.posix.isAbsolute(i)||mr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Ft(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Fm(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function es(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Xo)throw new Error(`${t} exceeds ${Xo} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Qo)throw new Error(`${t} contains more than ${Qo} wildcard tokens`);return e}function Lm(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>es(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function ku(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function vx(e){if(e===void 0)return{...De,include:[...De.include],exclude:[...De.exclude]};let t=Ft(e,"native.snapshot");return{include:Lm(t.include,"native.snapshot.include",De.include),exclude:Lm(t.exclude,"native.snapshot.exclude",De.exclude),max_files:ku(t.max_files,De.max_files,"native.snapshot.max_files"),max_total_bytes:ku(t.max_total_bytes,De.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ku(t.max_duration_ms,De.max_duration_ms,"native.snapshot.max_duration_ms")}}function gx(e){if(e===void 0)return;let t=Ft(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=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 i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Ft(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=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 f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:Mr(i),toArtifactRoot:Mr(n),stage:a,...o?{cleanup:o}:{}}}function wx(e){if(e===void 0)return;let t=Ft(e,"native.finish");if(t.pull_request===void 0)return{};let r=Ft(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 i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(mr.posix.isAbsolute(i[0])||mr.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??ux;if(!Number.isSafeInteger(n)||n<1||n>Bm)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Bm}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function yx(e,t={}){let r=Ft(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Su;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=gx(r.pending_root_move),c=wx(r.finish);return{artifact_root:Mr(i),language:Fm(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:vx(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Nx(e){let t=Ft(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Mm(t.artifact_layout),language:Fm(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function bx(e){let r=Ft(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((i,n)=>Zo(i,`hook.allow_paths[${n}]`)))]}}function kx(e){if(e===void 0)return{...Bn};let t=Ft(e,"memory"),r=t.learning??Bn.learning,i=t.retrieval??Bn.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function xu(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Sx(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")||mr.posix.isAbsolute(r)||mr.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))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>Hm)throw new Error(`${t} exceeds ${Hm} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Dm)throw new Error(`${t} contains more than ${Dm} wildcard tokens`);return r}function Ex(e){let r=xu(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>Sx(i,`knowledge.local.include[${n}]`)))]}}function xx(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,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function Cx(e){let t=xu(e,"knowledge.remote"),r=xx(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function Px(e){if(e===void 0)return{...Eu};let t=xu(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:Ex(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Cx(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function Rx(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Ax(e,t,r,i,n,a,o,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 f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(f)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Ri(e,t={}){let r=(0,Ln.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=Rx(n.ambient_resume),o=n.hook===void 0?void 0:bx(n.hook),s=kx(n.memory),c=Px(n.knowledge),l=n.native===void 0?void 0:yx(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:Nx(n.classic),u=Ax(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function qm(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 Wm(e){let t=e.knowledge??{...Eu};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Bn},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...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,...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:qm(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}}:{}}}function He(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Fn(e,t){let r=Wm(t),i=Ri((0,Ln.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...He(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=He(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=He(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...He(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...He(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=He(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=He(a.finish);o.finish={...s,pull_request:{...He(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...He(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=He(a.pending_root_move),c=qm(i.native.pending_root_move),l=He(s.cleanup),f=He(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...He(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function ts(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Bn},knowledge:{...Eu},native:{artifact_root:Mr(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Su,snapshot:{...De,include:[...De.include],exclude:[...De.exclude]}}}}var Ln,Vn,Xo,Qo,Hm,Dm,Su,Bn,Eu,ux,Bm,dx,fx,px,De,Pi,vr=C(()=>{"use strict";Ln=nn(Si(),1),Vn=64*1024,Xo=1024,Qo=64,Hm=1024,Dm=64,Su=5,Bn={learning:!0,retrieval:!0},Eu={provider:"local"},ux=12e4,Bm=6e5,dx=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],fx=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],px=[...dx,...fx].sort((e,t)=>e.localeCompare(t,"en")),De={include:["**/*"],exclude:[...px],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Pi={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.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
147
147
  # 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.
148
148
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
149
149
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -167,27 +167,27 @@ ${Yo(t)}`).digest("hex")}var ve=C(()=>{"use strict"});import mr from"path";funct
167
167
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
168
168
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
169
169
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
170
- # 可选值:true | false`}}});import{constants as rs,promises as Fr}from"fs";function Cu(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function zm(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function qn(e){return{dev:e.dev,ino:e.ino,birthtime:Cu(e)}}function is(e,t){let r=qn(e),i=qn(t);return it(r,i)?J(r,i):J(r,i)&&Cu(e)===Cu(t)&&zm(e)===zm(t)&&e.size===t.size}async function Ai(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Fr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new st("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new st("too-large",`${i} exceeds ${t} bytes`);let o=await Fr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:qn(a)});let s=process.platform==="win32"?rs.O_RDONLY:rs.O_RDONLY|rs.O_NOFOLLOW|rs.O_NONBLOCK,c;try{c=await Fr.open(e,s)}catch(l){throw l.code==="ELOOP"?new st("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),Fr.lstat(e,{bigint:n}),Fr.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!is(a,l)||!is(a,f))throw new st("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:qn(l)}),await r.hooks?.afterOpen?.();let d=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,w),null);if(y===0)break;if(h+=y,h>t)throw new st("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[p,m,g]=await Promise.all([c.stat({bigint:n}),Fr.lstat(e,{bigint:n}),Fr.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!is(a,p)||!is(a,m))throw new st("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:qn(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:g}}finally{await c.close()}}var st,Wn=C(()=>{"use strict";Dn();st=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as ns}from"fs";import gr from"path";function _x(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Pu(e,t){let r=gr.relative(e,t);return r===""||!gr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${gr.sep}`)}async function Jm(e,t){let r=gr.resolve(e),i=await ns.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ns.realpath(r)}async function Gm(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=gr.join(n,r[a]);let o;try{o=await ns.lstat(n)}catch(f){if(_x(f))return{exists:!1,kind:"missing"};throw f}let s=gr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await ns.realpath(n);if(!Pu(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function _i(e,t,r){let i=Zo(t,r.label),n=gr.resolve(e),a=await Jm(n,r.label),o=i.split("/"),s=gr.resolve(n,...o);if(!Pu(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Gm(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function wr(e,t,r,i){let n=await _i(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Jm(n.projectRoot,i.label);return Ai(n.target,r,{...i,verify:async(o,s)=>{if(!Pu(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Gm(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var qr=C(()=>{"use strict";Wn();vr()});import{createHash as Ix}from"crypto";function Ru(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Tx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function as(e,t={}){return(await Jn(e,t)).document}async function Um(e){try{return(await wr(e,zn,Vn,{label:zn})).bytes}catch(t){if(Tx(t))return null;throw t}}function Km(e){return e?{exists:!0,sha256:Ix("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function os(e){return Km(await Um(e))}async function Jn(e,t={}){let r=await Um(e);return{document:r?Ri(r.toString("utf8"),t):null,identity:Km(r)}}async function Au(e){return(await as(e))?.config??null}var zn,Ii=C(()=>{"use strict";vr();qr();zn=".comet/config.yaml"});var Ti=C(()=>{"use strict";Dn()});var I$,_u=C(()=>{"use strict";Ti();Ii();qr();I$=16*1024});async function Iu(e,t){if(!t)return;let r=await os(e);if(!Ru(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Tu=C(()=>{"use strict";Ti();vr();Ii();qr();_u()});import{randomUUID as Hx}from"crypto";import{promises as oe}from"fs";import ct from"path";function ss(e,t){let r=ct.relative(e,t);return r===""||!ct.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ct.sep}`)}function Dx(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function cs(e,t){return J({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Bx(e,t){return cs(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ym(e){let t=await oe.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 oe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ji(e){for(let t of e){let r=await oe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Dx(t,r)||await oe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Lx(e,t,r){let[i,n]=await Promise.all([oe.lstat(e),oe.realpath(e),r?ji(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!cs(i,t)||r&&!ss(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Vx(e,t){let r=ct.resolve(e),i=ct.resolve(t);if(!ss(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Ym(r)],a=ct.relative(r,i).split(ct.sep).filter(Boolean),o=r;for(let s of a){await ji(n),o=ct.join(o,s);try{await oe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ym(o);if(!ss(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ji(n),n}async function Mx(e){let t;try{t=await oe.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Fx(e,t,r={}){let i=ct.dirname(e),n=r.containedRoot?await Vx(r.containedRoot,i):null;n||await oe.mkdir(i,{recursive:!0});let a=ct.join(i,`.${ct.basename(e)}.${Hx()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await oe.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([oe.lstat(a),oe.realpath(a)]);if(await ji(n),!l.isFile()||l.isSymbolicLink()||!cs(s,l)||!ss(n[0].realPath,f))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!cs(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Lx(a,c,n),await r.beforeCommit?.(),n){await ji(n);let l=await oe.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Bx(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await oe.link(a,e),await oe.unlink(a)):await oe.rename(a,e),await Mx(i)}catch(l){if(await o?.close(),!n)await oe.rm(a,{force:!0});else try{await ji(n),await oe.rm(a,{force:!0})}catch{}throw l}}async function Je(e,t,r={}){await Fx(e,t,r)}async function pe(e,t,r={}){await Je(e,JSON.stringify(t,null,2)+`
171
- `,r)}var Q=C(()=>{"use strict";yt()});import{existsSync as Xm,promises as Wr}from"fs";import B from"path";import qx from"os";async function ju(e){try{return await Wr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function zx(e){try{let t=await Wr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Oi(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function $i(e){let t=[],r=e;for(;!await ju(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await Wr.realpath(r);return B.resolve(i,...t.reverse())}async function $u(e){try{return(await Wr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ls(e){let t=B.resolve(e);try{(await Wr.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(qx.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...Un.split("/")),s=t===r||await zx(o);if(await ju(o)&&s)return t}if(await ju(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function us(e){return Mr(e)}async function Jx(e,t){let r=us(t),i=B.resolve(e,...r.split("/")),n=await Wr.realpath(e),a=await $i(i);if(!Oi(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function yr(e,t){let r=us(t),i=await Jx(e,r),n=B.join(i,"comet");if(await $u(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([$i(i),$i(n)]);if(!Oi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await $u(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Wr.realpath(s),$i(c)]);if(!Oi(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...Un.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Qm(e){if(!Wx.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ke(e,t){Qm(t);let r=B.join(e.changesRuntimeDir,t);if(!ge(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ou(e,t){Qm(t);let r=B.join(e.changesDir,t,"runtime");if(!ge(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ge(e,t){let r=ke(e,t);if(Xm(r))return r;let i=Ou(e,t);return Xm(i)?i:r}function Hu(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!ge(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ie(e,t){let r=B.resolve(t);if(ge(e.runtimeDir,r))return e.runtimeDir;if(ge(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ge(e,t){return Oi(B.resolve(e),B.resolve(t))}async function U(e,t){let r=B.resolve(e),i=B.resolve(t);if(!Oi(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await $u(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([$i(r),$i(i)]);if(!Oi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Un,Wx,K=C(()=>{"use strict";vr();Un=".comet/config.yaml",Wx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import Gx from"path";function Ux(e="docs",t="en"){return ts(e,t)}async function Te(e){let t=(await as(e))?.config??null;return t?.native?t:null}async function fs(e){let t=await Te(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 ps(e,t,r={}){let i=await Jn(e,{allowPartialProject:!0}),n=Fn(i.document?.value??{},t),a=Gx.join(e,...Un.split("/"));await Je(a,Mn(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Iu(e,i.identity)}})}async function Zm(e){let t=await ls(e.startPath),r=await Te(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Un} 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 i=e.explicitArtifactRoot?us(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Ux(i??"docs"),a=await yr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var ds,lt=C(()=>{"use strict";vr();Ii();Tu();Q();K();ds=es});function ms(){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 zr,Kn,hs,Hi=C(()=>{"use strict";zr="comet.native.v4",Kn="comet.native.local-execution.v4",hs=["multi-session","single-session"]});var Vu={};Ga(Vu,{NativePortableStateVersionConflictError:()=>Yn,appendNativePortableHistory:()=>we,compareAndSwapNativePortableState:()=>Li,createNativePortableState:()=>rv,parseNativePortableState:()=>I,readNativePortableState:()=>Be,writeNativePortableState:()=>Xn});import{promises as Kx}from"node:fs";function Se(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ee(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function se(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 Bu(e,t){return e===null?null:se(e,t)}function ev(e,t){let r=se(e,t);if(!Zx.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Di(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Y(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 tC(e,t){return e===null?null:Y(e,t,Number.MIN_SAFE_INTEGER)}function ee(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Nt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function ws(e,t){return Nt(e,t,(r,i)=>se(r,`${t}[${i}]`))}function Jr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Bi(e,t){let r=se(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Lu(e,t,r=!1){let i=se(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Ue(e,t){let r=Se(e,t);return Ee(r,new Set(["text","truncated"]),t),{text:se(r.text,`${t}.text`,{empty:!0}),truncated:Di(r.truncated,`${t}.truncated`)}}function rC(e,t){let r=`Native spec_changes[${t}]`,i=Se(e,r);Ee(i,new Set(["capability","operation","source"]),r);let n=se(i.capability,`${r}.capability`);if(!Xx.test(n))throw new Error(`${r}.capability is invalid`);let a=ee(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Lu(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function iC(e){let t="Native workspace",r=Se(e,t);Ee(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ee(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Bu(r.change_branch,`${t}.change_branch`),a=Bu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ee(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function nC(e){let t="Native loop",r=Se(e,t);Ee(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 i=ws(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Jr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ee(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ee(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:Y(r.goal_cycle,`${t}.goal_cycle`,1),iteration:Y(r.iteration,`${t}.iteration`),attempt:Y(r.attempt,`${t}.attempt`),retry_epoch:Y(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:Y(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:Y(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:Y(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Bu(r.next_action,`${t}.next_action`)}}function aC(e,t){let r=`Native acceptance[${t}]`,i=Se(e,r);Ee(i,new Set(["id","source","text","result","reason"]),r);let n=se(i.id,`${r}.id`);if(!Qx.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Lu(i.source,`${r}.source`),text:se(i.text,`${r}.text`),result:ee(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ue(i.reason,`${r}.reason`)}}function oC(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Se(e,r);return Ee(i,new Set(["name","result","note"]),r),{name:Ue(i.name,`${r}.name`),result:ee(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ue(i.note,`${r}.note`)}}function sC(e){let t="Native builder_handoff",r=Se(e,t);Ee(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=ws(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Jr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Se(r.review,`${t}.review`);return n&&Ee(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:se(r.candidate_id,`${t}.candidate_id`),identity_provider:se(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:se(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:Y(r.iteration,`${t}.iteration`,1),summary:Ue(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Nt(r.checks,`${t}.checks`,oC),checks_truncated:Di(r.checks_truncated,`${t}.checks_truncated`),known_limits:Nt(r.known_limits,`${t}.known_limits`,(a,o)=>Ue(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Di(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ee(n.status,["passed"],`${t}.review.status`),summary:Ue(n.summary,`${t}.review.summary`),reviewer_execution_ref:se(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Bi(r.submitted_at,`${t}.submitted_at`)}}function cC(e,t){let r=`Native blockers[${t}]`,i=Se(e,r);Ee(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ws(i.acceptance_ids,`${r}.acceptance_ids`);return Jr(n,`${r}.acceptance_ids`),{owner:ee(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ue(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ee(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function lC(e,t){let r=`Native verification.checks[${t}]`,i=Se(e,r);return Ee(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:se(i.id,`${r}.id`),name:Ue(i.name,`${r}.name`),argv_display:Nt(i.argv_display,`${r}.argv_display`,(n,a)=>Ue(n,`${r}.argv_display[${a}]`)),argv_truncated:Di(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Lu(i.cwd_ref,`${r}.cwd_ref`,!0),status:ee(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:tC(i.exit_code,`${r}.exit_code`),duration_ms:Y(i.duration_ms,`${r}.duration_ms`)}}function uC(e){let t="Native verification",r=Se(e,t);Ee(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Nt(r.checks,`${t}.checks`,lC);Jr(i.map(a=>a.id),`${t}.checks IDs`);let n=se(r.identity_provider,`${t}.identity_provider`);return{candidate_id:se(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:se(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:Y(r.iteration,`${t}.iteration`,1),attempt:Y(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ee(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ee(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ue(r.summary,`${t}.summary`),risks:Nt(r.risks,`${t}.risks`,(a,o)=>Ue(a,`${t}.risks[${o}]`)),risks_truncated:Di(r.risks_truncated,`${t}.risks_truncated`),completed_at:Bi(r.completed_at,`${t}.completed_at`)}}function tv(e,t){let r=`Native history[${t}]`,i=Se(e,r);Ee(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ws(i.unresolved_ids,`${r}.unresolved_ids`);return Jr(n,`${r}.unresolved_ids`),{goal_cycle:Y(i.goal_cycle,`${r}.goal_cycle`,1),iteration:Y(i.iteration,`${r}.iteration`),attempt:Y(i.attempt,`${r}.attempt`),outcome:ee(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ue(i.summary,`${r}.summary`),completed_at:Bi(i.completed_at,`${r}.completed_at`)}}function dC(e){let t="Native history_overflow.outcome_counts",r=Se(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ee(r,new Set(i),t),{pass:Y(r.pass,`${t}.pass`),fail:Y(r.fail,`${t}.fail`),blocked:Y(r.blocked,`${t}.blocked`),"execution-error":Y(r["execution-error"],`${t}.execution-error`),recovery:Y(r.recovery,`${t}.recovery`)}}function fC(e){let t="Native history_overflow",r=Se(e,t);Ee(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=Y(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Bi(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Bi(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=dC(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function pC(e){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}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);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");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");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.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function hC(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(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.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 I(e){let t=Se(e,"Native portable state");if(Ee(t,eC,"Native portable state"),t.schema!==zr)throw new Error(`Native portable state schema must be ${zr}`);let r=se(t.name,"Native state name");if(!Yx.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 i=Nt(t.spec_changes,"Native spec_changes",rC);Jr(i.map(s=>s.capability),"Native spec change capabilities");let n=Nt(t.acceptance,"Native acceptance",aC);Jr(n.map(s=>s.id),"Native acceptance IDs");let a=Nt(t.history,"Native history",tv);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:zr,name:r,language:ee(t.language,["en","zh-CN"],"Native state language"),phase:ee(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ee(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:Y(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:ev(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:ev(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ee(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:iC(t.workspace),loop:nC(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:sC(t.builder_handoff),blockers:Nt(t.blockers,"Native blockers",cC),verification:t.verification===null?null:uC(t.verification),history:a,history_overflow:fC(t.history_overflow),verification_result:ee(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ee(t.verification_report,["verification.md"],"Native verification_report"),archived:Di(t.archived,"Native archived"),created_at:Bi(t.created_at,"Native created_at")};return pC(o),hC(o),o}function rv(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return I({schema:zr,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:ms(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function we(e,t){let r=I(e),i=tv(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return I({...r,history:n,history_overflow:a})}function mC(e,t){let r=(0,gs.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})}async function Be(e){let t=await Kx.readFile(e,"utf8");return I(mC(t,"Native portable state"))}async function Xn(e,t,r={}){let i=I(t);await Je(e,(0,gs.stringify)(i),r)}async function vC(e,t){let r=vs.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);vs.set(e,a),await r;try{return await t()}finally{i(),vs.get(e)===a&&vs.delete(e)}}async function Li(e){return vC(e.file,async()=>{let t=Y(e.expectedStateVersion,"Native expected state version",1),r=I(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Be(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Yn(t,i.state_version);return await Xn(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Be(e.file);if(n.state_version!==t)throw new Yn(t,n.state_version)}}),r})}var gs,Yx,Xx,Qx,Zx,eC,Yn,vs,Ft=C(()=>{"use strict";gs=nn(Si(),1);Q();Hi();Yx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Qx=/^A[1-9][0-9]*$/u,Zx=/^[a-f0-9]{64}$/u,eC=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Yn=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};vs=new Map});import{createHash as gC}from"node:crypto";import{lstatSync as wC,readFileSync as iv,promises as nv}from"node:fs";import ys from"node:path";function yC(e){try{if(T(e,["ls-files","--",Ns]))return!1;let t=ys.join(e,Ns),r=wC(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(iv(av(e),"utf8")).hash===ov(iv(t))}catch{return!1}}async function sv(e){let t=ys.join(e,Ns),r;try{r=await nv.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=av(e);await nv.mkdir(ys.dirname(i),{recursive:!0}),await pe(i,{hash:ov(r)},{containedRoot:e})}function qt(e,t=[]){return jm(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===Ns&&yC(e))}var Ns,av,ov,Qn=C(()=>{"use strict";Vr();Q();Ns=".comet/config.yaml",av=e=>ys.join(e,".comet","runtime","native","workspace-config.json"),ov=e=>gC("sha256").update(e).digest("hex")});import{spawn as Mu}from"node:child_process";import{existsSync as cv}from"node:fs";import Gr from"node:path";function Fu(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function EC(e){let t=(Fu(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function xC(e,t,r){let n=Gr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Fu(t,"PATH")??"").split(Gr.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Gr.win32.extname(e)?[e]:EC(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Gr.join(s,c):Gr.resolve(r,c)))}function qu(e,t,r){return xC(e,t,r).find(i=>cv(i))??e}function CC(e){let t=Fu(e,"SystemRoot");if(t){let r=Gr.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(cv(r))return r}return"powershell.exe"}function Wu(e){if(e.some(t=>kC.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function PC(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(SC,"utf16le").toString("base64");return Mu(CC(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function zu(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Mu(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=qu(e,i,r.cwd),a=Gr.win32.extname(n).toLowerCase();return bC.has(a)&&Wu(t),NC.has(a)?PC(n,t,{cwd:r.cwd,env:i}):Mu(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var NC,bC,kC,SC,bs=C(()=>{"use strict";NC=new Set([".bat",".cmd",".ps1"]),bC=new Set([".bat",".cmd"]),kC=/[&|<>()^%"!\r\n]/u,SC=["$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 RC}from"node:child_process";import Ju from"node:path";async function Zn(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&Ju.win32.isAbsolute(r)?Ju.win32.resolve(r):"C:\\Windows",n=Ju.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(u,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(u))};try{c=RC(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",u=>f(u===0)),l=setTimeout(()=>f(!1,!0),AC)}catch{f(!1)}});for(let o=0;o<_C;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var AC,_C,Gu=C(()=>{"use strict";AC=1e3,_C=2});function Le(e){return e.replace(IC,"$1 [REDACTED]").replace(TC,"[REDACTED PRIVATE KEY]").replace(jC,"$1[REDACTED]@").replace($C,"[REDACTED TOKEN]").replace(OC,'$1"[REDACTED]"').replace(HC,"$1$2$1$3$4[REDACTED]$4").replace(DC,"$1$2[REDACTED]")}var IC,TC,jC,$C,OC,HC,DC,Nr=C(()=>{"use strict";IC=/\b(Bearer|Basic)\s+[^\s"']+/giu,TC=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,jC=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,$C=/\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,OC=/("(?:[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,HC=/(["'])((?:[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,DC=/\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{createWriteStream as BC,promises as LC}from"node:fs";import Ve from"node:path";function lv(e,t){let r=Ve.relative(e,t);return r===""||!Ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ve.sep}`)}function uv(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function ks(e,t){if(t.length===0||t.includes("\\")||Ve.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Ve.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Ve.resolve(e),i=Ve.resolve(r,...t.split("/"));if(!lv(r,i))throw new Error("Native check cwd escaped the project root");return i}function ea(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function Uu(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Le(r);return VC.test(r)&&(t=!0),i})}function br(e,t){if(uv(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return ks(e,t.cwdRef)}async function Ur(e){let{plan:t}=e;uv(e.operationId,"Native check operation ID");let r=br(e.projectRoot,t),i=Ve.join(e.runtimeDir,"logs","checks"),n=Ve.join(i,`${e.operationId}-${t.id}.log`);if(!lv(Ve.resolve(e.runtimeDir),Ve.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await LC.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=BC(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=zu(t.executable,t.argv,{cwd:r,env:process.env})}catch(m){o.destroy(),c(m);return}let f=!1,u=null,d=null,h=Promise.resolve(),v=!1,p=setTimeout(()=>{f=!0,Zn(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(p.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",m=>{u=m,o.write(`
170
+ # 可选值:true | false`}}});import{constants as rs,promises as Fr}from"fs";function Cu(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function zm(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function qn(e){return{dev:e.dev,ino:e.ino,birthtime:Cu(e)}}function is(e,t){let r=qn(e),i=qn(t);return nt(r,i)?J(r,i):J(r,i)&&Cu(e)===Cu(t)&&zm(e)===zm(t)&&e.size===t.size}async function Ai(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Fr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ct("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ct("too-large",`${i} exceeds ${t} bytes`);let o=await Fr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:qn(a)});let s=process.platform==="win32"?rs.O_RDONLY:rs.O_RDONLY|rs.O_NOFOLLOW|rs.O_NONBLOCK,c;try{c=await Fr.open(e,s)}catch(l){throw l.code==="ELOOP"?new ct("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),Fr.lstat(e,{bigint:n}),Fr.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!is(a,l)||!is(a,f))throw new ct("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:qn(l)}),await r.hooks?.afterOpen?.();let d=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,w),null);if(y===0)break;if(h+=y,h>t)throw new ct("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[p,m,g]=await Promise.all([c.stat({bigint:n}),Fr.lstat(e,{bigint:n}),Fr.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!is(a,p)||!is(a,m))throw new ct("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:qn(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:g}}finally{await c.close()}}var ct,Wn=C(()=>{"use strict";Dn();ct=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as ns}from"fs";import gr from"path";function _x(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Pu(e,t){let r=gr.relative(e,t);return r===""||!gr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${gr.sep}`)}async function Jm(e,t){let r=gr.resolve(e),i=await ns.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ns.realpath(r)}async function Gm(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=gr.join(n,r[a]);let o;try{o=await ns.lstat(n)}catch(f){if(_x(f))return{exists:!1,kind:"missing"};throw f}let s=gr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await ns.realpath(n);if(!Pu(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function _i(e,t,r){let i=Zo(t,r.label),n=gr.resolve(e),a=await Jm(n,r.label),o=i.split("/"),s=gr.resolve(n,...o);if(!Pu(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Gm(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function wr(e,t,r,i){let n=await _i(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Jm(n.projectRoot,i.label);return Ai(n.target,r,{...i,verify:async(o,s)=>{if(!Pu(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Gm(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var qr=C(()=>{"use strict";Wn();vr()});import{createHash as Ix}from"crypto";function Ru(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Tx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function as(e,t={}){return(await Jn(e,t)).document}async function Um(e){try{return(await wr(e,zn,Vn,{label:zn})).bytes}catch(t){if(Tx(t))return null;throw t}}function Km(e){return e?{exists:!0,sha256:Ix("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function os(e){return Km(await Um(e))}async function Jn(e,t={}){let r=await Um(e);return{document:r?Ri(r.toString("utf8"),t):null,identity:Km(r)}}async function Au(e){return(await as(e))?.config??null}var zn,Ii=C(()=>{"use strict";vr();qr();zn=".comet/config.yaml"});var Ti=C(()=>{"use strict";Dn()});var I$,_u=C(()=>{"use strict";Ti();Ii();qr();I$=16*1024});async function Iu(e,t){if(!t)return;let r=await os(e);if(!Ru(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Tu=C(()=>{"use strict";Ti();vr();Ii();qr();_u()});import{randomUUID as Hx}from"crypto";import{promises as oe}from"fs";import lt from"path";function ss(e,t){let r=lt.relative(e,t);return r===""||!lt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${lt.sep}`)}function Dx(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function cs(e,t){return J({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Bx(e,t){return cs(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ym(e){let t=await oe.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 oe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ji(e){for(let t of e){let r=await oe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Dx(t,r)||await oe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Lx(e,t,r){let[i,n]=await Promise.all([oe.lstat(e),oe.realpath(e),r?ji(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!cs(i,t)||r&&!ss(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Vx(e,t){let r=lt.resolve(e),i=lt.resolve(t);if(!ss(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Ym(r)],a=lt.relative(r,i).split(lt.sep).filter(Boolean),o=r;for(let s of a){await ji(n),o=lt.join(o,s);try{await oe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ym(o);if(!ss(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ji(n),n}async function Mx(e){let t;try{t=await oe.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Fx(e,t,r={}){let i=lt.dirname(e),n=r.containedRoot?await Vx(r.containedRoot,i):null;n||await oe.mkdir(i,{recursive:!0});let a=lt.join(i,`.${lt.basename(e)}.${Hx()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await oe.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([oe.lstat(a),oe.realpath(a)]);if(await ji(n),!l.isFile()||l.isSymbolicLink()||!cs(s,l)||!ss(n[0].realPath,f))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!cs(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Lx(a,c,n),await r.beforeCommit?.(),n){await ji(n);let l=await oe.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Bx(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await oe.link(a,e),await oe.unlink(a)):await oe.rename(a,e),await Mx(i)}catch(l){if(await o?.close(),!n)await oe.rm(a,{force:!0});else try{await ji(n),await oe.rm(a,{force:!0})}catch{}throw l}}async function Je(e,t,r={}){await Fx(e,t,r)}async function pe(e,t,r={}){await Je(e,JSON.stringify(t,null,2)+`
171
+ `,r)}var Q=C(()=>{"use strict";Nt()});import{existsSync as Xm,promises as Wr}from"fs";import B from"path";import qx from"os";async function ju(e){try{return await Wr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function zx(e){try{let t=await Wr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Oi(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function $i(e){let t=[],r=e;for(;!await ju(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await Wr.realpath(r);return B.resolve(i,...t.reverse())}async function $u(e){try{return(await Wr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ls(e){let t=B.resolve(e);try{(await Wr.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(qx.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...Un.split("/")),s=t===r||await zx(o);if(await ju(o)&&s)return t}if(await ju(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function us(e){return Mr(e)}async function Jx(e,t){let r=us(t),i=B.resolve(e,...r.split("/")),n=await Wr.realpath(e),a=await $i(i);if(!Oi(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function yr(e,t){let r=us(t),i=await Jx(e,r),n=B.join(i,"comet");if(await $u(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([$i(i),$i(n)]);if(!Oi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await $u(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Wr.realpath(s),$i(c)]);if(!Oi(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...Un.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Qm(e){if(!Wx.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ke(e,t){Qm(t);let r=B.join(e.changesRuntimeDir,t);if(!ge(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ou(e,t){Qm(t);let r=B.join(e.changesDir,t,"runtime");if(!ge(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ge(e,t){let r=ke(e,t);if(Xm(r))return r;let i=Ou(e,t);return Xm(i)?i:r}function Hu(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!ge(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ie(e,t){let r=B.resolve(t);if(ge(e.runtimeDir,r))return e.runtimeDir;if(ge(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ge(e,t){return Oi(B.resolve(e),B.resolve(t))}async function U(e,t){let r=B.resolve(e),i=B.resolve(t);if(!Oi(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await $u(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([$i(r),$i(i)]);if(!Oi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Un,Wx,K=C(()=>{"use strict";vr();Un=".comet/config.yaml",Wx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import Gx from"path";function Ux(e="docs",t="en"){return ts(e,t)}async function Te(e){let t=(await as(e))?.config??null;return t?.native?t:null}async function fs(e){let t=await Te(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 ps(e,t,r={}){let i=await Jn(e,{allowPartialProject:!0}),n=Fn(i.document?.value??{},t),a=Gx.join(e,...Un.split("/"));await Je(a,Mn(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Iu(e,i.identity)}})}async function Zm(e){let t=await ls(e.startPath),r=await Te(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Un} 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 i=e.explicitArtifactRoot?us(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Ux(i??"docs"),a=await yr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var ds,ut=C(()=>{"use strict";vr();Ii();Tu();Q();K();ds=es});function ms(){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 zr,Kn,hs,Hi=C(()=>{"use strict";zr="comet.native.v4",Kn="comet.native.local-execution.v4",hs=["multi-session","single-session"]});var Vu={};Ga(Vu,{NativePortableStateVersionConflictError:()=>Yn,appendNativePortableHistory:()=>we,compareAndSwapNativePortableState:()=>Li,createNativePortableState:()=>rv,parseNativePortableState:()=>I,readNativePortableState:()=>Be,writeNativePortableState:()=>Xn});import{promises as Kx}from"node:fs";function Se(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ee(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function se(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 Bu(e,t){return e===null?null:se(e,t)}function ev(e,t){let r=se(e,t);if(!Zx.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Di(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Y(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 tC(e,t){return e===null?null:Y(e,t,Number.MIN_SAFE_INTEGER)}function te(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function bt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function ws(e,t){return bt(e,t,(r,i)=>se(r,`${t}[${i}]`))}function Jr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Bi(e,t){let r=se(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Lu(e,t,r=!1){let i=se(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Ue(e,t){let r=Se(e,t);return Ee(r,new Set(["text","truncated"]),t),{text:se(r.text,`${t}.text`,{empty:!0}),truncated:Di(r.truncated,`${t}.truncated`)}}function rC(e,t){let r=`Native spec_changes[${t}]`,i=Se(e,r);Ee(i,new Set(["capability","operation","source"]),r);let n=se(i.capability,`${r}.capability`);if(!Xx.test(n))throw new Error(`${r}.capability is invalid`);let a=te(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Lu(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function iC(e){let t="Native workspace",r=Se(e,t);Ee(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=te(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Bu(r.change_branch,`${t}.change_branch`),a=Bu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:te(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function nC(e){let t="Native loop",r=Se(e,t);Ee(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 i=ws(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Jr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:te(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:te(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:Y(r.goal_cycle,`${t}.goal_cycle`,1),iteration:Y(r.iteration,`${t}.iteration`),attempt:Y(r.attempt,`${t}.attempt`),retry_epoch:Y(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:Y(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:Y(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:Y(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Bu(r.next_action,`${t}.next_action`)}}function aC(e,t){let r=`Native acceptance[${t}]`,i=Se(e,r);Ee(i,new Set(["id","source","text","result","reason"]),r);let n=se(i.id,`${r}.id`);if(!Qx.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Lu(i.source,`${r}.source`),text:se(i.text,`${r}.text`),result:te(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ue(i.reason,`${r}.reason`)}}function oC(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Se(e,r);return Ee(i,new Set(["name","result","note"]),r),{name:Ue(i.name,`${r}.name`),result:te(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ue(i.note,`${r}.note`)}}function sC(e){let t="Native builder_handoff",r=Se(e,t);Ee(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=ws(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Jr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Se(r.review,`${t}.review`);return n&&Ee(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:se(r.candidate_id,`${t}.candidate_id`),identity_provider:se(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:se(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:Y(r.iteration,`${t}.iteration`,1),summary:Ue(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:bt(r.checks,`${t}.checks`,oC),checks_truncated:Di(r.checks_truncated,`${t}.checks_truncated`),known_limits:bt(r.known_limits,`${t}.known_limits`,(a,o)=>Ue(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Di(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:te(n.status,["passed"],`${t}.review.status`),summary:Ue(n.summary,`${t}.review.summary`),reviewer_execution_ref:se(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Bi(r.submitted_at,`${t}.submitted_at`)}}function cC(e,t){let r=`Native blockers[${t}]`,i=Se(e,r);Ee(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ws(i.acceptance_ids,`${r}.acceptance_ids`);return Jr(n,`${r}.acceptance_ids`),{owner:te(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ue(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:te(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function lC(e,t){let r=`Native verification.checks[${t}]`,i=Se(e,r);return Ee(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:se(i.id,`${r}.id`),name:Ue(i.name,`${r}.name`),argv_display:bt(i.argv_display,`${r}.argv_display`,(n,a)=>Ue(n,`${r}.argv_display[${a}]`)),argv_truncated:Di(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Lu(i.cwd_ref,`${r}.cwd_ref`,!0),status:te(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:tC(i.exit_code,`${r}.exit_code`),duration_ms:Y(i.duration_ms,`${r}.duration_ms`)}}function uC(e){let t="Native verification",r=Se(e,t);Ee(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=bt(r.checks,`${t}.checks`,lC);Jr(i.map(a=>a.id),`${t}.checks IDs`);let n=se(r.identity_provider,`${t}.identity_provider`);return{candidate_id:se(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:se(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:Y(r.iteration,`${t}.iteration`,1),attempt:Y(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":te(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:te(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ue(r.summary,`${t}.summary`),risks:bt(r.risks,`${t}.risks`,(a,o)=>Ue(a,`${t}.risks[${o}]`)),risks_truncated:Di(r.risks_truncated,`${t}.risks_truncated`),completed_at:Bi(r.completed_at,`${t}.completed_at`)}}function tv(e,t){let r=`Native history[${t}]`,i=Se(e,r);Ee(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ws(i.unresolved_ids,`${r}.unresolved_ids`);return Jr(n,`${r}.unresolved_ids`),{goal_cycle:Y(i.goal_cycle,`${r}.goal_cycle`,1),iteration:Y(i.iteration,`${r}.iteration`),attempt:Y(i.attempt,`${r}.attempt`),outcome:te(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ue(i.summary,`${r}.summary`),completed_at:Bi(i.completed_at,`${r}.completed_at`)}}function dC(e){let t="Native history_overflow.outcome_counts",r=Se(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ee(r,new Set(i),t),{pass:Y(r.pass,`${t}.pass`),fail:Y(r.fail,`${t}.fail`),blocked:Y(r.blocked,`${t}.blocked`),"execution-error":Y(r["execution-error"],`${t}.execution-error`),recovery:Y(r.recovery,`${t}.recovery`)}}function fC(e){let t="Native history_overflow",r=Se(e,t);Ee(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=Y(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Bi(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Bi(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=dC(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function pC(e){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}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);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");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");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.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function hC(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(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.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 I(e){let t=Se(e,"Native portable state");if(Ee(t,eC,"Native portable state"),t.schema!==zr)throw new Error(`Native portable state schema must be ${zr}`);let r=se(t.name,"Native state name");if(!Yx.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 i=bt(t.spec_changes,"Native spec_changes",rC);Jr(i.map(s=>s.capability),"Native spec change capabilities");let n=bt(t.acceptance,"Native acceptance",aC);Jr(n.map(s=>s.id),"Native acceptance IDs");let a=bt(t.history,"Native history",tv);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:zr,name:r,language:te(t.language,["en","zh-CN"],"Native state language"),phase:te(t.phase,["shape","build","verify","archive"],"Native state phase"),status:te(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:Y(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:ev(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:ev(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:te(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:iC(t.workspace),loop:nC(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:sC(t.builder_handoff),blockers:bt(t.blockers,"Native blockers",cC),verification:t.verification===null?null:uC(t.verification),history:a,history_overflow:fC(t.history_overflow),verification_result:te(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:te(t.verification_report,["verification.md"],"Native verification_report"),archived:Di(t.archived,"Native archived"),created_at:Bi(t.created_at,"Native created_at")};return pC(o),hC(o),o}function rv(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return I({schema:zr,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:ms(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function we(e,t){let r=I(e),i=tv(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return I({...r,history:n,history_overflow:a})}function mC(e,t){let r=(0,gs.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})}async function Be(e){let t=await Kx.readFile(e,"utf8");return I(mC(t,"Native portable state"))}async function Xn(e,t,r={}){let i=I(t);await Je(e,(0,gs.stringify)(i),r)}async function vC(e,t){let r=vs.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);vs.set(e,a),await r;try{return await t()}finally{i(),vs.get(e)===a&&vs.delete(e)}}async function Li(e){return vC(e.file,async()=>{let t=Y(e.expectedStateVersion,"Native expected state version",1),r=I(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Be(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Yn(t,i.state_version);return await Xn(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Be(e.file);if(n.state_version!==t)throw new Yn(t,n.state_version)}}),r})}var gs,Yx,Xx,Qx,Zx,eC,Yn,vs,qt=C(()=>{"use strict";gs=nn(Si(),1);Q();Hi();Yx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Qx=/^A[1-9][0-9]*$/u,Zx=/^[a-f0-9]{64}$/u,eC=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Yn=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};vs=new Map});import{createHash as gC}from"node:crypto";import{lstatSync as wC,readFileSync as iv,promises as nv}from"node:fs";import ys from"node:path";function yC(e){try{if(T(e,["ls-files","--",Ns]))return!1;let t=ys.join(e,Ns),r=wC(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(iv(av(e),"utf8")).hash===ov(iv(t))}catch{return!1}}async function sv(e){let t=ys.join(e,Ns),r;try{r=await nv.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=av(e);await nv.mkdir(ys.dirname(i),{recursive:!0}),await pe(i,{hash:ov(r)},{containedRoot:e})}function Wt(e,t=[]){return jm(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===Ns&&yC(e))}var Ns,av,ov,Qn=C(()=>{"use strict";Vr();Q();Ns=".comet/config.yaml",av=e=>ys.join(e,".comet","runtime","native","workspace-config.json"),ov=e=>gC("sha256").update(e).digest("hex")});import{spawn as Mu}from"node:child_process";import{existsSync as cv}from"node:fs";import Gr from"node:path";function Fu(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function EC(e){let t=(Fu(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function xC(e,t,r){let n=Gr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Fu(t,"PATH")??"").split(Gr.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Gr.win32.extname(e)?[e]:EC(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Gr.join(s,c):Gr.resolve(r,c)))}function qu(e,t,r){return xC(e,t,r).find(i=>cv(i))??e}function CC(e){let t=Fu(e,"SystemRoot");if(t){let r=Gr.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(cv(r))return r}return"powershell.exe"}function Wu(e){if(e.some(t=>kC.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function PC(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(SC,"utf16le").toString("base64");return Mu(CC(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function zu(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Mu(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=qu(e,i,r.cwd),a=Gr.win32.extname(n).toLowerCase();return bC.has(a)&&Wu(t),NC.has(a)?PC(n,t,{cwd:r.cwd,env:i}):Mu(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var NC,bC,kC,SC,bs=C(()=>{"use strict";NC=new Set([".bat",".cmd",".ps1"]),bC=new Set([".bat",".cmd"]),kC=/[&|<>()^%"!\r\n]/u,SC=["$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 RC}from"node:child_process";import Ju from"node:path";async function Zn(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&Ju.win32.isAbsolute(r)?Ju.win32.resolve(r):"C:\\Windows",n=Ju.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(u,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(u))};try{c=RC(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",u=>f(u===0)),l=setTimeout(()=>f(!1,!0),AC)}catch{f(!1)}});for(let o=0;o<_C;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var AC,_C,Gu=C(()=>{"use strict";AC=1e3,_C=2});function Le(e){return e.replace(IC,"$1 [REDACTED]").replace(TC,"[REDACTED PRIVATE KEY]").replace(jC,"$1[REDACTED]@").replace($C,"[REDACTED TOKEN]").replace(OC,'$1"[REDACTED]"').replace(HC,"$1$2$1$3$4[REDACTED]$4").replace(DC,"$1$2[REDACTED]")}var IC,TC,jC,$C,OC,HC,DC,Nr=C(()=>{"use strict";IC=/\b(Bearer|Basic)\s+[^\s"']+/giu,TC=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,jC=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,$C=/\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,OC=/("(?:[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,HC=/(["'])((?:[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,DC=/\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{createWriteStream as BC,promises as LC}from"node:fs";import Ve from"node:path";function lv(e,t){let r=Ve.relative(e,t);return r===""||!Ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ve.sep}`)}function uv(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function ks(e,t){if(t.length===0||t.includes("\\")||Ve.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Ve.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Ve.resolve(e),i=Ve.resolve(r,...t.split("/"));if(!lv(r,i))throw new Error("Native check cwd escaped the project root");return i}function ea(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function Uu(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Le(r);return VC.test(r)&&(t=!0),i})}function br(e,t){if(uv(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return ks(e,t.cwdRef)}async function Ur(e){let{plan:t}=e;uv(e.operationId,"Native check operation ID");let r=br(e.projectRoot,t),i=Ve.join(e.runtimeDir,"logs","checks"),n=Ve.join(i,`${e.operationId}-${t.id}.log`);if(!lv(Ve.resolve(e.runtimeDir),Ve.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await LC.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=BC(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=zu(t.executable,t.argv,{cwd:r,env:process.env})}catch(m){o.destroy(),c(m);return}let f=!1,u=null,d=null,h=Promise.resolve(),v=!1,p=setTimeout(()=>{f=!0,Zn(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(p.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",m=>{u=m,o.write(`
172
172
  [comet] failed to start check: ${Le(m.message)}
173
- `)}),l.once("close",(m,g)=>{v=!0,clearTimeout(p);let w=(e.now??(()=>new Date))();h.then(()=>{if(d!==null){o.destroy(),c(d);return}o.end(()=>{let y=f||u!==null||g!==null;s({id:t.id,name:t.name,argvDisplay:Uu(t.argv),cwdRef:t.cwdRef,status:y?"interrupted":m===0?"passed":"failed",exitCode:m,signal:g,timedOut:f,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:Ve.relative(e.runtimeDir,n).split(Ve.sep).join("/")})})})}),o.once("error",m=>{clearTimeout(p),d??=m,v?h.then(()=>c(d)):Zn(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let m=l.pid;h=Promise.resolve().then(()=>e.onSpawn({pid:m})).catch(async g=>{d=g,l.exitCode===null&&l.signalCode===null&&await Zn(l).catch(()=>l.kill("SIGKILL"))})}})}var VC,Ss=C(()=>{"use strict";bs();Gu();Nr();VC=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});function Ku(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Yu(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){Ku(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:ne,executionRef:Ku(t.executionRef,"Native execution ref"),[dv]:!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:Ku(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[fv]:!0})}})}function Es(e){return typeof e=="object"&&e!==null&&e[fv]===!0}function pv(e){return typeof e=="object"&&e!==null&&e[dv]===!0}var dv,fv,ne,Kr=C(()=>{"use strict";dv=Symbol("comet.native.trusted-execution-identity"),fv=Symbol("comet.native.trusted-verifier-envelope"),ne="skill-coordinated"});function xs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ta(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ra(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Yr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Cs(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=xs(t,`Native Verifier acceptance ${r}`);ta(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=Yr(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:Yr(i.reason,`Native Verifier acceptance ${n} reason`)}})}function MC(e){let t=xs(e,"Native Verifier final result");if(ta(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:ra(t.iteration,"Native Verifier iteration"),attempt:ra(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:Cs(t.acceptance),risks:t.risks,summary:Yr(t.summary,"Native Verifier summary")}}function FC(e,t){let r=xs(e,`Native Verifier check request ${t}`);if(ta(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=ra(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:Yr(r.id,`Native Verifier check request ${t} ID`),name:Yr(r.name,`Native Verifier check request ${t} name`),executable:Yr(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:Yr(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function Xu(e){let t=xs(e,"Native Verifier response");if(t.kind==="final-result")return ta(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:MC(t.result)};if(t.kind==="request-checks"){if(ta(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:ra(t.iteration,"Native Verifier iteration"),attempt:ra(t.attempt,"Native Verifier attempt"),checks:t.checks.map(FC)}}throw new Error("Native Verifier response kind is invalid")}function hv(e){if(!Es(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(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=Xu(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");return i.kind==="request-checks"||Qu(i.result,r),i}function Qu(e,t){Cs(e.acceptance);let r=[...t.acceptanceIds],i=e.acceptance.map(({id:c})=>c),n=i.filter((c,l)=>i.indexOf(c)!==l),a=i.filter(c=>!r.includes(c)),o=r.filter(c=>!i.includes(c));if(n.length>0||a.length>0||o.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(n)].join(", ")||"none"}; unknown: ${a.join(", ")||"none"}; missing: ${o.join(", ")||"none"})`);if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let s=e.acceptance.map(({result:c})=>c);if(e.verdict==="pass"&&s.some(c=>c!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!s.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!s.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion")}var ia=C(()=>{"use strict";Kr()});import{AsyncLocalStorage as qC}from"async_hooks";import{randomUUID as gv}from"crypto";import{promises as Ke}from"fs";import wv from"os";import ce from"path";function zC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function JC(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Nv(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Rs(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return it(r,i)?J(r,i):J(r,i)&&e.size===t.size}function Zu(e,t){return Rs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function bt(e){let t,r;try{let i=await Ai(e,mv,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof st?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${mv} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:JC(JSON.parse(t.toString("utf8")),e),identity:Nv(r)}}async function GC(e){return(await bt(e))?.owner??null}function bv(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==wv.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=ZC(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function UC(e,t){try{await Ke.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Ke.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function ed(e,t){let r=await bt(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Zu(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ke.mkdir(t,{recursive:!0});let i=ce.join(t,`${ce.basename(e.file)}.${e.owner.id}.${gv()}.removed`);try{await Ke.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await bt(i);if(!n||n.owner.id!==e.owner.id||!Rs(n.identity,e.identity))throw await UC(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ke.rm(i,{force:!0}),"removed"}function kv(e){return{id:gv(),pid:process.pid,hostname:wv.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Sv(e,t){let r;try{r=await Ke.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await GC(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
174
- `,"utf8"),await r.sync(),i=Nv(await r.stat({bigint:!0}))}finally{await r.close()}let n=await bt(e);if(!i||!n||n.owner.id!==t.id||!Rs(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function KC(e,t){let r=await U(e.runtimeDir,e.locksDir);await Ke.mkdir(r,{recursive:!0});let i=await U(e.runtimeDir,ce.join(r,yv));await Ke.mkdir(i,{recursive:!0});let n=kv(t),a=ce.join(i,`.${n.id}.tmp`),o=ce.join(i,`${n.id}.claim`);try{let s=await Sv(a,n);await Ke.rename(a,o);let c=await bt(o);if(!c||!Rs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Ke.rm(a,{force:!0})}}async function YC(e){let t=ce.dirname(e.file),r=!1,i=ce.basename(e.file);for(let n of await Ke.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ce.join(t,n.name);if(ce.resolve(a)!==ce.resolve(e.file))try{let o=await bt(a),s=bv(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ed(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Ev(e){let t=await bt(e.file);if(t){if(t.owner.id!==e.owner.id||!Zu(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ed(t,ce.dirname(e.file))}}async function XC(e,t){let r=Date.now()+WC;for(;;){let i=await KC(e,t);if(!await YC(i))return i;if(await Ev(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function QC(e){let t=Ps.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ps.set(e,n),await t,()=>{r(),Ps.get(e)===n&&Ps.delete(e)}}async function td(e,t,r){let i=ce.resolve(e.locksDir),n=vv.getStore();if(n?.has(i))return r();let a=await QC(i);try{let o=await XC(e,t),s=new Map(n??[]);return s.set(i,o),await vv.run(s,async()=>{try{return await r()}finally{await Ev(o)}})}finally{a()}}async function xv(e,t,r){let i=[...new Map(e.map(a=>[ce.resolve(a.locksDir),a])).values()].sort((a,o)=>ce.resolve(a.locksDir).localeCompare(ce.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?td(o,t,()=>n(a+1)):r()};return n(0)}async function As(e,t,r){return td(e,`acquire ${t}`,async()=>{let i=await U(e.runtimeDir,e.locksDir);await Ke.mkdir(i,{recursive:!0});let n=await U(e.runtimeDir,ce.join(i,zC(t))),a=kv(r),o=await Sv(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function _s(e){await bt(e.file)&&await td({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ce.basename(e.file)}`,async()=>{let t=await bt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Zu(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ce.join(e.locksDir,yv);await ed(t,r)})}function ZC(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Cv(e){return bv(await bt(e))}var mv,yv,WC,vv,Ps,na=C(()=>{"use strict";Wn();K();yt();mv=16*1024,yv=".coordinator",WC=5e3,vv=new qC,Ps=new Map});function eP(e,t){return rd[e][t]}function id(e,t){return Rv[e][t]??Av[e][t]}function nd(e){return _v.get(e.trim().toLocaleLowerCase("en-US"))??null}function Is(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${eP(e,r)}
173
+ `)}),l.once("close",(m,g)=>{v=!0,clearTimeout(p);let w=(e.now??(()=>new Date))();h.then(()=>{if(d!==null){o.destroy(),c(d);return}o.end(()=>{let y=f||u!==null||g!==null;s({id:t.id,name:t.name,argvDisplay:Uu(t.argv),cwdRef:t.cwdRef,status:y?"interrupted":m===0?"passed":"failed",exitCode:m,signal:g,timedOut:f,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:Ve.relative(e.runtimeDir,n).split(Ve.sep).join("/")})})})}),o.once("error",m=>{clearTimeout(p),d??=m,v?h.then(()=>c(d)):Zn(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let m=l.pid;h=Promise.resolve().then(()=>e.onSpawn({pid:m})).catch(async g=>{d=g,l.exitCode===null&&l.signalCode===null&&await Zn(l).catch(()=>l.kill("SIGKILL"))})}})}var VC,Ss=C(()=>{"use strict";bs();Gu();Nr();VC=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});function Ku(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Yu(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){Ku(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:ne,executionRef:Ku(t.executionRef,"Native execution ref"),[dv]:!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:Ku(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[fv]:!0})}})}function Es(e){return typeof e=="object"&&e!==null&&e[fv]===!0}function pv(e){return typeof e=="object"&&e!==null&&e[dv]===!0}var dv,fv,ne,Kr=C(()=>{"use strict";dv=Symbol("comet.native.trusted-execution-identity"),fv=Symbol("comet.native.trusted-verifier-envelope"),ne="skill-coordinated"});function xs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ta(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ra(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Yr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Cs(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=xs(t,`Native Verifier acceptance ${r}`);ta(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=Yr(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:Yr(i.reason,`Native Verifier acceptance ${n} reason`)}})}function MC(e){let t=xs(e,"Native Verifier final result");if(ta(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:ra(t.iteration,"Native Verifier iteration"),attempt:ra(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:Cs(t.acceptance),risks:t.risks,summary:Yr(t.summary,"Native Verifier summary")}}function FC(e,t){let r=xs(e,`Native Verifier check request ${t}`);if(ta(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=ra(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:Yr(r.id,`Native Verifier check request ${t} ID`),name:Yr(r.name,`Native Verifier check request ${t} name`),executable:Yr(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:Yr(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function Xu(e){let t=xs(e,"Native Verifier response");if(t.kind==="final-result")return ta(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:MC(t.result)};if(t.kind==="request-checks"){if(ta(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:ra(t.iteration,"Native Verifier iteration"),attempt:ra(t.attempt,"Native Verifier attempt"),checks:t.checks.map(FC)}}throw new Error("Native Verifier response kind is invalid")}function hv(e){if(!Es(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(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=Xu(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");return i.kind==="request-checks"||Qu(i.result,r),i}function Qu(e,t){Cs(e.acceptance);let r=[...t.acceptanceIds],i=e.acceptance.map(({id:c})=>c),n=i.filter((c,l)=>i.indexOf(c)!==l),a=i.filter(c=>!r.includes(c)),o=r.filter(c=>!i.includes(c));if(n.length>0||a.length>0||o.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(n)].join(", ")||"none"}; unknown: ${a.join(", ")||"none"}; missing: ${o.join(", ")||"none"})`);if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let s=e.acceptance.map(({result:c})=>c);if(e.verdict==="pass"&&s.some(c=>c!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!s.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!s.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion")}var ia=C(()=>{"use strict";Kr()});import{AsyncLocalStorage as qC}from"async_hooks";import{randomUUID as gv}from"crypto";import{promises as Ke}from"fs";import wv from"os";import ce from"path";function zC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function JC(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Nv(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Rs(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return nt(r,i)?J(r,i):J(r,i)&&e.size===t.size}function Zu(e,t){return Rs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function kt(e){let t,r;try{let i=await Ai(e,mv,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof ct?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${mv} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:JC(JSON.parse(t.toString("utf8")),e),identity:Nv(r)}}async function GC(e){return(await kt(e))?.owner??null}function bv(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==wv.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=ZC(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function UC(e,t){try{await Ke.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Ke.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function ed(e,t){let r=await kt(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Zu(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ke.mkdir(t,{recursive:!0});let i=ce.join(t,`${ce.basename(e.file)}.${e.owner.id}.${gv()}.removed`);try{await Ke.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await kt(i);if(!n||n.owner.id!==e.owner.id||!Rs(n.identity,e.identity))throw await UC(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ke.rm(i,{force:!0}),"removed"}function kv(e){return{id:gv(),pid:process.pid,hostname:wv.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Sv(e,t){let r;try{r=await Ke.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await GC(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
174
+ `,"utf8"),await r.sync(),i=Nv(await r.stat({bigint:!0}))}finally{await r.close()}let n=await kt(e);if(!i||!n||n.owner.id!==t.id||!Rs(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function KC(e,t){let r=await U(e.runtimeDir,e.locksDir);await Ke.mkdir(r,{recursive:!0});let i=await U(e.runtimeDir,ce.join(r,yv));await Ke.mkdir(i,{recursive:!0});let n=kv(t),a=ce.join(i,`.${n.id}.tmp`),o=ce.join(i,`${n.id}.claim`);try{let s=await Sv(a,n);await Ke.rename(a,o);let c=await kt(o);if(!c||!Rs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Ke.rm(a,{force:!0})}}async function YC(e){let t=ce.dirname(e.file),r=!1,i=ce.basename(e.file);for(let n of await Ke.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ce.join(t,n.name);if(ce.resolve(a)!==ce.resolve(e.file))try{let o=await kt(a),s=bv(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ed(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Ev(e){let t=await kt(e.file);if(t){if(t.owner.id!==e.owner.id||!Zu(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ed(t,ce.dirname(e.file))}}async function XC(e,t){let r=Date.now()+WC;for(;;){let i=await KC(e,t);if(!await YC(i))return i;if(await Ev(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function QC(e){let t=Ps.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ps.set(e,n),await t,()=>{r(),Ps.get(e)===n&&Ps.delete(e)}}async function td(e,t,r){let i=ce.resolve(e.locksDir),n=vv.getStore();if(n?.has(i))return r();let a=await QC(i);try{let o=await XC(e,t),s=new Map(n??[]);return s.set(i,o),await vv.run(s,async()=>{try{return await r()}finally{await Ev(o)}})}finally{a()}}async function xv(e,t,r){let i=[...new Map(e.map(a=>[ce.resolve(a.locksDir),a])).values()].sort((a,o)=>ce.resolve(a.locksDir).localeCompare(ce.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?td(o,t,()=>n(a+1)):r()};return n(0)}async function As(e,t,r){return td(e,`acquire ${t}`,async()=>{let i=await U(e.runtimeDir,e.locksDir);await Ke.mkdir(i,{recursive:!0});let n=await U(e.runtimeDir,ce.join(i,zC(t))),a=kv(r),o=await Sv(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function _s(e){await kt(e.file)&&await td({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ce.basename(e.file)}`,async()=>{let t=await kt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Zu(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ce.join(e.locksDir,yv);await ed(t,r)})}function ZC(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Cv(e){return bv(await kt(e))}var mv,yv,WC,vv,Ps,na=C(()=>{"use strict";Wn();K();Nt();mv=16*1024,yv=".coordinator",WC=5e3,vv=new qC,Ps=new Map});function eP(e,t){return rd[e][t]}function id(e,t){return Rv[e][t]??Av[e][t]}function nd(e){return _v.get(e.trim().toLocaleLowerCase("en-US"))??null}function Is(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${eP(e,r)}
175
175
  `).join(`
176
- `)}function je(e,t,r){return e==="zh-CN"?r:t}var rd,Rv,Av,_v,Pv,Xr=C(()=>{"use strict";rd={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:"验证预期"}},Rv={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:"结论"}},Av={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:"结论"}},_v=new Map,Pv=new Map;for(let e of Object.keys(rd)){for(let[t,r]of Object.entries(rd[e]))_v.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Rv[e]))Pv.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Av[e]))Pv.set(r.toLocaleLowerCase("en-US"),t)}});import{createHash as tP}from"node:crypto";import{constants as Ts,promises as ut}from"node:fs";import dt from"node:path";function $s(e,t){let r=dt.relative(e,t);return r===""||!dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${dt.sep}`)}function rP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function iP(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function js(e,t){return J({...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 ad(e,t){let r=await ut.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ut.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function aP(e,t,r){let i=dt.resolve(e),n=dt.resolve(t);if(!$s(i,n))throw new Error(`${r} is outside its managed root`);let a=[await ad(i,r)],o=i;for(let s of dt.relative(i,n).split(dt.sep).filter(Boolean)){await Qr(a,r),o=dt.join(o,s);let c=await ad(o,r);if(!$s(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Qr(a,r),a}async function Qr(e,t){for(let r of e){let i=await ut.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!iP(r,i)||await ut.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function oP(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Vi(e){let t=rP(e.maxBytes),r=dt.resolve(e.file),i=await aP(e.root,dt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>ad(dt.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Qr(i,e.label);let a=await ut.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=nP(a),s=await ut.realpath(r);if(!$s(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>$s(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ts.O_RDONLY:Ts.O_RDONLY|Ts.O_NOFOLLOW|Ts.O_NONBLOCK,l=await ut.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([ut.lstat(r),ut.realpath(r)]);if(await Qr(i,e.label),await Qr(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!js(o,f)||!js(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await oP(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),ut.lstat(r),ut.realpath(r)]);if(await Qr(i,e.label),await Qr(n,e.label),!p.isFile()||p.isSymbolicLink()||m!==s||!js(o,v)||!js(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:tP("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}var kt=C(()=>{"use strict";Q();yt()});var Iv=C(()=>{"use strict"});import{createHash as sP}from"crypto";function Me(e){return sP("sha256").update(e).digest("hex")}var St=C(()=>{"use strict"});import Tv from"path";function Os(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function CP(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function PP(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
176
+ `)}function je(e,t,r){return e==="zh-CN"?r:t}var rd,Rv,Av,_v,Pv,Xr=C(()=>{"use strict";rd={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:"验证预期"}},Rv={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:"结论"}},Av={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:"结论"}},_v=new Map,Pv=new Map;for(let e of Object.keys(rd)){for(let[t,r]of Object.entries(rd[e]))_v.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Rv[e]))Pv.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Av[e]))Pv.set(r.toLocaleLowerCase("en-US"),t)}});import{createHash as tP}from"node:crypto";import{constants as Ts,promises as dt}from"node:fs";import ft from"node:path";function $s(e,t){let r=ft.relative(e,t);return r===""||!ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ft.sep}`)}function rP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function iP(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function js(e,t){return J({...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 ad(e,t){let r=await dt.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await dt.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function aP(e,t,r){let i=ft.resolve(e),n=ft.resolve(t);if(!$s(i,n))throw new Error(`${r} is outside its managed root`);let a=[await ad(i,r)],o=i;for(let s of ft.relative(i,n).split(ft.sep).filter(Boolean)){await Qr(a,r),o=ft.join(o,s);let c=await ad(o,r);if(!$s(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Qr(a,r),a}async function Qr(e,t){for(let r of e){let i=await dt.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!iP(r,i)||await dt.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function oP(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Vi(e){let t=rP(e.maxBytes),r=ft.resolve(e.file),i=await aP(e.root,ft.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>ad(ft.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Qr(i,e.label);let a=await dt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=nP(a),s=await dt.realpath(r);if(!$s(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>$s(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ts.O_RDONLY:Ts.O_RDONLY|Ts.O_NOFOLLOW|Ts.O_NONBLOCK,l=await dt.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([dt.lstat(r),dt.realpath(r)]);if(await Qr(i,e.label),await Qr(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!js(o,f)||!js(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await oP(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),dt.lstat(r),dt.realpath(r)]);if(await Qr(i,e.label),await Qr(n,e.label),!p.isFile()||p.isSymbolicLink()||m!==s||!js(o,v)||!js(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:tP("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}var St=C(()=>{"use strict";Q();Nt()});var Iv=C(()=>{"use strict"});import{createHash as sP}from"crypto";function Me(e){return sP("sha256").update(e).digest("hex")}var Et=C(()=>{"use strict"});import Tv from"path";function Os(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function CP(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function PP(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
177
177
  `)}function RP(e,t){return Me(`comet.native.snapshot-policy.v1
178
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function od(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function AP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function jv(e){let t=ds(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?AP(n):void 0;if(a&&!a())return!1;let o=od(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let f=r[l];f&&(f.kind==="literal"&&f.value===s||f.kind==="question"&&s!=="/"?c.add(l+1):f.kind==="star"&&s!=="/"||f.kind==="globstar"?c.add(l):f.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=od(r,c,a),o===null||o.size===0)return!1}return od(r,o,a)?.has(r.length)??!1}}function _P(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ds(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>ds(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=RP(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(jv),excludeMatchers:r.map(jv),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xe(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Fi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Et(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hv(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=Tv.posix.normalize(e);if(r!==e||Tv.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function IP(e,t){let r=Ye(e,`Native snapshot entry ${t}`);Xe(r,yP,`Native snapshot entry ${t}`);let i=Hv(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Hs.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Et(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!xP.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function TP(e,t){let r=Ye(e,`Native snapshot omission ${t}`);if(Xe(r,NP,`Native snapshot omission ${t}`),!SP.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!EP.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Hv(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Et(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function jP(e){let t=Ye(e,"Native snapshot omission overflow");if(Xe(t,bP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Hs.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Fi(t.count,"Native snapshot omission overflow count")}}function Mi(e,t){let r=Ye(e,t);if(Xe(r,vP,t),typeof r.hash!="string"||!Hs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Et(r.recordCount,`${t} recordCount`),n=Et(r.storedRecordCount,`${t} storedRecordCount`),a=Et(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function $v(e){let t=Ye(e,"Native Git selection evidence");if(Xe(t,mP,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Mi(t.stageBefore,"Native Git selection stageBefore"),i=Mi(t.combined,"Native Git selection combined"),n=Mi(t.stageAfter,"Native Git selection stageAfter"),a=Mi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Mi(t.finalCombined,"Native Git selection finalCombined"),s=Mi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(u=>u.overflow),l=!Os(r,n)||!Os(n,a)||!Os(i,o)||!Os(a,s),f=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==f)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:f,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Ov(e,t){let r=Ye(e,t);if(Xe(r,wP,t),typeof r.hash!="string"||!Hs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Et(r.visitedNodeCount,`${t} visitedNodeCount`),n=Et(r.recordCount,`${t} recordCount`),a=Et(r.storedRecordCount,`${t} storedRecordCount`),o=Et(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function $P(e){let t=Ye(e,"Native physical selection evidence");if(Xe(t,gP,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Ov(t.before,"Native physical selection before"),i=Ov(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!CP(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function sd(e){let t=Ye(e,"Native content snapshot manifest");if(Xe(t,uP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!kP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let b=Ye(t.capture,"Native content snapshot capture");if(Xe(b,pP,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=b.gitSelection===void 0?void 0:$v(b.gitSelection),S=b.physicalSelection===void 0?void 0:$P(b.physicalSelection),E=null;if(b.projection!==void 0){let A=Ye(b.projection,"Native content snapshot projection");if(Xe(A,hP,"Native content snapshot projection"),A.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...A.selection===void 0?{}:{selection:$v(A.selection)}}}if(b.provider==="git"){if(S||E)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(S&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");r=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...S?{physicalSelection:S}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=Ye(t.limits,"Native content snapshot limits");Xe(i,dP,"Native content snapshot limits");let n={maxFiles:Fi(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Fi(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Fi(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Fi(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Fi(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Ye(t.policy,"Native snapshot policy");if(Xe(b,fP,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=_P({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(IP),s=t.omitted.map(TP),c=Et(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:jP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,P)=>b+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>lP||c<s.length)throw new Error("Native content snapshot omission count is invalid");let f=c-s.length;if(f===0&&l||f>0&&l?.count!==f)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(b=>b.reason==="git-enumeration-limit"),d=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...u,...d])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(u.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...g])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,y=w?.status==="overflow"||w?.status==="overflow-and-changed",N=w?.status==="changed"||w?.status==="overflow-and-changed";if(y!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(PP(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}var o0,lP,s0,uP,dP,fP,pP,hP,mP,vP,gP,wP,yP,NP,bP,kP,SP,EP,Hs,xP,c0,l0,u0,d0,f0,aa=C(()=>{"use strict";Q();lt();St();yt();K();kt();Hn();o0={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},lP=1e3,s0=8*1024*1024,uP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),dP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),fP=new Set(["schema","include","exclude","hash"]),pP=new Set(["provider","gitSelection","physicalSelection","projection"]),hP=new Set(["provider","selection"]),mP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),vP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),gP=new Set(["schema","status","before","after"]),wP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),yP=new Set(["path","hash","size","type","gitObjectId"]),NP=new Set(["path","size","type","reason"]),bP=new Set(["ref","hash","count"]),kP=new Set(["change-created","legacy-migration","explicit"]),SP=new Set(["file","directory","other"]),EP=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Hs=/^[a-f0-9]{64}$/u,xP=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,c0=64*1024,l0=64*1024,u0={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},d0={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};f0=(1n<<256n)-1n});var oa=C(()=>{"use strict"});var Ds=C(()=>{"use strict"});var Dv=C(()=>{"use strict"});var cd=C(()=>{"use strict";Ds()});var Bv=C(()=>{"use strict";Ds();cd()});var VP,Lv=C(()=>{"use strict";VP=nn(Si(),1);Ti();vr();qr()});var R0,Vv=C(()=>{"use strict";Ti();qr();R0=4*1024*1024});function FP(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Mv(e,t){return(...r)=>{let i=MP;if(i===null)return t(...r);let n=FP(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var MP,Fv=C(()=>{"use strict";MP=null});var j0,qv=C(()=>{"use strict";Fv();Ii();j0=Mv("hookWritePolicy",async e=>(await Au(e))?.hook??{allow_paths:[]})});var Wv=C(()=>{"use strict";Ds();Ti();Dv();Bv();vr();Lv();qr();Ii();Tu();Vv();qv();_u();cd()});var zv=C(()=>{"use strict";Wv();Dn()});var RH,Jv=C(()=>{"use strict";zv();RH=256*1024});var Gv=C(()=>{"use strict";Jv();oa()});var MH,sa=C(()=>{"use strict";oa();Gv();Q();yt();MH={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});var ld=C(()=>{"use strict";oa();xe();K();sa()});import qi from"node:path";function zP(e,t){let r=qi.relative(e,t);return qi.isAbsolute(r)||r===".."||r.startsWith(`..${qi.sep}`)?null:r.replaceAll("\\","/")||"."}function Yv(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Xv(e,t){if(e.length===0||Yv(e)||e.includes("\\")||qi.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=qi.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function JP(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function ud(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Yv(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function GP(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ud(e.changeBranch,"Native workspace change branch"),ud(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function UP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Kv.test(t.baseCommit)||typeof t.targetCommit!="string"||!Kv.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ud(t.targetBranch,"Native workspace Git target branch")}function KP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!ca.test(String(t.projectRootId))||!ca.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");JP(t.capturedAt),Xv(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!ca.test(String(t.projectRootPathId))||a&&!ca.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ca.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&UP(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(GP(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function YP(e,t){return qi.join(Ge(e,t),"workspace.json")}function XP(e,t){let r=YP(e,t),i=Ie(e,r),n=zP(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Xv(n,"Native workspace file ref")}}async function QP(e,t){try{let r=XP(e,t),i=await ie({root:r.root,ref:r.ref,maxBytes:WP});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function la(e,t){let r=await QP(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(KP(r),r)}var ca,Kv,WP,rD,ua=C(()=>{"use strict";rt();Q();at();xe();K();ca=/^[a-f0-9]{64}$/u,Kv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,WP=16*1024,rD=process.platform});var Wt,xt,Ct,Bs=C(()=>{"use strict";Wt="comet.native.v3",xt="comet.native.v2",Ct="comet.native.v1"});import Wi from"path";function pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function tg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function vd(e){if(!eg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function sR(e){if(!eg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function rg(e,t){if(e.length===0||Wi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cR(e,t){let r=pa(e,`spec_changes[${t}]`);if(tg(r,rR,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(sR(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&rg(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!fd.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!fd.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function lR(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function gd(e,t){if(tg(e,t,Zr),typeof e.name!="string")throw new Error("Native change name is required");if(vd(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!iR.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!nR.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(cR),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!aR.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&rg(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lR(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ha(e){let t=pa(e,Zr);if(t.schema!==Ct)throw new Error(`Expected ${Ct}`);return{schema:Ct,...gd(t,eR)}}function fa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function dd(e,t,r){if(e===null)return null;let i=typeof e=="string"?oR.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function uR(e){if(e==null)return null;if(typeof e!="string"||!fd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function dR(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ma(e){let t=pa(e,Zr);if(t.schema!==xt)throw new Error(`Expected ${xt}`);if(fa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${xt} minimum_runtime_version must be 2`);return{schema:xt,minimum_runtime_version:2,revision:fa(t.revision,"Native v2 revision"),...gd(t,Zv)}}function va(e){let t=pa(e,Zr);if(t.schema!==Wt){if(t.schema===Ct||t.schema===xt){let o=t.schema===Ct?ha(t):ma(t);throw new pd(o.name,o.schema)}throw new Sr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=fa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Sr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=fa(t.revision,"Native revision"),n=gd(t,tR),a=uR(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Wt,minimum_runtime_version:3,revision:i,verification_protocol:dR(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:dd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:dd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:dd(t.partial_allowance,"Native partial_allowance","allowances")}}function fR(e){let t=pa(e,Zr);if(t.schema===Ct){let n=ha(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema===xt){let n=ma(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema!==Wt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Sr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=fa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Sr(t.schema,r).message};let i=va(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Pt(e,t){vd(t);let r=Wi.join(e.changesDir,t);if(!ge(e.changesDir,r))throw new Error("Native change path escaped");return r}async function pR(e,t=Wi.dirname(e)){let r=Wi.relative(t,e).split(Wi.sep).join("/"),i=await ie({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,md.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function ig(e,t){let r=Wi.join(Pt(e,t),Zr);await U(e.nativeRoot,r);let i=fR(await pR(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}var md,Qv,eR,Zv,tR,rR,iR,nR,aR,Zr,fd,eg,oR,pd,Sr,Ls,da,Vs,AD,ye=C(()=>{"use strict";md=nn(Si(),1);rt();at();Q();Xr();lt();xe();K();kt();Iv();aa();ld();ua();Bs();Qv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],eR=new Set(Qv),Zv=new Set([...Qv,"minimum_runtime_version","revision"]),tR=new Set([...Zv,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),rR=new Set(["capability","operation","source","base_hash"]),iR=new Set(["shape","build","verify","archive"]),nR=new Set(["implicit","confirmed"]),aR=new Set(["pending","pass","fail"]),Zr="comet-state.yaml",fd=/^[a-f0-9]{64}$/u,eg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,pd=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Sr=class extends Error{constructor(r,i){super(r!==Wt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Ls=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},da=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Vs=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},AD=Is("en")});function og(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 ng(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function ag(e){return e.includes("-->")||e.includes("--!>")}function*Ms(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
178
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function od(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function AP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function jv(e){let t=ds(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?AP(n):void 0;if(a&&!a())return!1;let o=od(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let f=r[l];f&&(f.kind==="literal"&&f.value===s||f.kind==="question"&&s!=="/"?c.add(l+1):f.kind==="star"&&s!=="/"||f.kind==="globstar"?c.add(l):f.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=od(r,c,a),o===null||o.size===0)return!1}return od(r,o,a)?.has(r.length)??!1}}function _P(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ds(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>ds(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=RP(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(jv),excludeMatchers:r.map(jv),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xe(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Fi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hv(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=Tv.posix.normalize(e);if(r!==e||Tv.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function IP(e,t){let r=Ye(e,`Native snapshot entry ${t}`);Xe(r,yP,`Native snapshot entry ${t}`);let i=Hv(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Hs.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:xt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!xP.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function TP(e,t){let r=Ye(e,`Native snapshot omission ${t}`);if(Xe(r,NP,`Native snapshot omission ${t}`),!SP.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!EP.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Hv(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:xt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function jP(e){let t=Ye(e,"Native snapshot omission overflow");if(Xe(t,bP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Hs.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Fi(t.count,"Native snapshot omission overflow count")}}function Mi(e,t){let r=Ye(e,t);if(Xe(r,vP,t),typeof r.hash!="string"||!Hs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=xt(r.recordCount,`${t} recordCount`),n=xt(r.storedRecordCount,`${t} storedRecordCount`),a=xt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function $v(e){let t=Ye(e,"Native Git selection evidence");if(Xe(t,mP,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Mi(t.stageBefore,"Native Git selection stageBefore"),i=Mi(t.combined,"Native Git selection combined"),n=Mi(t.stageAfter,"Native Git selection stageAfter"),a=Mi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Mi(t.finalCombined,"Native Git selection finalCombined"),s=Mi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(u=>u.overflow),l=!Os(r,n)||!Os(n,a)||!Os(i,o)||!Os(a,s),f=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==f)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:f,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Ov(e,t){let r=Ye(e,t);if(Xe(r,wP,t),typeof r.hash!="string"||!Hs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=xt(r.visitedNodeCount,`${t} visitedNodeCount`),n=xt(r.recordCount,`${t} recordCount`),a=xt(r.storedRecordCount,`${t} storedRecordCount`),o=xt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function $P(e){let t=Ye(e,"Native physical selection evidence");if(Xe(t,gP,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Ov(t.before,"Native physical selection before"),i=Ov(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!CP(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function sd(e){let t=Ye(e,"Native content snapshot manifest");if(Xe(t,uP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!kP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let b=Ye(t.capture,"Native content snapshot capture");if(Xe(b,pP,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=b.gitSelection===void 0?void 0:$v(b.gitSelection),S=b.physicalSelection===void 0?void 0:$P(b.physicalSelection),E=null;if(b.projection!==void 0){let A=Ye(b.projection,"Native content snapshot projection");if(Xe(A,hP,"Native content snapshot projection"),A.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...A.selection===void 0?{}:{selection:$v(A.selection)}}}if(b.provider==="git"){if(S||E)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(S&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");r=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...S?{physicalSelection:S}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=Ye(t.limits,"Native content snapshot limits");Xe(i,dP,"Native content snapshot limits");let n={maxFiles:Fi(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Fi(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Fi(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Fi(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Fi(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Ye(t.policy,"Native snapshot policy");if(Xe(b,fP,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=_P({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(IP),s=t.omitted.map(TP),c=xt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:jP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,P)=>b+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>lP||c<s.length)throw new Error("Native content snapshot omission count is invalid");let f=c-s.length;if(f===0&&l||f>0&&l?.count!==f)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(b=>b.reason==="git-enumeration-limit"),d=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...u,...d])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(u.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...g])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,y=w?.status==="overflow"||w?.status==="overflow-and-changed",N=w?.status==="changed"||w?.status==="overflow-and-changed";if(y!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(PP(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}var o0,lP,s0,uP,dP,fP,pP,hP,mP,vP,gP,wP,yP,NP,bP,kP,SP,EP,Hs,xP,c0,l0,u0,d0,f0,aa=C(()=>{"use strict";Q();ut();Et();Nt();K();St();Hn();o0={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},lP=1e3,s0=8*1024*1024,uP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),dP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),fP=new Set(["schema","include","exclude","hash"]),pP=new Set(["provider","gitSelection","physicalSelection","projection"]),hP=new Set(["provider","selection"]),mP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),vP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),gP=new Set(["schema","status","before","after"]),wP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),yP=new Set(["path","hash","size","type","gitObjectId"]),NP=new Set(["path","size","type","reason"]),bP=new Set(["ref","hash","count"]),kP=new Set(["change-created","legacy-migration","explicit"]),SP=new Set(["file","directory","other"]),EP=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Hs=/^[a-f0-9]{64}$/u,xP=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,c0=64*1024,l0=64*1024,u0={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},d0={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};f0=(1n<<256n)-1n});var oa=C(()=>{"use strict"});var Ds=C(()=>{"use strict"});var Dv=C(()=>{"use strict"});var cd=C(()=>{"use strict";Ds()});var Bv=C(()=>{"use strict";Ds();cd()});var VP,Lv=C(()=>{"use strict";VP=nn(Si(),1);Ti();vr();qr()});var R0,Vv=C(()=>{"use strict";Ti();qr();R0=4*1024*1024});function FP(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Mv(e,t){return(...r)=>{let i=MP;if(i===null)return t(...r);let n=FP(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var MP,Fv=C(()=>{"use strict";MP=null});var j0,qv=C(()=>{"use strict";Fv();Ii();j0=Mv("hookWritePolicy",async e=>(await Au(e))?.hook??{allow_paths:[]})});var Wv=C(()=>{"use strict";Ds();Ti();Dv();Bv();vr();Lv();qr();Ii();Tu();Vv();qv();_u();cd()});var zv=C(()=>{"use strict";Wv();Dn()});var RH,Jv=C(()=>{"use strict";zv();RH=256*1024});var Gv=C(()=>{"use strict";Jv();oa()});var MH,sa=C(()=>{"use strict";oa();Gv();Q();Nt();MH={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});var ld=C(()=>{"use strict";oa();xe();K();sa()});import qi from"node:path";function zP(e,t){let r=qi.relative(e,t);return qi.isAbsolute(r)||r===".."||r.startsWith(`..${qi.sep}`)?null:r.replaceAll("\\","/")||"."}function Yv(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Xv(e,t){if(e.length===0||Yv(e)||e.includes("\\")||qi.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=qi.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function JP(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function ud(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Yv(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function GP(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ud(e.changeBranch,"Native workspace change branch"),ud(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function UP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Kv.test(t.baseCommit)||typeof t.targetCommit!="string"||!Kv.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ud(t.targetBranch,"Native workspace Git target branch")}function KP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!ca.test(String(t.projectRootId))||!ca.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");JP(t.capturedAt),Xv(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!ca.test(String(t.projectRootPathId))||a&&!ca.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ca.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&UP(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(GP(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function YP(e,t){return qi.join(Ge(e,t),"workspace.json")}function XP(e,t){let r=YP(e,t),i=Ie(e,r),n=zP(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Xv(n,"Native workspace file ref")}}async function QP(e,t){try{let r=XP(e,t),i=await ie({root:r.root,ref:r.ref,maxBytes:WP});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function la(e,t){let r=await QP(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(KP(r),r)}var ca,Kv,WP,rD,ua=C(()=>{"use strict";it();Q();ot();xe();K();ca=/^[a-f0-9]{64}$/u,Kv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,WP=16*1024,rD=process.platform});var zt,Ct,Pt,Bs=C(()=>{"use strict";zt="comet.native.v3",Ct="comet.native.v2",Pt="comet.native.v1"});import Wi from"path";function pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function tg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function vd(e){if(!eg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function sR(e){if(!eg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function rg(e,t){if(e.length===0||Wi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cR(e,t){let r=pa(e,`spec_changes[${t}]`);if(tg(r,rR,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(sR(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&rg(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!fd.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!fd.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function lR(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function gd(e,t){if(tg(e,t,Zr),typeof e.name!="string")throw new Error("Native change name is required");if(vd(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!iR.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!nR.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(cR),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!aR.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&rg(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lR(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ha(e){let t=pa(e,Zr);if(t.schema!==Pt)throw new Error(`Expected ${Pt}`);return{schema:Pt,...gd(t,eR)}}function fa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function dd(e,t,r){if(e===null)return null;let i=typeof e=="string"?oR.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function uR(e){if(e==null)return null;if(typeof e!="string"||!fd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function dR(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ma(e){let t=pa(e,Zr);if(t.schema!==Ct)throw new Error(`Expected ${Ct}`);if(fa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ct} minimum_runtime_version must be 2`);return{schema:Ct,minimum_runtime_version:2,revision:fa(t.revision,"Native v2 revision"),...gd(t,Zv)}}function va(e){let t=pa(e,Zr);if(t.schema!==zt){if(t.schema===Pt||t.schema===Ct){let o=t.schema===Pt?ha(t):ma(t);throw new pd(o.name,o.schema)}throw new Sr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=fa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Sr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=fa(t.revision,"Native revision"),n=gd(t,tR),a=uR(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:zt,minimum_runtime_version:3,revision:i,verification_protocol:dR(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:dd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:dd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:dd(t.partial_allowance,"Native partial_allowance","allowances")}}function fR(e){let t=pa(e,Zr);if(t.schema===Pt){let n=ha(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${zt}`}}if(t.schema===Ct){let n=ma(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${zt}`}}if(t.schema!==zt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Sr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=fa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Sr(t.schema,r).message};let i=va(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Rt(e,t){vd(t);let r=Wi.join(e.changesDir,t);if(!ge(e.changesDir,r))throw new Error("Native change path escaped");return r}async function pR(e,t=Wi.dirname(e)){let r=Wi.relative(t,e).split(Wi.sep).join("/"),i=await ie({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,md.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function ig(e,t){let r=Wi.join(Rt(e,t),Zr);await U(e.nativeRoot,r);let i=fR(await pR(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}var md,Qv,eR,Zv,tR,rR,iR,nR,aR,Zr,fd,eg,oR,pd,Sr,Ls,da,Vs,AD,ye=C(()=>{"use strict";md=nn(Si(),1);it();ot();Q();Xr();ut();xe();K();St();Iv();aa();ld();ua();Bs();Qv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],eR=new Set(Qv),Zv=new Set([...Qv,"minimum_runtime_version","revision"]),tR=new Set([...Zv,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),rR=new Set(["capability","operation","source","base_hash"]),iR=new Set(["shape","build","verify","archive"]),nR=new Set(["implicit","confirmed"]),aR=new Set(["pending","pass","fail"]),Zr="comet-state.yaml",fd=/^[a-f0-9]{64}$/u,eg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,pd=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Sr=class extends Error{constructor(r,i){super(r!==zt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Ls=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},da=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Vs=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},AD=Is("en")});function og(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 ng(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function ag(e){return e.includes("-->")||e.includes("--!>")}function*Ms(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
179
179
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
180
180
  `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=ng(l,t);else if(r)ag(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=ng(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!ag(d))r=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);h&&n.has(h[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(d)&&(i=h[1])}}}if(c===-1)break;o=c+1}}function ga(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function sg(e,t,r,i=[],n="content-hash"){let a=ga(r),o=t.replaceAll("\\","/").trim(),s=i.map(ga);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${_(hR,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function cg(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function mR(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ms(e)){n=s+1;let c=o?og(a):null;c?.level===1&&(nd(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function wd(e,t="brief.md",r=Fs.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=mR(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:u}of Ms(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let h=d[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:u}of Ms(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),cg(o.map(l=>sg("brief-example",t,l.join(`
181
181
  `),[],i)),"Brief",i)}function yd(e,t="spec.md",r=Fs.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(sg("spec-scenario",t,[o.title,...o.body].join(`
182
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Ms(e)){let f=l?og(c):null,u=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let d=ga(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:d,body:[],context:a.map(h=>h.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),cg(n,"Specification",i)}var hR,jD,Fs,qs=C(()=>{"use strict";Xr();ve();hR="comet.native.acceptance.v1",jD=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Fs=Object.freeze({maxCriteria:1024})});import lg from"node:path";function ug(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||lg.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||lg.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function gR(e,t){return e.localeCompare(t,"en")}function Ws(e){let t=ug(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>gR(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=wd(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=ug(a.source,`Native spec source for ${a.capability}`);i.push(...yd(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=ga(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function dg(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!vR.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function fg(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var vR,zs=C(()=>{"use strict";qs();vR=/^A[1-9]\d*$/u});function wR(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function F(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(wR(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var wa=C(()=>{"use strict"});import yR from"node:path";function xR(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function CR(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function PR(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 RR(e){return e.schema===Ct?ha(e):e.schema===xt?ma(e):va(e)}function AR(e){return yR.posix.normalize(e.replaceAll("\\","/"))}function _R(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:AR(t.source)})}function IR(e){return e==="shape"?"shape":"build"}function TR(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function jR(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function pg(e){let t=RR(e.state);dg(e.acceptance);let r=IR(t.phase),i=r==="shape"?0:1,n=CR(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return I({schema:zr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:_R(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:TR(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:F(jR(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:ms(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Nd(e){let t=xR(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!NR.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Js)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!kR.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!bR.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!ER.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!SR.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Js,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:PR(t.createdAt,"Native portable migration transaction createdAt")}}function hg(e){switch(Nd(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Js,NR,bR,kR,SR,ER,bd=C(()=>{"use strict";ye();zs();Ft();wa();Hi();Bs();Js="comet.native.portable-migration.v1",NR=new Set(["schema","id","change","fromSchema","status","createdAt"]),bR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kR=/^[a-z0-9][a-z0-9-]{7,127}$/u,SR=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),ER=new Set([Ct,xt,Wt])});import kd from"node:path";function wg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function MR(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=wg(e,r);if(yg(i,VR,r),typeof i.capability!="string"||!gg.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function FR(e){let t=wg(e,"Native portable Archive transaction");if(yg(t,LR,"Native portable Archive transaction"),t.schema!==mg)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!HR.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!gg.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"||!DR.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"||!BR.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(MR);if(new Set(r.map(({capability:n})=>n)).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 i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:mg,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 Gs(e){let t=$R.exec(e);if(t)return{kind:"archive",change:t[1]};let r=OR.exec(e);return r?{kind:"migration",change:r[1]}:null}function Us(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Gs(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return kd.join(e.transactionsDir,r)}async function Sd(e,t){let r=Gs(t);if(!r)return null;let i=await ie({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=kd.join(e.transactionsDir,t);if(r.kind==="archive"){let s=FR(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Nd(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Ks(e,t){let r=Us(e,t);try{return await Sd(e,kd.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Ng(e){return e.kind==="archive"||e.journal.status!=="committed"}var mg,vg,$R,OR,HR,DR,BR,LR,VR,gg,Ys=C(()=>{"use strict";at();bd();mg="comet.native.archive-transaction.v4",vg="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",$R=new RegExp(`^portable-archive-(${vg})\\.json$`,"u"),OR=new RegExp(`^portable-migration-(${vg})\\.json$`,"u"),HR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,DR=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BR=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),LR=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),VR=new Set(["capability","operation","source","content"]),gg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import zt from"path";import{TextDecoder as WR}from"util";function Qs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zs(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Eg(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ed(e,t){if(typeof e!="string"||e.length===0||zt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Xs(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function bg(e,t){if(Ed(e,t),e.includes("\\")||e!==zt.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 XR(e,t){let r=Qs(e,`transaction operations[${t}]`);if(Zs(r,JR,`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`);Ed(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Ed(r[i],`transaction operation ${r.id} ${i}`);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 xg(e){let t=Qs(e,"Native Archive transaction journal");if(Zs(t,GR,"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"||!Sg.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(!Eg(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Xs(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=Qs(s,`Archive transaction operations[${c}]`);if(Zs(l,UR,`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`);bg(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&bg(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Xs(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(Xs(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`);Xs(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=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)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/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 QR(e){let t=Qs(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return xg(t);if(Zs(t,zR,"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"||!Sg.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!zt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!zt.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(!Eg(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(XR),i=r.map(n=>n.id);if(new Set(i).size!==i.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 ZR(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return zt.join(e.transactionsDir,t)}function Cg(e,t){let r=ZR(e,t);return{directory:r,journal:zt.join(r,"transaction.json"),events:zt.join(r,"events.jsonl"),staged:zt.join(r,"staged"),backups:zt.join(r,"backups")}}async function xd(e,t){let r=Cg(e,t);return await Promise.all(Object.values(r).map(i=>U(e.runtimeDir,i))),r}async function Cd(e,t,r={}){let i=await xd(e,t),n=await Vi({root:e.runtimeDir,file:i.journal,maxBytes:KR,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(YR.decode(n.bytes)),o=QR(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var zR,JR,GR,UR,Sg,KR,nB,aB,oB,YR,ec=C(()=>{"use strict";Q();K();kt();zR=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),JR=new Set(["id","type","source","target","staged","backup"]),GR=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),UR=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Sg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),KR=256*1024,nB=1024*1024,aB=16*1024,oB=64*1024*1024,YR=new WR("utf-8",{fatal:!0})});import{promises as eA}from"fs";import tA from"path";async function rA(e,t,r){let i;try{i=await eA.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Cd(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Gs(n.name))try{let a=await Sd(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ng(a))return!0}catch{return!0}return!1}async function iA(e,t){let r=Date.now()+5e3,i=tA.join(e.locksDir,"root-move.lock");for(;;)try{return await As(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Cv(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function R(e,t,r,i){let n=await iA(e,t);try{if(await fs(e.projectRoot),await rA(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await _s(n)}}var xe=C(()=>{"use strict";lt();na();Ys();ec()});var Pg=C(()=>{"use strict"});import{execFileSync as nA}from"node:child_process";import Rg from"node:path";function Rd(e,t,r={}){let i=r.timeoutMs??aA,n=r.maxBufferBytes??oA;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=Rg.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?qu(e,o,a):e,c=Rg.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Wu(t);try{return nA(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(f){let u=typeof f.stderr=="string"?f.stderr.trim():Buffer.isBuffer(f.stderr)?f.stderr.toString("utf8").trim():"";throw new Pd(e,t,u,{cause:f})}}var aA,oA,Pd,Ag=C(()=>{"use strict";bs();aA=6e4,oA=8*1024*1024,Pd=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr}});import{promises as _g}from"node:fs";import sA from"node:path";async function ei(e){if(e===process.pid&&Ad!==null)return Ad;let t=await cA(e);return e===process.pid&&t!==null&&(Ad=t),t}async function cA(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([_g.readFile(`/proc/${e}/stat`,"utf8"),_g.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32"){let t=process.env.SystemRoot??"C:\\Windows",r=sA.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=Rd(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:15e3,maxBufferBytes:4096}).trim();return/^\d+$/u.test(i)?`win32:${i}`:null}if(process.platform==="darwin"){let t=Rd("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}async function zi(e,t){if(!Number.isSafeInteger(e)||e<=0)return!0;try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return!1}if(!t)return!0;let r=await ei(e);return r===null||r===t}var Ad,_d=C(()=>{"use strict";Ag();Ad=null});import{promises as ya}from"node:fs";import Ne from"node:path";function Id(e,t){let r=Ne.normalize(e),i=Ne.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function jg(e,t){let r=Ne.relative(e,t);return r===""||!Ne.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ne.sep}`)}function Ig(e){return JSON.stringify(e.native)}async function tc(e,t){let r=await Te(e);if(r&&t){if(Ig(r)!==Ig(t))throw new Error(`Native worktree configuration differs from the source project: ${Ne.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await ps(e,t),await sv(e),!0):!1}async function lA(e,t){if(!jg(e,t))return!1;let i=`/${Ne.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=T(e,["rev-parse","--git-common-dir"]),a=Ne.resolve(e,n),o=Ne.join(a,"info","exclude"),s="";try{s=await ya.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await ya.mkdir(Ne.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
182
+ `),o.context,i)),o=null}};for(let{line:c,body:l}of Ms(e)){let f=l?og(c):null,u=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let d=ga(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:d,body:[],context:a.map(h=>h.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),cg(n,"Specification",i)}var hR,jD,Fs,qs=C(()=>{"use strict";Xr();ve();hR="comet.native.acceptance.v1",jD=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Fs=Object.freeze({maxCriteria:1024})});import lg from"node:path";function ug(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||lg.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||lg.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function gR(e,t){return e.localeCompare(t,"en")}function Ws(e){let t=ug(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>gR(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=wd(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=ug(a.source,`Native spec source for ${a.capability}`);i.push(...yd(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=ga(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function dg(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!vR.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function fg(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var vR,zs=C(()=>{"use strict";qs();vR=/^A[1-9]\d*$/u});function wR(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function F(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(wR(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var wa=C(()=>{"use strict"});import yR from"node:path";function xR(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function CR(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function PR(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 RR(e){return e.schema===Pt?ha(e):e.schema===Ct?ma(e):va(e)}function AR(e){return yR.posix.normalize(e.replaceAll("\\","/"))}function _R(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:AR(t.source)})}function IR(e){return e==="shape"?"shape":"build"}function TR(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function jR(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function pg(e){let t=RR(e.state);dg(e.acceptance);let r=IR(t.phase),i=r==="shape"?0:1,n=CR(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return I({schema:zr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:_R(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:TR(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:F(jR(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:ms(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Nd(e){let t=xR(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!NR.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Js)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!kR.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!bR.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!ER.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!SR.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Js,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:PR(t.createdAt,"Native portable migration transaction createdAt")}}function hg(e){switch(Nd(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Js,NR,bR,kR,SR,ER,bd=C(()=>{"use strict";ye();zs();qt();wa();Hi();Bs();Js="comet.native.portable-migration.v1",NR=new Set(["schema","id","change","fromSchema","status","createdAt"]),bR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kR=/^[a-z0-9][a-z0-9-]{7,127}$/u,SR=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),ER=new Set([Pt,Ct,zt])});import kd from"node:path";function wg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function MR(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=wg(e,r);if(yg(i,VR,r),typeof i.capability!="string"||!gg.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function FR(e){let t=wg(e,"Native portable Archive transaction");if(yg(t,LR,"Native portable Archive transaction"),t.schema!==mg)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!HR.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!gg.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"||!DR.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"||!BR.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(MR);if(new Set(r.map(({capability:n})=>n)).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 i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:mg,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 Gs(e){let t=$R.exec(e);if(t)return{kind:"archive",change:t[1]};let r=OR.exec(e);return r?{kind:"migration",change:r[1]}:null}function Us(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Gs(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return kd.join(e.transactionsDir,r)}async function Sd(e,t){let r=Gs(t);if(!r)return null;let i=await ie({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=kd.join(e.transactionsDir,t);if(r.kind==="archive"){let s=FR(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Nd(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Ks(e,t){let r=Us(e,t);try{return await Sd(e,kd.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Ng(e){return e.kind==="archive"||e.journal.status!=="committed"}var mg,vg,$R,OR,HR,DR,BR,LR,VR,gg,Ys=C(()=>{"use strict";ot();bd();mg="comet.native.archive-transaction.v4",vg="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",$R=new RegExp(`^portable-archive-(${vg})\\.json$`,"u"),OR=new RegExp(`^portable-migration-(${vg})\\.json$`,"u"),HR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,DR=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BR=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),LR=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),VR=new Set(["capability","operation","source","content"]),gg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import Jt from"path";import{TextDecoder as WR}from"util";function Qs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zs(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Eg(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ed(e,t){if(typeof e!="string"||e.length===0||Jt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Xs(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function bg(e,t){if(Ed(e,t),e.includes("\\")||e!==Jt.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 XR(e,t){let r=Qs(e,`transaction operations[${t}]`);if(Zs(r,JR,`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`);Ed(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Ed(r[i],`transaction operation ${r.id} ${i}`);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 xg(e){let t=Qs(e,"Native Archive transaction journal");if(Zs(t,GR,"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"||!Sg.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(!Eg(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Xs(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=Qs(s,`Archive transaction operations[${c}]`);if(Zs(l,UR,`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`);bg(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&bg(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Xs(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(Xs(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`);Xs(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=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)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/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 QR(e){let t=Qs(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return xg(t);if(Zs(t,zR,"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"||!Sg.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Jt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Jt.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(!Eg(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(XR),i=r.map(n=>n.id);if(new Set(i).size!==i.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 ZR(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Jt.join(e.transactionsDir,t)}function Cg(e,t){let r=ZR(e,t);return{directory:r,journal:Jt.join(r,"transaction.json"),events:Jt.join(r,"events.jsonl"),staged:Jt.join(r,"staged"),backups:Jt.join(r,"backups")}}async function xd(e,t){let r=Cg(e,t);return await Promise.all(Object.values(r).map(i=>U(e.runtimeDir,i))),r}async function Cd(e,t,r={}){let i=await xd(e,t),n=await Vi({root:e.runtimeDir,file:i.journal,maxBytes:KR,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(YR.decode(n.bytes)),o=QR(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var zR,JR,GR,UR,Sg,KR,nB,aB,oB,YR,ec=C(()=>{"use strict";Q();K();St();zR=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),JR=new Set(["id","type","source","target","staged","backup"]),GR=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),UR=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Sg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),KR=256*1024,nB=1024*1024,aB=16*1024,oB=64*1024*1024,YR=new WR("utf-8",{fatal:!0})});import{promises as eA}from"fs";import tA from"path";async function rA(e,t,r){let i;try{i=await eA.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Cd(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Gs(n.name))try{let a=await Sd(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ng(a))return!0}catch{return!0}return!1}async function iA(e,t){let r=Date.now()+5e3,i=tA.join(e.locksDir,"root-move.lock");for(;;)try{return await As(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Cv(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function R(e,t,r,i){let n=await iA(e,t);try{if(await fs(e.projectRoot),await rA(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await _s(n)}}var xe=C(()=>{"use strict";ut();na();Ys();ec()});var Pg=C(()=>{"use strict"});import{execFileSync as nA}from"node:child_process";import Rg from"node:path";function Rd(e,t,r={}){let i=r.timeoutMs??aA,n=r.maxBufferBytes??oA;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=Rg.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?qu(e,o,a):e,c=Rg.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Wu(t);try{return nA(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(f){let u=typeof f.stderr=="string"?f.stderr.trim():Buffer.isBuffer(f.stderr)?f.stderr.toString("utf8").trim():"";throw new Pd(e,t,u,{cause:f})}}var aA,oA,Pd,Ag=C(()=>{"use strict";bs();aA=6e4,oA=8*1024*1024,Pd=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr}});import{promises as _g}from"node:fs";import sA from"node:path";async function ei(e){if(e===process.pid&&Ad!==null)return Ad;let t=await cA(e);return e===process.pid&&t!==null&&(Ad=t),t}async function cA(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([_g.readFile(`/proc/${e}/stat`,"utf8"),_g.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32"){let t=process.env.SystemRoot??"C:\\Windows",r=sA.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=Rd(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:15e3,maxBufferBytes:4096}).trim();return/^\d+$/u.test(i)?`win32:${i}`:null}if(process.platform==="darwin"){let t=Rd("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}async function zi(e,t){if(!Number.isSafeInteger(e)||e<=0)return!0;try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return!1}if(!t)return!0;let r=await ei(e);return r===null||r===t}var Ad,_d=C(()=>{"use strict";Ag();Ad=null});import{promises as ya}from"node:fs";import Ne from"node:path";function Id(e,t){let r=Ne.normalize(e),i=Ne.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function jg(e,t){let r=Ne.relative(e,t);return r===""||!Ne.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ne.sep}`)}function Ig(e){return JSON.stringify(e.native)}async function tc(e,t){let r=await Te(e);if(r&&t){if(Ig(r)!==Ig(t))throw new Error(`Native worktree configuration differs from the source project: ${Ne.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await ps(e,t),await sv(e),!0):!1}async function lA(e,t){if(!jg(e,t))return!1;let i=`/${Ne.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=T(e,["rev-parse","--git-common-dir"]),a=Ne.resolve(e,n),o=Ne.join(a,"info","exclude"),s="";try{s=await ya.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await ya.mkdir(Ne.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
183
183
  `)?"":`
184
184
  `;return await ya.appendFile(o,`${c}${i}
185
- `,"utf8"),!0}function uA(e,t,r){let i=Ne.resolve(e,r??Ne.join(".worktrees",t)),n=Ne.resolve(e,T(e,["rev-parse","--git-common-dir"]));if(jg(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Lr(e).some(a=>Id(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function dA(e){try{throw await ya.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Tg(e){try{return await ya.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Td(e){let t=Ne.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 i=X(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await yr(t,e.sourceConfig?.native.artifact_root??"docs");return xv([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=X(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;yu(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(yu(t,o),!Ei(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!Tm(t))throw new Error("Native branch isolation requires a clean current working directory");if(Ei(t,n))throw new Error(`Native change branch already exists: ${n}`);T(t,["switch","-c",n,o]),h=!0}let v;try{v=await tc(t,e.sourceConfig)}catch(p){throw new Er(`Native branch preparation is incomplete: ${p.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?Ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Id(h,i.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await tc(t,e.sourceConfig)}catch(p){throw new Er(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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:!1,configInitialized:v}}}let s=Go(i.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await Tg(c.root)){let h=e.worktreePath?Ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Id(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await tc(c.root,e.sourceConfig)}catch(p){throw new Er(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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:!1,configInitialized:v}}}c&&!await Tg(c.root)&&(T(i.primaryWorktreeRoot,["worktree","prune"]),s=Go(i.primaryWorktreeRoot));let l=Ei(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=uA(i.primaryWorktreeRoot,e.name,e.worktreePath);await dA(f);let u=await lA(i.primaryWorktreeRoot,f),d={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:u,configInitialized:!1};try{T(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await tc(f,e.sourceConfig)}catch(h){throw new Er(`Native worktree preparation is incomplete: ${h.message}`,d,{cause:h})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}var Er,jd=C(()=>{"use strict";Vr();rt();lt();Qn();na();K();Er=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import{createHash as Mg}from"node:crypto";import $g from"path";function be(e,t){return e<t?-1:e>t?1:0}function Od(e){if(!Dd.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function gA(e,t){return e===t?0:e===null?-1:t===null?1:be(e,t)}function Cr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=$g.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||$g.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function Wg(e,t){return e==="."?e:Cr(e,t)}function Ji(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function wA(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Cr(e.path,`${t} path`),hash:e.hash,size:Ji(e.size,`${t} size`),type:"file"}}function yA(e,t){return{path:Wg(e.path,`${t} path`),size:e.size===null?null:Ji(e.size,`${t} size`),type:e.type,reason:e.reason}}function NA(e,t){return be(e.path,t.path)||be(e.hash,t.hash)||e.size-t.size}function bA(e,t){return be(e.path,t.path)||be(e.reason,t.reason)||be(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ka(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
185
+ `,"utf8"),!0}function uA(e,t,r){let i=Ne.resolve(e,r??Ne.join(".worktrees",t)),n=Ne.resolve(e,T(e,["rev-parse","--git-common-dir"]));if(jg(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Lr(e).some(a=>Id(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function dA(e){try{throw await ya.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Tg(e){try{return await ya.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Td(e){let t=Ne.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 i=X(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await yr(t,e.sourceConfig?.native.artifact_root??"docs");return xv([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=X(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;yu(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(yu(t,o),!Ei(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!Tm(t))throw new Error("Native branch isolation requires a clean current working directory");if(Ei(t,n))throw new Error(`Native change branch already exists: ${n}`);T(t,["switch","-c",n,o]),h=!0}let v;try{v=await tc(t,e.sourceConfig)}catch(p){throw new Er(`Native branch preparation is incomplete: ${p.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?Ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Id(h,i.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await tc(t,e.sourceConfig)}catch(p){throw new Er(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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:!1,configInitialized:v}}}let s=Go(i.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await Tg(c.root)){let h=e.worktreePath?Ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Id(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await tc(c.root,e.sourceConfig)}catch(p){throw new Er(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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:!1,configInitialized:v}}}c&&!await Tg(c.root)&&(T(i.primaryWorktreeRoot,["worktree","prune"]),s=Go(i.primaryWorktreeRoot));let l=Ei(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=uA(i.primaryWorktreeRoot,e.name,e.worktreePath);await dA(f);let u=await lA(i.primaryWorktreeRoot,f),d={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:u,configInitialized:!1};try{T(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await tc(f,e.sourceConfig)}catch(h){throw new Er(`Native worktree preparation is incomplete: ${h.message}`,d,{cause:h})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}var Er,jd=C(()=>{"use strict";Vr();it();ut();Qn();na();K();Er=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import{createHash as Mg}from"node:crypto";import $g from"path";function be(e,t){return e<t?-1:e>t?1:0}function Od(e){if(!Dd.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function gA(e,t){return e===t?0:e===null?-1:t===null?1:be(e,t)}function Cr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=$g.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||$g.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function Wg(e,t){return e==="."?e:Cr(e,t)}function Ji(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function wA(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Cr(e.path,`${t} path`),hash:e.hash,size:Ji(e.size,`${t} size`),type:"file"}}function yA(e,t){return{path:Wg(e.path,`${t} path`),size:e.size===null?null:Ji(e.size,`${t} size`),type:e.type,reason:e.reason}}function NA(e,t){return be(e.path,t.path)||be(e.hash,t.hash)||e.size-t.size}function bA(e,t){return be(e.path,t.path)||be(e.reason,t.reason)||be(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ka(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
186
186
  `,"utf8")}function xr(e,t,r){let i=`${t}
187
187
  ${Yo(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function kA(e){if(ka(e)<=ri)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=Mg("sha256");a.update(`${hA}
188
- `),e.omissionOverflow&&xr(a,"existing-overflow",e.omissionOverflow);let o=(d,h)=>{h||(i+=1),n+=1,xr(a,"omission",d)},s=d=>{i+=1,n+=1,xr(a,"entry",d)},c=()=>{for(let d=r.length-1;d>=0;d-=1){let h=r[d];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return r.splice(d,1),h}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),f=l();for(;ka(f)>ri;){if(r.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(r.length/4));for(let v=0;v<h;v+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");f=l()}let u=a.digest("hex");return{...f,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${u}`,hash:u,count:n}}}function SA(e){let t=sd(e),r=t.entries.map((n,a)=>wA(n,`Snapshot entry ${a}`));if(r.sort(NA),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>yA(n,`Snapshot omission ${a}`));return i.sort(bA),kA({schema:Fg,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function ic(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:Cr(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>be(r.path,i.path)||be(r.kind,i.kind))}function Sa(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Og(e){return e?{hash:e.hash,size:e.size}:null}function zg(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:be(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let f=c?.path??l?.path;f!==void 0&&r({path:f,kind:c?l?"modified":"removed":"added",before:Og(c),after:Og(l)})}}function EA(e,t){return{...e,attributedTo:t.filter(r=>Sa(r,e.path))}}function Jt(e,t){return{id:`scope:${_(fA,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function xA(e,t){let r=t.omitted.map(i=>Jt({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(Jt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Jt({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function Hg(e,t){return xA(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Hd(e,t){return be(e.kind,t.kind)||be(e.source,t.source)||gA(e.path,t.path)||be(e.id,t.id)}function CA(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Hd)}function Jg(e){return[...new Set(e.map((t,r)=>Cr(t,`Git path ${r}`)))].sort(be)}function Dg(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function PA(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Gg(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Jg(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Dg(e.baseCommit,"Native external drift base commit"),targetBranch:PA(e.targetBranch,"Native external drift target branch"),targetCommit:Dg(e.targetCommit,"Native external drift target commit"),paths:t}}function RA(e){if(typeof e.contractHash!="string"||!Dd.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ic(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Jg(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Gg(e.externalDrift)}}}function AA(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,f=!1,u=0,d=0;return zg(e,t,h=>{let v=r.some(p=>Sa(p,h.path));if(u+=1,c.push(h.path),!v&&!n?.has(h.path)&&(d+=1),o?.has(h.path)&&s.push(h.path),!f&&a.length<mA){let p=EA(h,r),m=ka(p);l+m<=ri?(a.push(p),l+=m):f=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:u,totalUnattributed:d}}function Ug(e,t){return Jt({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function _A(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:Ji(Number(t[1]),"Scope overflow change count"),unresolved:Ji(Number(t[2]),"Scope overflow unresolved count"),unattributed:Ji(Number(t[3]),"Scope overflow unattributed count")},i=ti(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Ug(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function IA(e){let t=Mg("sha256");t.update(`${pA}
189
- `);let r=0;zg(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){xr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Sa(o,n.path)&&(a+=1,xr(t,"change-attribution",o));xr(t,"change-end",{attributionCount:a}),a===0&&xr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&xr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function TA(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=AA(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let P=new Set(r.externalDrift.paths),S=new Set(o.changePaths),E=r.externalDrift.paths.filter(A=>!S.has(A)||n.some(M=>Sa(M,A)));if(E.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${E.slice(0,8).join(", ")}`);if(P.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=_(Na,e),c=_(Na,t),l=[],f=new Set(r.externalDrift?.paths??[]);for(let[P,S]of[["baseline",e],["current",t]])for(let E of S.omitted){if(l.length>=vA)break;l.push(Jt({kind:"snapshot-omission",source:P,path:E.path,evidence:{reason:E.reason,size:E.size,type:E.type}},`${P} snapshot omitted ${E.path}: ${E.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Hg("baseline",e),...Hg("current",t),...o.totalChanges===0&&a===null?[Jt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(r.gitChangedPaths===void 0)return;let P=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(S=>P.has(S)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(S=>!P.has(S))}},v=P=>{let S=o.candidates.slice(0,P.detailedChangeCount),E=S.filter(ae=>ae.attributedTo.length===0&&!f.has(ae.path)),A=o.totalChanges-S.length,M=o.totalUnattributed-E.length,$=u-P.detailedOmissionCount,de=M+$,rr=[...E.map(ae=>Jt({kind:"unattributed-change",source:"implementation-scope",path:ae.path,evidence:{after:ae.after,before:ae.before,changeKind:ae.kind}},`Changed path is not covered by a declared artifact: ${ae.path}`)),...l.slice(0,P.detailedOmissionCount),...d,...de>0?[Ug(P.overflowHash,{changes:A,unattributed:M,unresolved:de})]:[]],vt=CA(rr),Oe=P.includeGitAdvisory?h():void 0;return{schema:$d,contractHash:i,baselineProjectionRef:Od(s),baselineProjectionHash:s,currentProjectionRef:Od(c),currentProjectionHash:c,complete:vt.length===0,declaredArtifacts:n,changes:S,unattributed:E,unresolvedScopes:vt,noCodeReason:a,...Oe?{gitAdvisory:Oe}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},p=o.candidates.length,m=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let P=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:w});if(ka({...P,scopeHash:w})<=ri)break;if(g){g=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>p||u>m?IA({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:m}):w,k=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:N}),b={...k,scopeHash:_(qg,k)};if(ka(b)>ri)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Rt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function At(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function ti(e,t){if(typeof e!="string"||!Dd.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Bg(e,t,r){let i=Od(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function rc(e,t){let r=Rt(e,"Native snapshot projection");if(At(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==Fg)throw new Error("Native snapshot projection schema is invalid");let i=sd({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=SA(i);if(_(Na,r)!==_(Na,n))throw new Error("Native snapshot projection is not canonical");let a=_(Na,n);if(t!==void 0&&ti(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Bd(e,t){let r=Rt(e,`Declared artifact ${t}`);if(At(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Cr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Lg(e,t){if(e===null)return null;let r=Rt(e,t);return At(r,["hash","size"],[],t),{hash:ti(r.hash,`${t} hash`),size:Ji(r.size,`${t} size`)}}function Vg(e,t){let r=Rt(e,`Implementation change ${t}`);if(At(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Bd),n=ic(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Lg(r.before,`Implementation change ${t} before`),o=Lg(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Cr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function $A(e,t){let r=Rt(e,`Unresolved scope ${t}`);At(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?Wg(r.path,`Unresolved scope ${t} path`):Cr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function ba(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>Cr(n,`${t} ${a}`)),i=[...new Set(r)].sort(be);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function Kg(e){let t=Rt(e,"Native implementation external drift");if(At(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=ba(t.paths,"Native external drift paths");return Gg({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function nc(e){let t=Rt(e,"Native implementation scope"),r=[...jA].filter(E=>E!=="gitAdvisory"&&E!=="externalDrift");if(At(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==$d)throw new Error("Native implementation scope schema is invalid");let i=ti(t.contractHash,"Implementation scope contractHash"),n=ti(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Bg(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=ti(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Bg(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Bd);if(JSON.stringify(c)!==JSON.stringify(ic(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Vg),f=[...l].sort((E,A)=>be(E.path,A.path));if(JSON.stringify(l)!==JSON.stringify(f)||new Set(l.map(E=>E.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let u=new Set(c.map(E=>`${E.kind}:${E.path}`));if(l.some(E=>E.attributedTo.some(A=>!u.has(`${A.kind}:${A.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(E=>JSON.stringify(E.attributedTo)!==JSON.stringify(c.filter(A=>Sa(A,E.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(Vg),h=t.externalDrift===void 0?void 0:Kg(t.externalDrift),v=new Set(h?.paths??[]),p=l.filter(E=>E.attributedTo.length===0&&!v.has(E.path));if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map($A),g=m.filter(E=>E.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:_A(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,N=[...p.map(E=>Jt({kind:"unattributed-change",source:"implementation-scope",path:E.path,evidence:{after:E.after,before:E.before,changeKind:E.kind}},`Changed path is not covered by a declared artifact: ${E.path}`)),...l.length+(w?.changes??0)===0&&y===null?[Jt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(E=>E.kind==="unattributed-change"||E.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Hd))||new Set(m.map(E=>E.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(Hd))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let E=Rt(t.gitAdvisory,"Implementation scope Git advisory");if(At(E,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),E.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let A=ba(E.changedPaths,"Git changed paths"),M=ba(E.pathsPresentInSnapshotChanges,"Git present paths"),$=ba(E.pathsAbsentFromSnapshotChanges,"Git absent paths"),de=[...M,...$].sort(be);if(JSON.stringify(de)!==JSON.stringify(A)||$.some(rr=>l.some(vt=>vt.path===rr)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:A,pathsPresentInSnapshotChanges:M,pathsAbsentFromSnapshotChanges:$}}let P={schema:$d,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:y,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},S=ti(t.scopeHash,"Implementation scope scopeHash");if(_(qg,P)!==S)throw new Error("Implementation scope content hash mismatch");return{...P,scopeHash:S}}function OA(e){let t=Rt(e,"Native implementation scope authority");if(At(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(Bd);if(JSON.stringify(r)!==JSON.stringify(ic(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=ba(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Kg(t.externalDrift),a=RA({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Ea(e){let t=Rt(e,"Native implementation scope bundle");At(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=OA(t.authority),i=rc(t.baseline),n=rc(t.current),a=nc(t.scope),o=TA(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function Yg(e){let t=nc(e.scope);return Ea({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var $d,Fg,Na,qg,fA,pA,hA,Dd,ri,mA,vA,jA,Gi=C(()=>{"use strict";ve();aa();$d="comet.native.implementation-scope.v2",Fg="comet.native.content-snapshot-projection.v1",Na="comet.native.content-snapshot-projection.v1",qg="comet.native.implementation-scope.v2",fA="comet.native.unresolved-scope-id.v1",pA="comet.native.scope-detail-overflow.v1",hA="comet.native.snapshot-projection-overflow.v2",Dd=/^[a-f0-9]{64}$/u,ri=1024*1024,mA=128,vA=128;jA=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import Xg from"node:path";function Gt(e,t){if(!Zg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ew(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function tw(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Ld(e,t,r=2e3){let i=Le(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function xa(e,t){let r=Xg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||Xg.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function LA(e,t,r){let i=xa(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ci(i),a=i.toLowerCase(),o=r?xa(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function Vd(e){let t=xa(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Ui(e,t){return e<t?-1:e>t?1:0}function ac(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function oc(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function rw(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Qg(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function VA(e){let t=ac(e,"Native acceptance trace");if(oc(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Zg.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=xa(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=ac(o,`Native acceptance trace entry ${s}`);if(oc(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(u=>typeof u!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(u=>Vd(u)),f=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ui))||f==="passed"&&(l.length===0||c.skippedReason!==null)||f==="failed"&&l.length===0&&c.skippedReason===null||f==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:f,kind:c.kind,source:xa(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Ld(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Ui(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=Gt(t.traceHash,"Native acceptance trace hash");if(_(HA,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function iw(e){let t=ac(e,"Native partial allowance");if(oc(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Ui))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:tw(t.change),scopeHash:Gt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Ld(t.reason,"Partial allowance reason"),confirmedSummary:Ld(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:ew(t.sourceRevision),confirmedAt:rw(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=Gt(t.allowanceHash,"Native partial allowance hash");if(_(DA,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Md(e){let t=ac(e,"Native verification evidence");if(oc(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=Gt(t.implementationScopeHash,"Native verification implementation scope hash"),i=VA(t.acceptanceTrace),n=Gt(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Gt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>Vd(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ui)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Ui);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(d=>Vd(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ui)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let f={schema:"comet.native.verification-evidence.v2",change:tw(t.change),sourceRevision:ew(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Gt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Qg(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:LA(t.reportRef,"Native verification report ref"),reportHash:Gt(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:Qg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:rw(t.createdAt,"Native verification timestamp")},u=Gt(t.envelopeHash,"Native verification envelope hash");if(_(BA,f)!==u)throw new Error("Native verification evidence content hash mismatch");return{...f,envelopeHash:u}}var Zg,HA,DA,BA,sc=C(()=>{"use strict";ve();Nr();Hn();Gi();Zg=/^[a-f0-9]{64}$/u,HA="comet.native.acceptance-trace.v2",DA="comet.native.partial-allowance.v1",BA="comet.native.verification-evidence.v2"});var cc,MA,FA,qA,zB,WA,JB,Fd=C(()=>{"use strict";ve();cc="scoped-text-safety",MA=1,FA=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),qA="comet.native.checker-policy.v1",zB=_(qA,{policy:cc,version:MA,limits:FA,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),WA=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],JB=new Set(WA)});function Ki(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Pr(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Ut(e,t){if(typeof e!="string"||!JA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ft(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Le(e).trim();if(!r||r.length>YA||r!==e.trim())throw new Error(`${t} is invalid`);return r}function qd(e,t){let r=ft(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function Ca(e,t,r=ft,i=!1,n=XA){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function ZA(e,t){if(typeof e!="string"||!GA.test(e))throw new Error(`${t} is invalid`);return e}function e_(e){let t=Ki(e,"Native verification receipt bindings");if(Pr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!UA.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Ut(t.contractHash,"Native verification receipt contract hash"),scopeHash:Ut(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Ut(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Ut(t.artifactHash,"Native verification receipt artifact hash")}}function t_(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=KA.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function r_(e,t,r,i){let n=Ki(t,`Native ${e} evidence`);if(e==="automated-check"){if(Pr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=qd(n.startedAt,"Native automated-check start time"),o=qd(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Ki(n.worktree,"Native automated-check worktree");if(Pr(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Ki(n.afterFence,"Native automated-check after fence");if(Pr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ft(n.executable,"Native automated-check executable"),args:Ca(n.args,"Native automated-check arguments",ft,!0),cwd:ft(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:ft(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Ut(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Ut(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Ut(n.outputHash,"Native automated-check output hash"),outputSummary:ft(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Pr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=t_(n.checkReceiptRef);if(Ut(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Ca(n.subjects,"Native static inspection subjects",ft,i==="required-check"),rule:ft(n.rule,"Native static inspection rule"),resultSummary:ft(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Pr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Ca(n.steps,"Native manual evidence steps"),observations:Ca(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function i_(e){let t=Ki(e,"Native verification receipt");if(Pr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=ft(t.actor,"Native verification receipt actor"),o=Ca(t.acceptanceIds,"Native receipt acceptance IDs",ZA,i==="required-check",QA).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Wd,kind:r,role:i,status:n,bindings:e_(t.bindings),acceptanceIds:o,actor:a,issuedAt:qd(t.issuedAt,"Native verification receipt issue time"),evidence:r_(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==cc||s.actor!==`native-runtime:${cc}`))throw new Error("Native required check policy identity is invalid");return s}function zd(e){let t=Ki(e,"Native verification receipt");if(Pr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Wd)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=i_(i),a=Ut(t.receiptHash,"Native verification receipt hash");if(_(zA,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var Wd,zA,JA,GA,UA,KA,YA,XA,QA,lc=C(()=>{"use strict";ve();Fd();Nr();Wd="comet.native.verification-receipt.v3",zA=Wd,JA=/^[a-f0-9]{64}$/u,GA=/^acceptance-[a-f0-9]{64}$/u,UA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,YA=4096,XA=256,QA=1024});var hw={};Ga(hw,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>_t,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>n_,listNativeVerificationReceiptRefs:()=>fw,nativeEvidenceRef:()=>Rr,nativeReportEvidenceRef:()=>c_,readArchivedNativeVerificationAcceptanceCounts:()=>m_,readNativeImplementationScope:()=>_a,readNativeImplementationScopeBundle:()=>dc,readNativePartialAllowance:()=>Yd,readNativeVerificationEvidence:()=>Xd,readNativeVerificationReceipt:()=>fc,readNativeVerificationReportSnapshot:()=>Aa,removeNativeVerificationReportSnapshot:()=>lw,writeNativeImplementationScope:()=>p_,writeNativePartialAllowance:()=>h_,writeNativeVerificationEvidence:()=>pw,writeNativeVerificationReceipt:()=>dw,writeNativeVerificationReportSnapshot:()=>Ra});import{createHash as sw}from"node:crypto";import{promises as Ce}from"node:fs";import pt from"node:path";function Jd(e,t){let r=pt.relative(e,t);return r===""||!pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${pt.sep}`)}function a_(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pa(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return it(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function nw(e){let t=await Ce.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Ce.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function o_(e,t){let r=pt.resolve(e),i=pt.resolve(t);if(!Jd(r,i))throw new Error("Native evidence path is outside its change");let n=[await nw(r)],a=r;for(let o of pt.relative(r,i).split(pt.sep).filter(Boolean)){a=pt.join(a,o);let s=await nw(a);if(!Jd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function aw(e){for(let t of e){let r=await Ce.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!a_(t,r)||await Ce.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function s_(e,t,r={}){let i=await o_(t,pt.dirname(e));await r.afterParentChainCaptured?.();let n=await Ce.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Ce.realpath(e);if(!Jd(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Ce.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Ce.lstat(e),Ce.realpath(e)]);if(await aw(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Pa(s,n)||!Pa(s,c))throw new Error("Native evidence document changed while opening");if(s.size>_t)throw new Error(`Native evidence document exceeds ${_t} bytes`);await r.afterOpen?.();let f=[],u=0,d=Buffer.allocUnsafe(64*1024);for(;;){let m=_t+1-u,g=await o.read(d,0,Math.min(d.length,m),null);if(g.bytesRead===0)break;if(u+=g.bytesRead,u>_t)throw new Error(`Native evidence document exceeds ${_t} bytes`);f.push(Buffer.from(d.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[h,v,p]=await Promise.all([o.stat(),Ce.lstat(e),Ce.realpath(e)]);if(await aw(i),!v.isFile()||v.isSymbolicLink()||p!==a||!Pa(s,h)||!Pa(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(f,u).toString("utf8"))}finally{await o.close()}}function Rr(e,t){if(!cw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function c_(e){return Rr("reports",e)}async function Ra(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>_t||sw("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return ni({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function lw(e){let t=Gd(e.paths,e.name,"reports",e.hash),r=Ie(e.paths,t);await U(r,t);let i=await Ce.lstat(t);if(await Aa(e.paths,e.name,e.hash),await U(r,t),!Pa(i,await Ce.lstat(t)))throw new Error("Native report evidence changed before rollback");await Ce.unlink(t)}async function Aa(e,t,r,i,n){if(!cw.test(r))throw new Error("Native report evidence hash is invalid");let a=await It({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||sw("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function ii(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function Gd(e,t,r,i,n){let a=Rr(r,i);return n?pt.join(n,...a.split("/")):Hu(Ge(e,t),a)}async function It(e){let t=Gd(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ie(e.paths,t);return await U(r,t),s_(t,r,e.hooks)}async function ni(e){uc(e.value);let t=Gd(e.paths,e.name,e.kind,e.hash),r=Ie(e.paths,t);await U(r,t);try{let n=await It(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Rr(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await pe(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await It(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Rr(e.kind,e.hash)}function uc(e){if(l_(e)>_t)throw new Error(`Native evidence document exceeds ${_t} bytes`)}function l_(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
190
- `,"utf8")}function ow(e,t){return rc(e,t)}function u_(e,t){let r=nc(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function uw(e,t,r){let i=iw(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Ud(e,t,r){let i=Md(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function d_(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function f_(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,f=typeof s=="number"?s:Number.NaN,u=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(f)||!Number.isSafeInteger(u)||l<0||f<0||u<0||f+u>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:f,skipped:u}}async function Kd(e,t,r,i=!1,n){let a=await _a(e,t,r.implementationScopeRef,void 0,n);if(i&&await Aa(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await Yd(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function p_(e){let t=Ea(e.bundle),{baseline:r,current:i,scope:n}=t;return uc(r),uc(i),uc(n),await ni({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await ni({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),ni({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function dc(e,t,r,i,n){let a=ii(r,"scopes"),o=u_(await It({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=ii(o.baselineProjectionRef,"snapshots"),c=ii(o.currentProjectionRef,"snapshots"),[l,f]=await Promise.all([It({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(u=>ow(u,s)),It({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(u=>ow(u,c))]);return Yg({baseline:l,current:f,scope:o})}async function _a(e,t,r,i,n){return(await dc(e,t,r,i,n)).scope}async function h_(e){let t=uw(e.allowance,e.name,e.allowance.allowanceHash),r=await _a(e.paths,e.name,Rr("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return ni({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function Yd(e,t,r,i,n){let a=ii(r,"allowances");return uw(await It({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function dw(e){let t=zd(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return ni({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function fc(e,t,r,i,n){let a=ii(r,"receipts"),o=zd(await It({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function fw(e,t){let r=pt.join(Ge(e,t),"evidence","receipts");await U(Ie(e,r),r);let i;try{i=await Ce.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>Rr("receipts",n))}async function pw(e){let t=Ud(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Kd(e.paths,e.name,t,!0),ni({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Xd(e,t,r,i,n){let a=ii(r,"verifications"),o=Ud(await It({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Kd(e,t,o,!1,n),o}async function m_(e,t,r,i){let n=ii(r,"verifications"),a=await It({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=f_(a,t,n);if(o)return o;let s=Ud(a,t,n);return await Kd(e,t,s,!1,i),d_(s.acceptanceTrace)}var cw,_t,n_,Ar=C(()=>{"use strict";Q();K();yt();Gi();sc();lc();cw=/^[a-f0-9]{64}$/u,_t=ri,n_=3*_t});var vw={};Ga(vw,{executeNativeSupervisorChecks:()=>tf,readNativeSupervisorCheckEvidence:()=>pc});import{createHash as v_,randomUUID as g_}from"node:crypto";import{promises as w_}from"node:fs";import mw from"node:path";function ef(e){return v_("sha256").update(e).digest("hex")}function Qd(e,t){if(T(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||T(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!qt(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function Zd(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function tf(e){if(e.plans.length===0||new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:s})=>!s))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:s,content:c})=>!s.trim()||Buffer.byteLength(c)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=_("comet.native.supervisor-check-plan.v1",{plans:e.plans,materials:e.materials}),r=await R(e.paths,"reserve Supervisor checks",async()=>{let s=await D(e.paths,e.parent),c=Zd(s,e.child,e.runId);Qd(e.parent,c),e.plans.forEach(f=>br(c.projectRoot,f));let l=c.checkExecution;if(l?.status==="running"){let f=await zi(l.ownerPid,l.ownerIdentity),u=Date.parse(l.expiresAt??"")||Date.parse(l.startedAt)+3e4;if(f){if(!(Date.now()<u))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(l.key!==t)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(c),execute:!1}}let d=l.activeProcess;if(d===void 0||d?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${mw.join(ke(e.paths,e.parent),"logs","checks")} for operation ${l.operationId}; stop any remaining check process in ${c.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${c.runId}, and dispatch a new Verifier for the preserved candidate.`);if(d&&await zi(d.pid,d.identity)){if(!(Date.now()<u))throw new Error(`Native Supervisor check ${d.checkId} is still running as PID ${d.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(c),execute:!1}}l.status="interrupted"}return l?.status==="completed"&&l.key===t&&e.plans.every(({repeatable:f})=>f)?{task:structuredClone(c),execute:!1}:(c.checkExecution={operationId:g_(),key:t,status:"running",ownerPid:process.pid,ownerIdentity:await ei(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((f,u)=>f+u.timeoutMs,0)+3e4).toISOString()},c.checksReason="running",s.stateVersion+=1,await W(e.paths,s),{task:structuredClone(c),execute:!0})}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.receiptRef&&await pc({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=ke(e.paths,e.parent),o=async s=>{await R(e.paths,"register Supervisor check process",async()=>{let c=await D(e.paths,e.parent),l=Zd(c,e.child,e.runId);if(l.checkExecution?.operationId!==n||l.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");l.checkExecution.activeProcess=s,c.stateVersion+=1,await W(e.paths,c)})};try{let s=[];for(let u of e.plans){await o({status:"starting",checkId:u.id});let d=await Ur({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:u,onSpawn:async({pid:p})=>{await o({status:"running",checkId:u.id,pid:p,identity:await ei(p)??void 0})}});await o(null);let h=mw.join(a,d.logRef),v=await w_.readFile(h,"utf8");s.push({...d,logContent:Le(v).slice(0,128*1024)})}Qd(e.parent,i);let c={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:t,checks:s,materials:e.materials.map(({name:u,content:d})=>{let h=Le(d);return{name:u,content:h,hash:ef(h)}})},l=JSON.stringify(c),f=await Ra({paths:e.paths,name:e.parent,hash:ef(l),text:l});return await R(e.paths,"complete Supervisor checks",async()=>{let u=await D(e.paths,e.parent),d=Zd(u,e.child,e.runId);if(d.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Qd(e.parent,d),d.checkExecution.status="completed",d.checkExecution.receiptRef=f,d.checksReason="completed",u.stateVersion+=1,await W(e.paths,u)}),{status:"completed",operationId:n,receiptRef:f}}catch(s){throw await R(e.paths,"interrupt Supervisor checks",async()=>{let c=await D(e.paths,e.parent),l=c?.children.find(({name:f})=>f===e.child)?.task;l?.runId===e.runId&&l.checkExecution?.operationId===n&&(l.checkExecution.status="interrupted",l.checksReason="not-run",c.stateVersion+=1,await W(e.paths,c))}),s}}async function pc(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await Aa(e.paths,e.parent,t[1])),i=e.task;if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!Array.isArray(r.materials)||r.materials.some(({content:n,hash:a})=>ef(n)!==a))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var rf=C(()=>{"use strict";Qn();Vr();_d();ve();Ss();Ar();xe();K();Nr();ai()});import jt from"node:path";import{randomUUID as ww}from"node:crypto";import{promises as yw}from"node:fs";function Nw(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`}async function bw(e){let t=jt.join(".worktrees",`${e.parent}-integration`);return Td({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Nw(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function N_(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 Td({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:jt.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function b_(e,t){return jt.join(ke(e,t),"supervisor")}function Yi(e,t){return jt.join(b_(e,t),"state.json")}function kw(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!==nf)throw new Error(`Native Supervisor state schema must be ${nf}`);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[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Tt(t.integration.targetCommit,"Native Supervisor target commit"),Tt(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");Tt(n.candidateCommit,"Native Supervisor integration candidate commit"),Tt(n.integrationCommit,"Native Supervisor integration check commit")}if(!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 n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Tt(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Tt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function D(e,t,r={}){try{let i=await yw.readFile(Yi(e,t),"utf8"),n=JSON.parse(i);if(kw(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(ja(),Aw)),{readNativePortableState:l}=await Promise.resolve().then(()=>(Ft(),Vu)),f=await l(jt.join(o.changesDir,t,"comet-state.yaml")),u=await s({changeDir:jt.join(o.changesDir,t),acceptanceIds:f.acceptance.map(({id:d})=>d),validation:c(f)});if(!u)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let d of n.children)u.contract.children.some(({name:h})=>h===d.name)&&(d.acceptanceScope=hc(u.contract,d.name),d.contractHash=_("comet.native.supervisor-contract.v1",u.contract),d.task&&(d.task.acceptance=structuredClone(d.acceptanceScope),d.task.contractHash=d.contractHash,d.task.verificationBoundary="child-scope-parent-reverifies-all",d.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Ft(),Vu)),s=await o(jt.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function W(e,t){kw(t),await yw.mkdir(e.changesRuntimeDir,{recursive:!0}),await pe(Yi(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Tt(e,t){if(!y_.test(e))throw new Error(`${t} must be a Git commit`)}function ht(e){return structuredClone(e)}function $t(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function k_(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function S_(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function af(e){Tt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:hc(e.contract,i.name),contractHash:_("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:nf,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 hc(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function vc(e){let t=Nw(e.parent),r=xi(e.paths.projectRoot,t);if(!r)return null;let i=xi(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Lr(e.paths.projectRoot).map(o=>jt.resolve(o)).find(o=>X(o).currentBranch===t);if(!n)return null;let a=af({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return $t(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Sw(e){let t=ht(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=hc(e.contract,n.name),s=_("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.status=n.candidateCommit?"needs-reverify":"ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."),n.acceptanceScope=o,n.contractHash=s}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:hc(e.contract,n.name),contractHash:_("comet.native.supervisor-contract.v1",e.contract)});return t.stateVersion+=1,t}function of(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=ht(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);k_(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,$t(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function E_(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function Ew(e,t){let r=E_(e,t),i=ht(e);return $t(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function x_(e,t,r){let i=X(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!qt(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=T(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return T(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return T(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(T(e,["merge","--ff-only",r]),T(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function mc(e){if(!qt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=T(e.integration.worktree,["rev-parse","--show-toplevel"]);if(jt.resolve(t)!==jt.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=T(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return T(e.integration.worktree,["rev-parse","HEAD"])}function C_(e,t,r){let i=X(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!qt(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(T(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function sf(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=ht(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,$t(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function gc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=ht(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,$t(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function xw(e){return R(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await D(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Te(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let u;try{u=await N_({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?C_(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):x_(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(h){let v=ht(o),p=v.children.find(({name:m})=>m===l.name);p&&(p.blocker=h.message,$t(v,{kind:"task-blocked",child:l.name,runId:null,summary:p.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let d=of(o,{role:f?"verifier":"builder",child:l.name,projectRoot:u.projectRoot,runId:ww()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await W(e.paths,o),{state:o,tasks:s}})}function Cw(e,t){Tt(t.candidateCommit,"Native Supervisor candidate commit");let r=ht(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,$t(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Pw(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=ht(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return Qu({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),$t(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function gw(e,t){Tt(t.integrationCommit,"Native Supervisor integration commit");let r=ht(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,$t(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function Rw(e){let t=await R(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let u=await D(e.paths,e.state.parent)??e.state,d=u.integration.checkExecution;if(d?.status==="running"){if(await zi(d.ownerPid,d.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(d.activeProcess===void 0||d.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(d.activeProcess&&await zi(d.activeProcess.pid,d.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(u.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let h=u.children.find(({name:w})=>w===e.name);if(!h)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=S_(u).find(({status:w})=>w!=="integrated"&&w!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(h.status!=="verified"||!h.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:N})=>!N))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:N})=>N)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(e.checkPlans.forEach(N=>br(u.integration.worktree,N)),!h.verification?.receiptRef||!h.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:w}=await Promise.resolve().then(()=>(rf(),vw)),y=await w({paths:e.paths,parent:u.parent,task:h.verification.execution,receiptRef:h.verification.receiptRef});if(y.candidateCommit!==h.verifiedCommit||y.checks.some(({status:N})=>N!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let p=mc(u);if(p!==u.integration.headCommit){let w=(()=>{try{return T(u.integration.worktree,["merge-base","--is-ancestor",u.integration.headCommit,p]),!0}catch{return!1}})(),y=(()=>{try{return T(u.integration.worktree,["merge-base","--is-ancestor",h.verifiedCommit,p]),!0}catch{return!1}})();if(!w||!y)throw new Error(`Native Supervisor integration head drifted: expected ${u.integration.headCommit}, got ${p}`)}try{T(u.integration.worktree,["cat-file","-e",`${h.verifiedCommit}^{commit}`])}catch(w){throw new Error(`Native Supervisor verified commit is unavailable: ${h.verifiedCommit}`,{cause:w})}if(p===u.integration.headCommit){try{T(u.integration.worktree,["merge","--no-ff","--no-edit",h.verifiedCommit])}catch(w){throw new Error(`Native Supervisor integration conflict preserved in ${u.integration.worktree}`,{cause:w})}p=T(u.integration.worktree,["rev-parse","HEAD"])}let m=p;if(e.checkPlans){let w=ww(),y=_("comet.native.supervisor-integration-plan.v1",{child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:m,plans:e.checkPlans});return u.integration.checkExecution={operationId:w,key:y,child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:m,status:"running",ownerPid:process.pid,ownerIdentity:await ei(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null},u.stateVersion+=1,await W(e.paths,u),{pending:{state:u,candidateCommit:h.verifiedCommit,integrationCommit:m,operationId:w,key:y}}}let g=gw(u,{name:e.name,integrationCommit:m,checks:e.checks});return await W(e.paths,g),{completed:g}});if(t.completed)return t.completed;let{state:r,candidateCommit:i,integrationCommit:n,operationId:a,key:o}=t.pending,{writeNativeVerificationReportSnapshot:s}=await Promise.resolve().then(()=>(Ar(),hw)),{createHash:c}=await import("node:crypto"),l=async f=>R(e.paths,"record Supervisor integration check process",async()=>{let u=await D(e.paths,r.parent),d=u?.integration.checkExecution;if(!u||d?.operationId!==a||d.key!==o||d.status!=="running")throw new Error("Native Supervisor integration check operation is stale");d.activeProcess=f,u.stateVersion+=1,await W(e.paths,u)});try{let f=[];for(let p of e.checkPlans)await l({status:"starting",checkId:p.id}),f.push(await Ur({projectRoot:r.integration.worktree,runtimeDir:ke(e.paths,r.parent),operationId:a,plan:p,onSpawn:async({pid:m})=>l({status:"running",checkId:p.id,pid:m,identity:await ei(m)??void 0})})),await l(null);let u=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:r.parent,child:e.name,candidateCommit:i,integrationCommit:n,operationId:a,planHash:o,results:f}),d=await s({paths:e.paths,name:r.parent,hash:c("sha256").update(u).digest("hex"),text:u}),h=f.map(p=>({name:p.name,status:p.status==="interrupted"?"incomplete":p.status,reason:p.status==="passed"?null:p.timedOut?"timed out":`exit ${p.exitCode??p.signal??"interrupted"}`,receiptRef:d})),v=h.filter(({status:p})=>p!=="passed");return await R(e.paths,"complete Supervisor integration checks",async()=>{let p=await D(e.paths,r.parent),m=p?.children.find(({name:y})=>y===e.name),g=p?.integration.checkExecution;if(!p||!m||g?.operationId!==a||g.key!==o||g.status!=="running"||g.child!==e.name||g.candidateCommit!==i||g.integrationCommit!==n||m.verifiedCommit!==i||mc(p)!==n)throw new Error("Native Supervisor integration changed during checks");if(g.receiptRef=d,g.checks=h,v.length>0){let y=`Native Supervisor integration checks did not pass (${v.map(({name:N,reason:k})=>`${N}: ${k}`).join("; ")}); receipt ${d}`;throw g.status="interrupted",g.error=y,m.blocker=y,p.stateVersion+=1,await W(e.paths,p),new Error(y)}g.status="completed";let w=gw(p,{name:e.name,integrationCommit:n,checks:h});return await W(e.paths,w),w})}catch(f){throw await R(e.paths,"interrupt Supervisor integration checks",async()=>{let u=await D(e.paths,r.parent),d=u?.integration.checkExecution;u&&d?.operationId===a&&d.key===o&&d.status==="running"&&(d.status="interrupted",d.error=f.message,u.stateVersion+=1,await W(e.paths,u))}),f}}function P_(e,t){if(Tt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=ht(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ia(e){let t=mc(e);if(t===e.integration.headCommit)return e;try{T(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=ht(e);return r.integration.headCommit=t,$t(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ta(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=mc(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return P_(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function cf(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var nf,y_,ai=C(()=>{"use strict";Qn();Q();ve();Ss();ia();xe();K();lt();rt();Pg();Vr();_d();jd();nf="comet.native.supervisor.v2",y_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var Aw={};Ga(Aw,{NATIVE_CHILDREN_FILE:()=>lf,NATIVE_CHILDREN_SCHEMA:()=>oi,NATIVE_CHILDREN_SCHEMA_V2:()=>pf,NATIVE_CHILDREN_V2_SCHEMA:()=>si,findNativeV1SupervisorParents:()=>Vw,hasNativeSupervisorShapeIntent:()=>Bw,hashNativeParentContract:()=>Xi,inspectNativeChildren:()=>Qe,nativeChildrenAcceptanceValidation:()=>ci,nativeChildrenIndexDrift:()=>Hw,parseNativeChildrenContract:()=>Dw,readNativeChildrenContract:()=>Ot,readNativeSupervisorShapeIntent:()=>$a});import{promises as df}from"node:fs";import $e from"node:path";function yc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function wc(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Iw(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,i)=>r.localeCompare(i,"en"))}function uf(e,t){let r=$e.normalize($e.resolve(e)),i=$e.normalize($e.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function j_(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Tw(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Hw(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===pf&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let f=s.get(l),u=e.acceptance_index[l];f&&u&&(u.source!==f.source||u.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!jw(e.children,l)),$w(i)?i:null}if(e.schema===oi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!jw(e.children,a)),$w(i)?i:null}return null}function jw(e,t){return e.some(r=>r.covers.includes(t))}function $w(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function ci(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function $_(e){let t=yc(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=yc(n,`Native children acceptance_index.${i}`);if(wc(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function O_(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let f=c.get(l);if(!f)continue;let u=e[l];if(u.source!==f.source||u.text!==f.text){let d=["source","text"].filter(h=>u[h]!==f[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function Dw(e,t,r={}){let i=(0,ff.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=yc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==oi&&a!==si)throw wc(n,_w,"Native children contract"),new Error(`Native children schema must be ${oi} or ${si}`);let o=a===oi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(wc(n,o==="indexed-v2"?A_:_w,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,h)=>{let v=yc(d,`Native child ${h}`);if(wc(v,o==="indexed-v2"?T_:o==="summary-v2"?I_:__,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!R_.test(v.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:p?v.summary:null,depends_on:Iw(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Iw(v.covers,`Native child ${v.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 f=new Set(l);for(let d of c){let h=d.depends_on.filter(v=>!f.has(v));if(h.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${h.join(", ")}`)}j_(c);let u=r.policy==="advisory";if(a===pf){if(o==="indexed-v2"){let d=$_(n.acceptance_index);u||O_(d,t,r);let h=Object.keys(d);return u||Tw(c,h,h),{schema:si,acceptance_index:d,children:c}}return{schema:si,children:c}}return t&&!u&&Tw(c,t),{schema:oi,children:c}}async function Ot(e){let t=$e.join(e.changeDir,lf);try{await df.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ie({root:e.changeDir,ref:lf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Dw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Hw(a,e.acceptanceIds,e.validation??{}):null}}function H_(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function Bw(e){let t=H_(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function $a(e){try{let t=await ie({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return Bw(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xi(e){return _("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function Lw(e){let t=Lr(e.projectRoot);t.some(i=>uf(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>$e.resolve(n)))]){let n=await Te(i);n&&r.push({projectRoot:i,paths:await yr(i,n.native.artifact_root),parent:uf(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Vw(e){let t=await Lw(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await df.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=$e.join(a.paths.changesDir,s.name),l;try{l=await Be($e.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let f=await Ot({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:u})=>u)}:{}});!f||f.contract.schema!==oi||f.contract.children.some(({name:u})=>u===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:h})=>h.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:h,state:v})=>X(h.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let h=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(h)i.push(`Native Supervisor parent ${a} targets ${h.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:f}=c,u=l.paths,d=await Qe({paths:u,state:f});if(!d)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!d.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(d.allDone)r.push({paths:u,state:f,inspection:d});else{let h=d.children.filter(({status:v})=>v!=="done").map(({name:v,status:p,message:m})=>`${v}=${p}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${h||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function D_(e,t){let r=$e.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Be(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function B_(e,t){let r;try{r=await df.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=$e.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Be(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function L_(e,t,r){let i=$e.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${$e.sep}`))return null;let n=i.split($e.sep).join("/");try{let a=(0,ff.parseDocument)(T(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:I(a.toJS({mapAsMap:!1}))}catch{return null}}function V_(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 Ow(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Qe(e){let t=$e.join(e.paths.changesDir,e.state.name),r=await $a(t),i=null,n;try{n=await Ot({changeDir:t,validation:ci(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(g){let w=cf(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Xi({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===si){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let k=await vc({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});k&&(g=k,await W(e.paths,k))}}if(g){let N=cf(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(k=>({...k,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let w=new Map(n.contract.children.map(N=>[N.name,N])),y=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(k=>n.contract.children.filter(({name:b})=>b!==N.name).every(({name:b})=>b!==k))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of y){if(N.status!=="ready")continue;w.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:y,readyChildren:y.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await Lw(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),f=new Map,u=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let y of await B_(g,l)){let N={...y,source:g,committedState:L_(g,y.file,w)};f.set(y.state.name,[...f.get(y.state.name)??[],N])}for(let y of l){let N=await D_(g,y);N&&u.set(y,[...u.get(y)??[],{source:g,state:N}])}}let d=new Map;for(let g of n.contract.children){let w=(f.get(g.name)??[]).find(({source:k,committedState:b})=>k.parent&&b?.name===g.name&&Ow(b,o));if(w){d.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=f.get(g.name)?.[0];if(y){d.set(g.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=u.get(g.name)??[];N.length>1?d.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&d.set(g.name,V_(N[0].state,N[0].source,o))}let h=new Map(n.contract.children.map(g=>[g.name,g])),v=new Map,p=g=>{let w=v.get(g);if(w)return w;let y=h.get(g),k=y.depends_on.map(p).every(({status:M})=>M==="done"),b=d.get(g),P=b?.kind==="active"&&k?y.depends_on.filter(M=>!(f.get(M)??[]).some(({source:$,committedState:de})=>uf($.projectRoot,b.projectRoot)&&de?.name===M&&Ow(de,o))):[],S,E=b?.message??null;b?.kind==="done"?(S=k?"done":"blocked",k||(E=`Native child ${g} was merged before its dependencies`)):b?.kind==="active"?(S=k&&P.length===0?"active":"blocked",k?P.length>0&&(E=`Native child ${g} does not include merged dependencies: ${P.join(", ")}`):E=`Native child ${g} started before its dependencies merged`):b?.kind==="blocked"?S="blocked":(S=s&&k?"ready":"pending",s||(E="Parent Shape confirmation is required"));let A={name:g,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:S,phase:b?.phase??null,projectRoot:b?.projectRoot??null,message:E};return v.set(g,A),A},m=n.contract.children.map(({name:g})=>p(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:m.every(({status:g})=>g==="done")}}var ff,lf,oi,si,pf,R_,_w,A_,__,I_,T_,ja=C(()=>{"use strict";ff=nn(Si(),1);rt();Vr();at();ve();lt();K();Ft();ai();lf="children.yaml",oi="comet.native.children.v1",si="comet.native.children.v2",pf=si,R_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_w=new Set(["schema","children"]),A_=new Set(["schema","acceptance_index","children"]),__=new Set(["name","depends_on","covers"]),I_=new Set(["name","summary","depends_on"]),T_=new Set(["name","depends_on","covers"])});ja();Hi();function Kt(e,t,r){return e.language==="zh-CN"?r:t}function M_(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return 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{required:!0,message:Kt(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Kt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Kt(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(Kt(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 r(Kt(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return 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 n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"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:o,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."}}return r(Kt(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 F_(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 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 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 a complete dry-run first, then return one confirmed command; 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 containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function q_(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:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:Kt(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Kt(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Fw(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function li(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function W_(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Mw(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function z_(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function J_(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function _r(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Fw({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[li("summary","--summary"),W_(e.name,e.flag)]}}function hf(e){return[_r({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),_r({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function te(e,t,r={}){let i=z_(t)&&e.coordination_mode===void 0,n=M_(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...hf({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),_r({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...hf({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:hf({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Fw({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:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:J_({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Mw("coordination-mode","--coordination-mode",hs)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"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:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:f})=>f==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),l=t.children.some(({status:f})=>f==="ready"||f==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[li("summary","--summary")],runnerAction:o("none")}}return{...a,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:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Kt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",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":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,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:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(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;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Mw("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...q_(e)],userCommunication:F_(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[_r({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}rt();Q();at();ye();xe();bd();Ys();zs();import{randomUUID as yI}from"node:crypto";import{promises as Va}from"node:fs";import NI from"node:path";rt();Q();import{createHash as SV,randomUUID as Sf}from"node:crypto";import{promises as ui}from"node:fs";import ue from"node:path";Xr();ye();at();St();K();var U_=["outcome","scope","nonGoals","acceptanceExamples"],iV=[...U_,"constraints","decisions","openQuestions","verificationExpectations"];function qw(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}at();ve();ja();ai();ye();Ss();Ft();wa();Kr();ia();import{randomUUID as K_}from"node:crypto";var Oa=3,mf=2;function Pe(e){return e.state_version+1}function Y_(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function vf(e){return e.map(t=>({...t,result:"pending",reason:null}))}function gf(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function X_(e){return(e??[]).map(t=>({name:F(t.name),result:t.result,note:t.note?F(t.note):null}))}function Yt(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:F(e.summary),completed_at:e.completedAt}}function Ww(e){let t=I(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:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return I({...t,phase:"build",status:"active",state_version:Pe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function zw(e){let t=I(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:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return I({...t,status:"await-user",state_version:Pe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Jw(e){let t=I(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(!pv(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=Y_(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):vf(t.acceptance),o=(r.now??new Date).toISOString();return I({...t,phase:"verify",state_version:Pe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??K_(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:F(r.summary),addressed_acceptance_ids:i,checks:X_(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>F(s)),known_limits_truncated:!1,review:{status:"passed",summary:F(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Gw(e){let t=I(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return I({...t,state_version:Pe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Q_(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function Z_(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.identityProvider===ne?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:F(e.response.result.summary),risks:e.response.result.risks.map(t=>F(t)),risks_truncated:!1,completed_at:e.completedAt}}function Uw(e){let t=I(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=gf(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=hv({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(m=>[m.id,m])),o=t.acceptance.map(m=>{let g=a.get(m.id);return g?{...m,result:g.result,reason:F(g.reason)}:m}),s=o.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),c=Z_({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let w=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:I({...w,state_version:Pe(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:vf(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let m=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===ne;return{response:i,state:I({...m,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:Pe(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:F("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:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:I({...m,status:"await-user",state_version:Pe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:F(i.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,f=Q_(t,s),u=l>=e.maxVerifyFailures,d=f>=3,h=u||d,v=d?"stalled":u?"budget":void 0,p=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:I({...p,phase:h?"verify":"build",status:h?"await-user":"active",state_version:Pe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:h?[{owner:"user",reason:F(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:F("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:h?"await-user":"repairing",iteration:h?t.loop.iteration:t.loop.iteration+1,attempt:h?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:h?"await-user":"repair-failed-acceptance"}})}}function Kw(e){let t=I(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==ne||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 I({...t,phase:"archive",status:"active",state_version:Pe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Yw(e){let t=I(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==ne||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=gf(t),n=we(t,Yt({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return I({...n,status:"await-user",state_version:Pe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:F(e.summary),risks:[F("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:F("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Xw(e){let t=I(e.state);if(t.phase!=="verify"||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")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=F(e.summary),n=we(t,Yt({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return I({...n,phase:"archive",status:"active",state_version:Pe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:F(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Qw(e,t){let r=I(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:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=we(r,Yt({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return I({...i,status:"active",state_version:Pe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Zw(e){let t=I(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(),i=t.loop.execution_failure_count+1,n=i>=Oa,a=we(t,Yt({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return I({...a,status:n?"blocked":"active",state_version:Pe(t),blockers:n?[{owner:"runtime",reason:F(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function ey(e){let t=I(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=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:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=gf(t),a=t.acceptance.some(({result:o})=>o==="passed");return I({...t,status:"active",state_version:Pe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Ha(e){let t=I(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.now??new Date).toISOString(),i=we(t,Yt({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?vf(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return I({...i,phase:"build",status:"active",state_version:Pe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}Q();Hi();import{promises as ry}from"node:fs";import Da from"node:path";function Nc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bc(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ht(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function ty(e,t){return e===null?null:Ht(e,t)}function Sc(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 eI(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function tI(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function kc(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function wf(e,t){if(e===null)return null;let r=Ht(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function yf(e,t){let r=Ht(e,t);if(!Da.isAbsolute(r))throw new Error(`${t} must be absolute`);return Da.resolve(r)}function rI(e,t){let r=`Native local checks[${t}]`,i=Nc(e,r);if(bc(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>Ht(l,`${r}.argv[${f}]`,!0)),a=kc(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=wf(i.startedAt,`${r}.startedAt`),s=wf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Sc(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Ht(i.id,`${r}.id`),name:Ht(i.name,`${r}.name`),operationId:Ht(i.operationId,`${r}.operationId`),status:a,repeatable:tI(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Sc(i.executionCount,`${r}.executionCount`),argv:n,cwd:yf(i.cwd,`${r}.cwd`),exitCode:eI(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Ht(i.log,`${r}.log`)}}function Nf(e){let t="Native local execution state",r=Nc(e,t);if(bc(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Kn)throw new Error(`Native local execution schema must be ${Kn}`);let i=Nc(r.workspace,"Native local workspace");bc(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Nc(r.execution,"Native local execution");bc(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=wf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ht(o.operationId,"Native local execution.operationId"),stage:kc(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:kc(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ty(o.executionId,"Native local execution.executionId"),status:kc(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Sc(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(rI);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Kn,change:Ht(r.change,"Native local change"),basedOnStateVersion:Sc(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:yf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:yf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ty(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function le(e){return Nf({schema:Kn,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Da.resolve(e.projectRoot),worktreeRoot:Da.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Dt(e){let t;try{t=await ry.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Nf(r)}async function G(e,t,r={}){let i=Nf(t);await ry.mkdir(Da.dirname(e),{recursive:!0}),await pe(e,i,r)}async function bf(e){let t=null,r=null;try{t=await Dt(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=le(e);return await G(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}xe();zs();Ft();Ys();wa();Kr();ia();Q();Xr();Kr();import{promises as iI}from"node:fs";function Ir(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
188
+ `),e.omissionOverflow&&xr(a,"existing-overflow",e.omissionOverflow);let o=(d,h)=>{h||(i+=1),n+=1,xr(a,"omission",d)},s=d=>{i+=1,n+=1,xr(a,"entry",d)},c=()=>{for(let d=r.length-1;d>=0;d-=1){let h=r[d];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return r.splice(d,1),h}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),f=l();for(;ka(f)>ri;){if(r.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(r.length/4));for(let v=0;v<h;v+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");f=l()}let u=a.digest("hex");return{...f,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${u}`,hash:u,count:n}}}function SA(e){let t=sd(e),r=t.entries.map((n,a)=>wA(n,`Snapshot entry ${a}`));if(r.sort(NA),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>yA(n,`Snapshot omission ${a}`));return i.sort(bA),kA({schema:Fg,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function ic(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:Cr(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>be(r.path,i.path)||be(r.kind,i.kind))}function Sa(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Og(e){return e?{hash:e.hash,size:e.size}:null}function zg(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:be(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let f=c?.path??l?.path;f!==void 0&&r({path:f,kind:c?l?"modified":"removed":"added",before:Og(c),after:Og(l)})}}function EA(e,t){return{...e,attributedTo:t.filter(r=>Sa(r,e.path))}}function Gt(e,t){return{id:`scope:${_(fA,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function xA(e,t){let r=t.omitted.map(i=>Gt({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(Gt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Gt({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function Hg(e,t){return xA(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Hd(e,t){return be(e.kind,t.kind)||be(e.source,t.source)||gA(e.path,t.path)||be(e.id,t.id)}function CA(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Hd)}function Jg(e){return[...new Set(e.map((t,r)=>Cr(t,`Git path ${r}`)))].sort(be)}function Dg(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function PA(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Gg(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Jg(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Dg(e.baseCommit,"Native external drift base commit"),targetBranch:PA(e.targetBranch,"Native external drift target branch"),targetCommit:Dg(e.targetCommit,"Native external drift target commit"),paths:t}}function RA(e){if(typeof e.contractHash!="string"||!Dd.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ic(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Jg(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Gg(e.externalDrift)}}}function AA(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,f=!1,u=0,d=0;return zg(e,t,h=>{let v=r.some(p=>Sa(p,h.path));if(u+=1,c.push(h.path),!v&&!n?.has(h.path)&&(d+=1),o?.has(h.path)&&s.push(h.path),!f&&a.length<mA){let p=EA(h,r),m=ka(p);l+m<=ri?(a.push(p),l+=m):f=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:u,totalUnattributed:d}}function Ug(e,t){return Gt({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function _A(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:Ji(Number(t[1]),"Scope overflow change count"),unresolved:Ji(Number(t[2]),"Scope overflow unresolved count"),unattributed:Ji(Number(t[3]),"Scope overflow unattributed count")},i=ti(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Ug(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function IA(e){let t=Mg("sha256");t.update(`${pA}
189
+ `);let r=0;zg(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){xr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Sa(o,n.path)&&(a+=1,xr(t,"change-attribution",o));xr(t,"change-end",{attributionCount:a}),a===0&&xr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&xr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function TA(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=AA(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let P=new Set(r.externalDrift.paths),S=new Set(o.changePaths),E=r.externalDrift.paths.filter(A=>!S.has(A)||n.some(M=>Sa(M,A)));if(E.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${E.slice(0,8).join(", ")}`);if(P.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=_(Na,e),c=_(Na,t),l=[],f=new Set(r.externalDrift?.paths??[]);for(let[P,S]of[["baseline",e],["current",t]])for(let E of S.omitted){if(l.length>=vA)break;l.push(Gt({kind:"snapshot-omission",source:P,path:E.path,evidence:{reason:E.reason,size:E.size,type:E.type}},`${P} snapshot omitted ${E.path}: ${E.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Hg("baseline",e),...Hg("current",t),...o.totalChanges===0&&a===null?[Gt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(r.gitChangedPaths===void 0)return;let P=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(S=>P.has(S)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(S=>!P.has(S))}},v=P=>{let S=o.candidates.slice(0,P.detailedChangeCount),E=S.filter(ae=>ae.attributedTo.length===0&&!f.has(ae.path)),A=o.totalChanges-S.length,M=o.totalUnattributed-E.length,$=u-P.detailedOmissionCount,de=M+$,rr=[...E.map(ae=>Gt({kind:"unattributed-change",source:"implementation-scope",path:ae.path,evidence:{after:ae.after,before:ae.before,changeKind:ae.kind}},`Changed path is not covered by a declared artifact: ${ae.path}`)),...l.slice(0,P.detailedOmissionCount),...d,...de>0?[Ug(P.overflowHash,{changes:A,unattributed:M,unresolved:de})]:[]],gt=CA(rr),Oe=P.includeGitAdvisory?h():void 0;return{schema:$d,contractHash:i,baselineProjectionRef:Od(s),baselineProjectionHash:s,currentProjectionRef:Od(c),currentProjectionHash:c,complete:gt.length===0,declaredArtifacts:n,changes:S,unattributed:E,unresolvedScopes:gt,noCodeReason:a,...Oe?{gitAdvisory:Oe}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},p=o.candidates.length,m=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let P=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:w});if(ka({...P,scopeHash:w})<=ri)break;if(g){g=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>p||u>m?IA({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:m}):w,k=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:N}),b={...k,scopeHash:_(qg,k)};if(ka(b)>ri)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function At(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _t(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function ti(e,t){if(typeof e!="string"||!Dd.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Bg(e,t,r){let i=Od(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function rc(e,t){let r=At(e,"Native snapshot projection");if(_t(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==Fg)throw new Error("Native snapshot projection schema is invalid");let i=sd({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=SA(i);if(_(Na,r)!==_(Na,n))throw new Error("Native snapshot projection is not canonical");let a=_(Na,n);if(t!==void 0&&ti(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Bd(e,t){let r=At(e,`Declared artifact ${t}`);if(_t(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Cr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Lg(e,t){if(e===null)return null;let r=At(e,t);return _t(r,["hash","size"],[],t),{hash:ti(r.hash,`${t} hash`),size:Ji(r.size,`${t} size`)}}function Vg(e,t){let r=At(e,`Implementation change ${t}`);if(_t(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Bd),n=ic(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Lg(r.before,`Implementation change ${t} before`),o=Lg(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Cr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function $A(e,t){let r=At(e,`Unresolved scope ${t}`);_t(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?Wg(r.path,`Unresolved scope ${t} path`):Cr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function ba(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>Cr(n,`${t} ${a}`)),i=[...new Set(r)].sort(be);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function Kg(e){let t=At(e,"Native implementation external drift");if(_t(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=ba(t.paths,"Native external drift paths");return Gg({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function nc(e){let t=At(e,"Native implementation scope"),r=[...jA].filter(E=>E!=="gitAdvisory"&&E!=="externalDrift");if(_t(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==$d)throw new Error("Native implementation scope schema is invalid");let i=ti(t.contractHash,"Implementation scope contractHash"),n=ti(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Bg(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=ti(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Bg(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Bd);if(JSON.stringify(c)!==JSON.stringify(ic(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Vg),f=[...l].sort((E,A)=>be(E.path,A.path));if(JSON.stringify(l)!==JSON.stringify(f)||new Set(l.map(E=>E.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let u=new Set(c.map(E=>`${E.kind}:${E.path}`));if(l.some(E=>E.attributedTo.some(A=>!u.has(`${A.kind}:${A.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(E=>JSON.stringify(E.attributedTo)!==JSON.stringify(c.filter(A=>Sa(A,E.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(Vg),h=t.externalDrift===void 0?void 0:Kg(t.externalDrift),v=new Set(h?.paths??[]),p=l.filter(E=>E.attributedTo.length===0&&!v.has(E.path));if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map($A),g=m.filter(E=>E.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:_A(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,N=[...p.map(E=>Gt({kind:"unattributed-change",source:"implementation-scope",path:E.path,evidence:{after:E.after,before:E.before,changeKind:E.kind}},`Changed path is not covered by a declared artifact: ${E.path}`)),...l.length+(w?.changes??0)===0&&y===null?[Gt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(E=>E.kind==="unattributed-change"||E.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Hd))||new Set(m.map(E=>E.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(Hd))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let E=At(t.gitAdvisory,"Implementation scope Git advisory");if(_t(E,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),E.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let A=ba(E.changedPaths,"Git changed paths"),M=ba(E.pathsPresentInSnapshotChanges,"Git present paths"),$=ba(E.pathsAbsentFromSnapshotChanges,"Git absent paths"),de=[...M,...$].sort(be);if(JSON.stringify(de)!==JSON.stringify(A)||$.some(rr=>l.some(gt=>gt.path===rr)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:A,pathsPresentInSnapshotChanges:M,pathsAbsentFromSnapshotChanges:$}}let P={schema:$d,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:y,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},S=ti(t.scopeHash,"Implementation scope scopeHash");if(_(qg,P)!==S)throw new Error("Implementation scope content hash mismatch");return{...P,scopeHash:S}}function OA(e){let t=At(e,"Native implementation scope authority");if(_t(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(Bd);if(JSON.stringify(r)!==JSON.stringify(ic(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=ba(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Kg(t.externalDrift),a=RA({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Ea(e){let t=At(e,"Native implementation scope bundle");_t(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=OA(t.authority),i=rc(t.baseline),n=rc(t.current),a=nc(t.scope),o=TA(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function Yg(e){let t=nc(e.scope);return Ea({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var $d,Fg,Na,qg,fA,pA,hA,Dd,ri,mA,vA,jA,Gi=C(()=>{"use strict";ve();aa();$d="comet.native.implementation-scope.v2",Fg="comet.native.content-snapshot-projection.v1",Na="comet.native.content-snapshot-projection.v1",qg="comet.native.implementation-scope.v2",fA="comet.native.unresolved-scope-id.v1",pA="comet.native.scope-detail-overflow.v1",hA="comet.native.snapshot-projection-overflow.v2",Dd=/^[a-f0-9]{64}$/u,ri=1024*1024,mA=128,vA=128;jA=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import Xg from"node:path";function Ut(e,t){if(!Zg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ew(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function tw(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Ld(e,t,r=2e3){let i=Le(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function xa(e,t){let r=Xg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||Xg.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function LA(e,t,r){let i=xa(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ci(i),a=i.toLowerCase(),o=r?xa(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function Vd(e){let t=xa(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Ui(e,t){return e<t?-1:e>t?1:0}function ac(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function oc(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function rw(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Qg(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function VA(e){let t=ac(e,"Native acceptance trace");if(oc(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Zg.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=xa(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=ac(o,`Native acceptance trace entry ${s}`);if(oc(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(u=>typeof u!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(u=>Vd(u)),f=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ui))||f==="passed"&&(l.length===0||c.skippedReason!==null)||f==="failed"&&l.length===0&&c.skippedReason===null||f==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:f,kind:c.kind,source:xa(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Ld(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Ui(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=Ut(t.traceHash,"Native acceptance trace hash");if(_(HA,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function iw(e){let t=ac(e,"Native partial allowance");if(oc(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Ui))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:tw(t.change),scopeHash:Ut(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Ld(t.reason,"Partial allowance reason"),confirmedSummary:Ld(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:ew(t.sourceRevision),confirmedAt:rw(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=Ut(t.allowanceHash,"Native partial allowance hash");if(_(DA,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Md(e){let t=ac(e,"Native verification evidence");if(oc(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=Ut(t.implementationScopeHash,"Native verification implementation scope hash"),i=VA(t.acceptanceTrace),n=Ut(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Ut(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>Vd(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ui)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Ui);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(d=>Vd(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ui)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let f={schema:"comet.native.verification-evidence.v2",change:tw(t.change),sourceRevision:ew(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ut(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Qg(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:LA(t.reportRef,"Native verification report ref"),reportHash:Ut(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:Qg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:rw(t.createdAt,"Native verification timestamp")},u=Ut(t.envelopeHash,"Native verification envelope hash");if(_(BA,f)!==u)throw new Error("Native verification evidence content hash mismatch");return{...f,envelopeHash:u}}var Zg,HA,DA,BA,sc=C(()=>{"use strict";ve();Nr();Hn();Gi();Zg=/^[a-f0-9]{64}$/u,HA="comet.native.acceptance-trace.v2",DA="comet.native.partial-allowance.v1",BA="comet.native.verification-evidence.v2"});var cc,MA,FA,qA,zB,WA,JB,Fd=C(()=>{"use strict";ve();cc="scoped-text-safety",MA=1,FA=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),qA="comet.native.checker-policy.v1",zB=_(qA,{policy:cc,version:MA,limits:FA,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),WA=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],JB=new Set(WA)});function Ki(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Pr(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Kt(e,t){if(typeof e!="string"||!JA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Le(e).trim();if(!r||r.length>YA||r!==e.trim())throw new Error(`${t} is invalid`);return r}function qd(e,t){let r=pt(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function Ca(e,t,r=pt,i=!1,n=XA){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function ZA(e,t){if(typeof e!="string"||!GA.test(e))throw new Error(`${t} is invalid`);return e}function e_(e){let t=Ki(e,"Native verification receipt bindings");if(Pr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!UA.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Kt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Kt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Kt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Kt(t.artifactHash,"Native verification receipt artifact hash")}}function t_(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=KA.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function r_(e,t,r,i){let n=Ki(t,`Native ${e} evidence`);if(e==="automated-check"){if(Pr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=qd(n.startedAt,"Native automated-check start time"),o=qd(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Ki(n.worktree,"Native automated-check worktree");if(Pr(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Ki(n.afterFence,"Native automated-check after fence");if(Pr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:pt(n.executable,"Native automated-check executable"),args:Ca(n.args,"Native automated-check arguments",pt,!0),cwd:pt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:pt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Kt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Kt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Kt(n.outputHash,"Native automated-check output hash"),outputSummary:pt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Pr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=t_(n.checkReceiptRef);if(Kt(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Ca(n.subjects,"Native static inspection subjects",pt,i==="required-check"),rule:pt(n.rule,"Native static inspection rule"),resultSummary:pt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Pr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Ca(n.steps,"Native manual evidence steps"),observations:Ca(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function i_(e){let t=Ki(e,"Native verification receipt");if(Pr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=pt(t.actor,"Native verification receipt actor"),o=Ca(t.acceptanceIds,"Native receipt acceptance IDs",ZA,i==="required-check",QA).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Wd,kind:r,role:i,status:n,bindings:e_(t.bindings),acceptanceIds:o,actor:a,issuedAt:qd(t.issuedAt,"Native verification receipt issue time"),evidence:r_(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==cc||s.actor!==`native-runtime:${cc}`))throw new Error("Native required check policy identity is invalid");return s}function zd(e){let t=Ki(e,"Native verification receipt");if(Pr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Wd)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=i_(i),a=Kt(t.receiptHash,"Native verification receipt hash");if(_(zA,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var Wd,zA,JA,GA,UA,KA,YA,XA,QA,lc=C(()=>{"use strict";ve();Fd();Nr();Wd="comet.native.verification-receipt.v3",zA=Wd,JA=/^[a-f0-9]{64}$/u,GA=/^acceptance-[a-f0-9]{64}$/u,UA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,YA=4096,XA=256,QA=1024});var hw={};Ga(hw,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>It,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>n_,listNativeVerificationReceiptRefs:()=>fw,nativeEvidenceRef:()=>Rr,nativeReportEvidenceRef:()=>c_,readArchivedNativeVerificationAcceptanceCounts:()=>m_,readNativeImplementationScope:()=>_a,readNativeImplementationScopeBundle:()=>dc,readNativePartialAllowance:()=>Yd,readNativeVerificationEvidence:()=>Xd,readNativeVerificationReceipt:()=>fc,readNativeVerificationReportSnapshot:()=>Aa,removeNativeVerificationReportSnapshot:()=>lw,writeNativeImplementationScope:()=>p_,writeNativePartialAllowance:()=>h_,writeNativeVerificationEvidence:()=>pw,writeNativeVerificationReceipt:()=>dw,writeNativeVerificationReportSnapshot:()=>Ra});import{createHash as sw}from"node:crypto";import{promises as Ce}from"node:fs";import ht from"node:path";function Jd(e,t){let r=ht.relative(e,t);return r===""||!ht.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ht.sep}`)}function a_(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pa(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return nt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function nw(e){let t=await Ce.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Ce.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function o_(e,t){let r=ht.resolve(e),i=ht.resolve(t);if(!Jd(r,i))throw new Error("Native evidence path is outside its change");let n=[await nw(r)],a=r;for(let o of ht.relative(r,i).split(ht.sep).filter(Boolean)){a=ht.join(a,o);let s=await nw(a);if(!Jd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function aw(e){for(let t of e){let r=await Ce.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!a_(t,r)||await Ce.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function s_(e,t,r={}){let i=await o_(t,ht.dirname(e));await r.afterParentChainCaptured?.();let n=await Ce.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Ce.realpath(e);if(!Jd(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Ce.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Ce.lstat(e),Ce.realpath(e)]);if(await aw(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Pa(s,n)||!Pa(s,c))throw new Error("Native evidence document changed while opening");if(s.size>It)throw new Error(`Native evidence document exceeds ${It} bytes`);await r.afterOpen?.();let f=[],u=0,d=Buffer.allocUnsafe(64*1024);for(;;){let m=It+1-u,g=await o.read(d,0,Math.min(d.length,m),null);if(g.bytesRead===0)break;if(u+=g.bytesRead,u>It)throw new Error(`Native evidence document exceeds ${It} bytes`);f.push(Buffer.from(d.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[h,v,p]=await Promise.all([o.stat(),Ce.lstat(e),Ce.realpath(e)]);if(await aw(i),!v.isFile()||v.isSymbolicLink()||p!==a||!Pa(s,h)||!Pa(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(f,u).toString("utf8"))}finally{await o.close()}}function Rr(e,t){if(!cw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function c_(e){return Rr("reports",e)}async function Ra(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>It||sw("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return ni({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function lw(e){let t=Gd(e.paths,e.name,"reports",e.hash),r=Ie(e.paths,t);await U(r,t);let i=await Ce.lstat(t);if(await Aa(e.paths,e.name,e.hash),await U(r,t),!Pa(i,await Ce.lstat(t)))throw new Error("Native report evidence changed before rollback");await Ce.unlink(t)}async function Aa(e,t,r,i,n){if(!cw.test(r))throw new Error("Native report evidence hash is invalid");let a=await Tt({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||sw("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function ii(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function Gd(e,t,r,i,n){let a=Rr(r,i);return n?ht.join(n,...a.split("/")):Hu(Ge(e,t),a)}async function Tt(e){let t=Gd(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ie(e.paths,t);return await U(r,t),s_(t,r,e.hooks)}async function ni(e){uc(e.value);let t=Gd(e.paths,e.name,e.kind,e.hash),r=Ie(e.paths,t);await U(r,t);try{let n=await Tt(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Rr(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await pe(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Tt(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Rr(e.kind,e.hash)}function uc(e){if(l_(e)>It)throw new Error(`Native evidence document exceeds ${It} bytes`)}function l_(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
190
+ `,"utf8")}function ow(e,t){return rc(e,t)}function u_(e,t){let r=nc(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function uw(e,t,r){let i=iw(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Ud(e,t,r){let i=Md(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function d_(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function f_(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,f=typeof s=="number"?s:Number.NaN,u=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(f)||!Number.isSafeInteger(u)||l<0||f<0||u<0||f+u>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:f,skipped:u}}async function Kd(e,t,r,i=!1,n){let a=await _a(e,t,r.implementationScopeRef,void 0,n);if(i&&await Aa(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await Yd(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function p_(e){let t=Ea(e.bundle),{baseline:r,current:i,scope:n}=t;return uc(r),uc(i),uc(n),await ni({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await ni({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),ni({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function dc(e,t,r,i,n){let a=ii(r,"scopes"),o=u_(await Tt({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=ii(o.baselineProjectionRef,"snapshots"),c=ii(o.currentProjectionRef,"snapshots"),[l,f]=await Promise.all([Tt({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(u=>ow(u,s)),Tt({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(u=>ow(u,c))]);return Yg({baseline:l,current:f,scope:o})}async function _a(e,t,r,i,n){return(await dc(e,t,r,i,n)).scope}async function h_(e){let t=uw(e.allowance,e.name,e.allowance.allowanceHash),r=await _a(e.paths,e.name,Rr("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return ni({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function Yd(e,t,r,i,n){let a=ii(r,"allowances");return uw(await Tt({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function dw(e){let t=zd(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return ni({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function fc(e,t,r,i,n){let a=ii(r,"receipts"),o=zd(await Tt({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function fw(e,t){let r=ht.join(Ge(e,t),"evidence","receipts");await U(Ie(e,r),r);let i;try{i=await Ce.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>Rr("receipts",n))}async function pw(e){let t=Ud(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Kd(e.paths,e.name,t,!0),ni({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Xd(e,t,r,i,n){let a=ii(r,"verifications"),o=Ud(await Tt({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Kd(e,t,o,!1,n),o}async function m_(e,t,r,i){let n=ii(r,"verifications"),a=await Tt({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=f_(a,t,n);if(o)return o;let s=Ud(a,t,n);return await Kd(e,t,s,!1,i),d_(s.acceptanceTrace)}var cw,It,n_,Ar=C(()=>{"use strict";Q();K();Nt();Gi();sc();lc();cw=/^[a-f0-9]{64}$/u,It=ri,n_=3*It});var vw={};Ga(vw,{executeNativeSupervisorChecks:()=>tf,readNativeSupervisorCheckEvidence:()=>pc});import{createHash as v_,randomUUID as g_}from"node:crypto";import{promises as w_}from"node:fs";import mw from"node:path";function ef(e){return v_("sha256").update(e).digest("hex")}function Qd(e,t){if(T(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||T(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!Wt(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function Zd(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function tf(e){if(e.plans.length===0||new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:s})=>!s))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:s,content:c})=>!s.trim()||Buffer.byteLength(c)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=_("comet.native.supervisor-check-plan.v1",{plans:e.plans,materials:e.materials}),r=await R(e.paths,"reserve Supervisor checks",async()=>{let s=await D(e.paths,e.parent),c=Zd(s,e.child,e.runId);Qd(e.parent,c),e.plans.forEach(f=>br(c.projectRoot,f));let l=c.checkExecution;if(l?.status==="running"){let f=await zi(l.ownerPid,l.ownerIdentity),u=Date.parse(l.expiresAt??"")||Date.parse(l.startedAt)+3e4;if(f){if(!(Date.now()<u))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(l.key!==t)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(c),execute:!1}}let d=l.activeProcess;if(d===void 0||d?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${mw.join(ke(e.paths,e.parent),"logs","checks")} for operation ${l.operationId}; stop any remaining check process in ${c.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${c.runId}, and dispatch a new Verifier for the preserved candidate.`);if(d&&await zi(d.pid,d.identity)){if(!(Date.now()<u))throw new Error(`Native Supervisor check ${d.checkId} is still running as PID ${d.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(c),execute:!1}}l.status="interrupted"}return l?.status==="completed"&&l.key===t&&e.plans.every(({repeatable:f})=>f)?{task:structuredClone(c),execute:!1}:(c.checkExecution={operationId:g_(),key:t,status:"running",ownerPid:process.pid,ownerIdentity:await ei(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((f,u)=>f+u.timeoutMs,0)+3e4).toISOString()},c.checksReason="running",s.stateVersion+=1,await W(e.paths,s),{task:structuredClone(c),execute:!0})}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.receiptRef&&await pc({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=ke(e.paths,e.parent),o=async s=>{await R(e.paths,"register Supervisor check process",async()=>{let c=await D(e.paths,e.parent),l=Zd(c,e.child,e.runId);if(l.checkExecution?.operationId!==n||l.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");l.checkExecution.activeProcess=s,c.stateVersion+=1,await W(e.paths,c)})};try{let s=[];for(let u of e.plans){await o({status:"starting",checkId:u.id});let d=await Ur({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:u,onSpawn:async({pid:p})=>{await o({status:"running",checkId:u.id,pid:p,identity:await ei(p)??void 0})}});await o(null);let h=mw.join(a,d.logRef),v=await w_.readFile(h,"utf8");s.push({...d,logContent:Le(v).slice(0,128*1024)})}Qd(e.parent,i);let c={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:t,checks:s,materials:e.materials.map(({name:u,content:d})=>{let h=Le(d);return{name:u,content:h,hash:ef(h)}})},l=JSON.stringify(c),f=await Ra({paths:e.paths,name:e.parent,hash:ef(l),text:l});return await R(e.paths,"complete Supervisor checks",async()=>{let u=await D(e.paths,e.parent),d=Zd(u,e.child,e.runId);if(d.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Qd(e.parent,d),d.checkExecution.status="completed",d.checkExecution.receiptRef=f,d.checksReason="completed",u.stateVersion+=1,await W(e.paths,u)}),{status:"completed",operationId:n,receiptRef:f}}catch(s){throw await R(e.paths,"interrupt Supervisor checks",async()=>{let c=await D(e.paths,e.parent),l=c?.children.find(({name:f})=>f===e.child)?.task;l?.runId===e.runId&&l.checkExecution?.operationId===n&&(l.checkExecution.status="interrupted",l.checksReason="not-run",c.stateVersion+=1,await W(e.paths,c))}),s}}async function pc(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await Aa(e.paths,e.parent,t[1])),i=e.task;if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!Array.isArray(r.materials)||r.materials.some(({content:n,hash:a})=>ef(n)!==a))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var rf=C(()=>{"use strict";Qn();Vr();_d();ve();Ss();Ar();xe();K();Nr();ai()});import $t from"node:path";import{randomUUID as ww}from"node:crypto";import{promises as yw}from"node:fs";function Nw(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`}async function bw(e){let t=$t.join(".worktrees",`${e.parent}-integration`);return Td({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Nw(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function N_(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 Td({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:$t.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function b_(e,t){return $t.join(ke(e,t),"supervisor")}function Yi(e,t){return $t.join(b_(e,t),"state.json")}function kw(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!==nf)throw new Error(`Native Supervisor state schema must be ${nf}`);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[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(jt(t.integration.targetCommit,"Native Supervisor target commit"),jt(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");jt(n.candidateCommit,"Native Supervisor integration candidate commit"),jt(n.integrationCommit,"Native Supervisor integration check commit")}if(!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 n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&jt(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(jt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function D(e,t,r={}){try{let i=await yw.readFile(Yi(e,t),"utf8"),n=JSON.parse(i);if(kw(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(ja(),Aw)),{readNativePortableState:l}=await Promise.resolve().then(()=>(qt(),Vu)),f=await l($t.join(o.changesDir,t,"comet-state.yaml")),u=await s({changeDir:$t.join(o.changesDir,t),acceptanceIds:f.acceptance.map(({id:d})=>d),validation:c(f)});if(!u)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let d of n.children)u.contract.children.some(({name:h})=>h===d.name)&&(d.acceptanceScope=hc(u.contract,d.name),d.contractHash=_("comet.native.supervisor-contract.v1",u.contract),d.task&&(d.task.acceptance=structuredClone(d.acceptanceScope),d.task.contractHash=d.contractHash,d.task.verificationBoundary="child-scope-parent-reverifies-all",d.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(qt(),Vu)),s=await o($t.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function W(e,t){kw(t),await yw.mkdir(e.changesRuntimeDir,{recursive:!0}),await pe(Yi(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function jt(e,t){if(!y_.test(e))throw new Error(`${t} must be a Git commit`)}function mt(e){return structuredClone(e)}function Ot(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function k_(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function S_(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function af(e){jt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:hc(e.contract,i.name),contractHash:_("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:nf,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 hc(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function vc(e){let t=Nw(e.parent),r=xi(e.paths.projectRoot,t);if(!r)return null;let i=xi(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Lr(e.paths.projectRoot).map(o=>$t.resolve(o)).find(o=>X(o).currentBranch===t);if(!n)return null;let a=af({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return Ot(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Sw(e){let t=mt(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=hc(e.contract,n.name),s=_("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.status=n.candidateCommit?"needs-reverify":"ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."),n.acceptanceScope=o,n.contractHash=s}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:hc(e.contract,n.name),contractHash:_("comet.native.supervisor-contract.v1",e.contract)});return t.stateVersion+=1,t}function of(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=mt(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);k_(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,Ot(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function E_(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function Ew(e,t){let r=E_(e,t),i=mt(e);return Ot(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function x_(e,t,r){let i=X(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!Wt(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=T(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return T(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return T(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(T(e,["merge","--ff-only",r]),T(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function mc(e){if(!Wt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=T(e.integration.worktree,["rev-parse","--show-toplevel"]);if($t.resolve(t)!==$t.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=T(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return T(e.integration.worktree,["rev-parse","HEAD"])}function C_(e,t,r){let i=X(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!Wt(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(T(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function sf(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=mt(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,Ot(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function gc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=mt(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,Ot(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function xw(e){return R(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await D(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Te(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let u;try{u=await N_({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?C_(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):x_(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(h){let v=mt(o),p=v.children.find(({name:m})=>m===l.name);p&&(p.blocker=h.message,Ot(v,{kind:"task-blocked",child:l.name,runId:null,summary:p.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let d=of(o,{role:f?"verifier":"builder",child:l.name,projectRoot:u.projectRoot,runId:ww()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await W(e.paths,o),{state:o,tasks:s}})}function Cw(e,t){jt(t.candidateCommit,"Native Supervisor candidate commit");let r=mt(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,Ot(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Pw(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=mt(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return Qu({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),Ot(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function gw(e,t){jt(t.integrationCommit,"Native Supervisor integration commit");let r=mt(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,Ot(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function Rw(e){let t=await R(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let u=await D(e.paths,e.state.parent)??e.state,d=u.integration.checkExecution;if(d?.status==="running"){if(await zi(d.ownerPid,d.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(d.activeProcess===void 0||d.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(d.activeProcess&&await zi(d.activeProcess.pid,d.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(u.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let h=u.children.find(({name:w})=>w===e.name);if(!h)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=S_(u).find(({status:w})=>w!=="integrated"&&w!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(h.status!=="verified"||!h.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:N})=>!N))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:N})=>N)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(e.checkPlans.forEach(N=>br(u.integration.worktree,N)),!h.verification?.receiptRef||!h.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:w}=await Promise.resolve().then(()=>(rf(),vw)),y=await w({paths:e.paths,parent:u.parent,task:h.verification.execution,receiptRef:h.verification.receiptRef});if(y.candidateCommit!==h.verifiedCommit||y.checks.some(({status:N})=>N!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let p=mc(u);if(p!==u.integration.headCommit){let w=(()=>{try{return T(u.integration.worktree,["merge-base","--is-ancestor",u.integration.headCommit,p]),!0}catch{return!1}})(),y=(()=>{try{return T(u.integration.worktree,["merge-base","--is-ancestor",h.verifiedCommit,p]),!0}catch{return!1}})();if(!w||!y)throw new Error(`Native Supervisor integration head drifted: expected ${u.integration.headCommit}, got ${p}`)}try{T(u.integration.worktree,["cat-file","-e",`${h.verifiedCommit}^{commit}`])}catch(w){throw new Error(`Native Supervisor verified commit is unavailable: ${h.verifiedCommit}`,{cause:w})}if(p===u.integration.headCommit){try{T(u.integration.worktree,["merge","--no-ff","--no-edit",h.verifiedCommit])}catch(w){throw new Error(`Native Supervisor integration conflict preserved in ${u.integration.worktree}`,{cause:w})}p=T(u.integration.worktree,["rev-parse","HEAD"])}let m=p;if(e.checkPlans){let w=ww(),y=_("comet.native.supervisor-integration-plan.v1",{child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:m,plans:e.checkPlans});return u.integration.checkExecution={operationId:w,key:y,child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:m,status:"running",ownerPid:process.pid,ownerIdentity:await ei(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null},u.stateVersion+=1,await W(e.paths,u),{pending:{state:u,candidateCommit:h.verifiedCommit,integrationCommit:m,operationId:w,key:y}}}let g=gw(u,{name:e.name,integrationCommit:m,checks:e.checks});return await W(e.paths,g),{completed:g}});if(t.completed)return t.completed;let{state:r,candidateCommit:i,integrationCommit:n,operationId:a,key:o}=t.pending,{writeNativeVerificationReportSnapshot:s}=await Promise.resolve().then(()=>(Ar(),hw)),{createHash:c}=await import("node:crypto"),l=async f=>R(e.paths,"record Supervisor integration check process",async()=>{let u=await D(e.paths,r.parent),d=u?.integration.checkExecution;if(!u||d?.operationId!==a||d.key!==o||d.status!=="running")throw new Error("Native Supervisor integration check operation is stale");d.activeProcess=f,u.stateVersion+=1,await W(e.paths,u)});try{let f=[];for(let p of e.checkPlans)await l({status:"starting",checkId:p.id}),f.push(await Ur({projectRoot:r.integration.worktree,runtimeDir:ke(e.paths,r.parent),operationId:a,plan:p,onSpawn:async({pid:m})=>l({status:"running",checkId:p.id,pid:m,identity:await ei(m)??void 0})})),await l(null);let u=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:r.parent,child:e.name,candidateCommit:i,integrationCommit:n,operationId:a,planHash:o,results:f}),d=await s({paths:e.paths,name:r.parent,hash:c("sha256").update(u).digest("hex"),text:u}),h=f.map(p=>({name:p.name,status:p.status==="interrupted"?"incomplete":p.status,reason:p.status==="passed"?null:p.timedOut?"timed out":`exit ${p.exitCode??p.signal??"interrupted"}`,receiptRef:d})),v=h.filter(({status:p})=>p!=="passed");return await R(e.paths,"complete Supervisor integration checks",async()=>{let p=await D(e.paths,r.parent),m=p?.children.find(({name:y})=>y===e.name),g=p?.integration.checkExecution;if(!p||!m||g?.operationId!==a||g.key!==o||g.status!=="running"||g.child!==e.name||g.candidateCommit!==i||g.integrationCommit!==n||m.verifiedCommit!==i||mc(p)!==n)throw new Error("Native Supervisor integration changed during checks");if(g.receiptRef=d,g.checks=h,v.length>0){let y=`Native Supervisor integration checks did not pass (${v.map(({name:N,reason:k})=>`${N}: ${k}`).join("; ")}); receipt ${d}`;throw g.status="interrupted",g.error=y,m.blocker=y,p.stateVersion+=1,await W(e.paths,p),new Error(y)}g.status="completed";let w=gw(p,{name:e.name,integrationCommit:n,checks:h});return await W(e.paths,w),w})}catch(f){throw await R(e.paths,"interrupt Supervisor integration checks",async()=>{let u=await D(e.paths,r.parent),d=u?.integration.checkExecution;u&&d?.operationId===a&&d.key===o&&d.status==="running"&&(d.status="interrupted",d.error=f.message,u.stateVersion+=1,await W(e.paths,u))}),f}}function P_(e,t){if(jt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=mt(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ia(e){let t=mc(e);if(t===e.integration.headCommit)return e;try{T(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=mt(e);return r.integration.headCommit=t,Ot(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ta(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=mc(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return P_(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function cf(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var nf,y_,ai=C(()=>{"use strict";Qn();Q();ve();Ss();ia();xe();K();ut();it();Pg();Vr();_d();jd();nf="comet.native.supervisor.v2",y_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var Aw={};Ga(Aw,{NATIVE_CHILDREN_FILE:()=>lf,NATIVE_CHILDREN_SCHEMA:()=>oi,NATIVE_CHILDREN_SCHEMA_V2:()=>pf,NATIVE_CHILDREN_V2_SCHEMA:()=>si,findNativeV1SupervisorParents:()=>Vw,hasNativeSupervisorShapeIntent:()=>Bw,hashNativeParentContract:()=>Xi,inspectNativeChildren:()=>Qe,nativeChildrenAcceptanceValidation:()=>ci,nativeChildrenIndexDrift:()=>Hw,parseNativeChildrenContract:()=>Dw,readNativeChildrenContract:()=>Ht,readNativeSupervisorShapeIntent:()=>$a});import{promises as df}from"node:fs";import $e from"node:path";function yc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function wc(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Iw(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,i)=>r.localeCompare(i,"en"))}function uf(e,t){let r=$e.normalize($e.resolve(e)),i=$e.normalize($e.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function j_(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Tw(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Hw(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===pf&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let f=s.get(l),u=e.acceptance_index[l];f&&u&&(u.source!==f.source||u.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!jw(e.children,l)),$w(i)?i:null}if(e.schema===oi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!jw(e.children,a)),$w(i)?i:null}return null}function jw(e,t){return e.some(r=>r.covers.includes(t))}function $w(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function ci(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function $_(e){let t=yc(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=yc(n,`Native children acceptance_index.${i}`);if(wc(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function O_(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let f=c.get(l);if(!f)continue;let u=e[l];if(u.source!==f.source||u.text!==f.text){let d=["source","text"].filter(h=>u[h]!==f[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function Dw(e,t,r={}){let i=(0,ff.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=yc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==oi&&a!==si)throw wc(n,_w,"Native children contract"),new Error(`Native children schema must be ${oi} or ${si}`);let o=a===oi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(wc(n,o==="indexed-v2"?A_:_w,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,h)=>{let v=yc(d,`Native child ${h}`);if(wc(v,o==="indexed-v2"?T_:o==="summary-v2"?I_:__,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!R_.test(v.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:p?v.summary:null,depends_on:Iw(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Iw(v.covers,`Native child ${v.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 f=new Set(l);for(let d of c){let h=d.depends_on.filter(v=>!f.has(v));if(h.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${h.join(", ")}`)}j_(c);let u=r.policy==="advisory";if(a===pf){if(o==="indexed-v2"){let d=$_(n.acceptance_index);u||O_(d,t,r);let h=Object.keys(d);return u||Tw(c,h,h),{schema:si,acceptance_index:d,children:c}}return{schema:si,children:c}}return t&&!u&&Tw(c,t),{schema:oi,children:c}}async function Ht(e){let t=$e.join(e.changeDir,lf);try{await df.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ie({root:e.changeDir,ref:lf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Dw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Hw(a,e.acceptanceIds,e.validation??{}):null}}function H_(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function Bw(e){let t=H_(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function $a(e){try{let t=await ie({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return Bw(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xi(e){return _("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function Lw(e){let t=Lr(e.projectRoot);t.some(i=>uf(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>$e.resolve(n)))]){let n=await Te(i);n&&r.push({projectRoot:i,paths:await yr(i,n.native.artifact_root),parent:uf(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Vw(e){let t=await Lw(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await df.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=$e.join(a.paths.changesDir,s.name),l;try{l=await Be($e.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let f=await Ht({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:u})=>u)}:{}});!f||f.contract.schema!==oi||f.contract.children.some(({name:u})=>u===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:h})=>h.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:h,state:v})=>X(h.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let h=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(h)i.push(`Native Supervisor parent ${a} targets ${h.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:f}=c,u=l.paths,d=await Qe({paths:u,state:f});if(!d)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!d.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(d.allDone)r.push({paths:u,state:f,inspection:d});else{let h=d.children.filter(({status:v})=>v!=="done").map(({name:v,status:p,message:m})=>`${v}=${p}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${h||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function D_(e,t){let r=$e.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Be(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function B_(e,t){let r;try{r=await df.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=$e.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Be(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function L_(e,t,r){let i=$e.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${$e.sep}`))return null;let n=i.split($e.sep).join("/");try{let a=(0,ff.parseDocument)(T(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:I(a.toJS({mapAsMap:!1}))}catch{return null}}function V_(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 Ow(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Qe(e){let t=$e.join(e.paths.changesDir,e.state.name),r=await $a(t),i=null,n;try{n=await Ht({changeDir:t,validation:ci(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(g){let w=cf(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Xi({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===si){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let k=await vc({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});k&&(g=k,await W(e.paths,k))}}if(g){let N=cf(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(k=>({...k,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let w=new Map(n.contract.children.map(N=>[N.name,N])),y=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(k=>n.contract.children.filter(({name:b})=>b!==N.name).every(({name:b})=>b!==k))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of y){if(N.status!=="ready")continue;w.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:y,readyChildren:y.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await Lw(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),f=new Map,u=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let y of await B_(g,l)){let N={...y,source:g,committedState:L_(g,y.file,w)};f.set(y.state.name,[...f.get(y.state.name)??[],N])}for(let y of l){let N=await D_(g,y);N&&u.set(y,[...u.get(y)??[],{source:g,state:N}])}}let d=new Map;for(let g of n.contract.children){let w=(f.get(g.name)??[]).find(({source:k,committedState:b})=>k.parent&&b?.name===g.name&&Ow(b,o));if(w){d.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=f.get(g.name)?.[0];if(y){d.set(g.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=u.get(g.name)??[];N.length>1?d.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&d.set(g.name,V_(N[0].state,N[0].source,o))}let h=new Map(n.contract.children.map(g=>[g.name,g])),v=new Map,p=g=>{let w=v.get(g);if(w)return w;let y=h.get(g),k=y.depends_on.map(p).every(({status:M})=>M==="done"),b=d.get(g),P=b?.kind==="active"&&k?y.depends_on.filter(M=>!(f.get(M)??[]).some(({source:$,committedState:de})=>uf($.projectRoot,b.projectRoot)&&de?.name===M&&Ow(de,o))):[],S,E=b?.message??null;b?.kind==="done"?(S=k?"done":"blocked",k||(E=`Native child ${g} was merged before its dependencies`)):b?.kind==="active"?(S=k&&P.length===0?"active":"blocked",k?P.length>0&&(E=`Native child ${g} does not include merged dependencies: ${P.join(", ")}`):E=`Native child ${g} started before its dependencies merged`):b?.kind==="blocked"?S="blocked":(S=s&&k?"ready":"pending",s||(E="Parent Shape confirmation is required"));let A={name:g,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:S,phase:b?.phase??null,projectRoot:b?.projectRoot??null,message:E};return v.set(g,A),A},m=n.contract.children.map(({name:g})=>p(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:m.every(({status:g})=>g==="done")}}var ff,lf,oi,si,pf,R_,_w,A_,__,I_,T_,ja=C(()=>{"use strict";ff=nn(Si(),1);it();Vr();ot();ve();ut();K();qt();ai();lf="children.yaml",oi="comet.native.children.v1",si="comet.native.children.v2",pf=si,R_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_w=new Set(["schema","children"]),A_=new Set(["schema","acceptance_index","children"]),__=new Set(["name","depends_on","covers"]),I_=new Set(["name","summary","depends_on"]),T_=new Set(["name","depends_on","covers"])});ja();Hi();function Ze(e,t,r){return e.language==="zh-CN"?r:t}function M_(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return 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{required:!0,message:Ze(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Ze(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ze(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(Ze(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 r(Ze(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return 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 n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"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:o,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."}}return e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{required:!0,message:Ze(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.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:Ze(e,"Accept the result","接受结果"),agentInstruction:Ze(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。不要替用户接受结果。")}:r(Ze(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 F_(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 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 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 a complete dry-run first, then return one confirmed command; 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 containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function q_(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:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:Ze(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Ze(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Fw(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function li(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function W_(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Mw(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function z_(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function J_(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function _r(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Fw({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[li("summary","--summary"),W_(e.name,e.flag)]}}function hf(e){return[_r({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),_r({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Z(e,t,r={}){let i=z_(t)&&e.coordination_mode===void 0,n=M_(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...hf({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),_r({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:[_r({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...hf({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[li("summary","--summary")],commandAlternatives:hf({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Fw({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:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:J_({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Mw("coordination-mode","--coordination-mode",hs)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"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:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:f})=>f==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),l=t.children.some(({status:f})=>f==="ready"||f==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[li("summary","--summary")],runnerAction:o("none")}}return{...a,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:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Ze(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",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":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,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:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(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;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Mw("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...q_(e)],userCommunication:F_(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[_r({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}it();Q();ot();ye();xe();bd();Ys();zs();import{randomUUID as yI}from"node:crypto";import{promises as Va}from"node:fs";import NI from"node:path";it();Q();import{createHash as SV,randomUUID as Sf}from"node:crypto";import{promises as ui}from"node:fs";import ue from"node:path";Xr();ye();ot();Et();K();var U_=["outcome","scope","nonGoals","acceptanceExamples"],iV=[...U_,"constraints","decisions","openQuestions","verificationExpectations"];function qw(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}ot();ve();ja();ai();ye();Ss();qt();wa();Kr();ia();import{randomUUID as K_}from"node:crypto";var Oa=3,mf=2;function Pe(e){return e.state_version+1}function Y_(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function vf(e){return e.map(t=>({...t,result:"pending",reason:null}))}function gf(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function X_(e){return(e??[]).map(t=>({name:F(t.name),result:t.result,note:t.note?F(t.note):null}))}function Yt(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:F(e.summary),completed_at:e.completedAt}}function Ww(e){let t=I(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:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return I({...t,phase:"build",status:"active",state_version:Pe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function zw(e){let t=I(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:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return I({...t,status:"await-user",state_version:Pe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Jw(e){let t=I(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(!pv(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=Y_(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):vf(t.acceptance),o=(r.now??new Date).toISOString();return I({...t,phase:"verify",state_version:Pe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??K_(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:F(r.summary),addressed_acceptance_ids:i,checks:X_(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>F(s)),known_limits_truncated:!1,review:{status:"passed",summary:F(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Gw(e){let t=I(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return I({...t,state_version:Pe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Q_(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function Z_(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.identityProvider===ne?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:F(e.response.result.summary),risks:e.response.result.risks.map(t=>F(t)),risks_truncated:!1,completed_at:e.completedAt}}function Uw(e){let t=I(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=gf(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=hv({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(m=>[m.id,m])),o=t.acceptance.map(m=>{let g=a.get(m.id);return g?{...m,result:g.result,reason:F(g.reason)}:m}),s=o.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),c=Z_({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let w=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:I({...w,state_version:Pe(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:vf(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let m=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===ne;return{response:i,state:I({...m,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:Pe(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:F("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:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:I({...m,status:"await-user",state_version:Pe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:F(i.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,f=Q_(t,s),u=l>=e.maxVerifyFailures,d=f>=3,h=u||d,v=d?"stalled":u?"budget":void 0,p=we({...t,acceptance:o,verification:c},Yt({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:I({...p,phase:h?"verify":"build",status:h?"await-user":"active",state_version:Pe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:h?[{owner:"user",reason:F(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:F("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:h?"await-user":"repairing",iteration:h?t.loop.iteration:t.loop.iteration+1,attempt:h?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:h?"await-user":"repair-failed-acceptance"}})}}function Kw(e){let t=I(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==ne||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 I({...t,phase:"archive",status:"active",state_version:Pe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Yw(e){let t=I(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==ne||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=gf(t),n=we(t,Yt({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return I({...n,status:"await-user",state_version:Pe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:F(e.summary),risks:[F("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:F("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Xw(e){let t=I(e.state);if(t.phase!=="verify"||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")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=F(e.summary),n=we(t,Yt({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return I({...n,phase:"archive",status:"active",state_version:Pe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:F(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Qw(e,t){let r=I(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:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=we(r,Yt({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return I({...i,status:"active",state_version:Pe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Zw(e){let t=I(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(),i=t.loop.execution_failure_count+1,n=i>=Oa,a=we(t,Yt({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return I({...a,status:n?"blocked":"active",state_version:Pe(t),blockers:n?[{owner:"runtime",reason:F(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function ey(e){let t=I(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=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:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=gf(t),a=t.acceptance.some(({result:o})=>o==="passed");return I({...t,status:"active",state_version:Pe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Ha(e){let t=I(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.now??new Date).toISOString(),i=we(t,Yt({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?vf(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return I({...i,phase:"build",status:"active",state_version:Pe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}Q();Hi();import{promises as ry}from"node:fs";import Da from"node:path";function Nc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bc(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Dt(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function ty(e,t){return e===null?null:Dt(e,t)}function Sc(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 eI(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function tI(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function kc(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function wf(e,t){if(e===null)return null;let r=Dt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function yf(e,t){let r=Dt(e,t);if(!Da.isAbsolute(r))throw new Error(`${t} must be absolute`);return Da.resolve(r)}function rI(e,t){let r=`Native local checks[${t}]`,i=Nc(e,r);if(bc(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>Dt(l,`${r}.argv[${f}]`,!0)),a=kc(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=wf(i.startedAt,`${r}.startedAt`),s=wf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Sc(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Dt(i.id,`${r}.id`),name:Dt(i.name,`${r}.name`),operationId:Dt(i.operationId,`${r}.operationId`),status:a,repeatable:tI(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Sc(i.executionCount,`${r}.executionCount`),argv:n,cwd:yf(i.cwd,`${r}.cwd`),exitCode:eI(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Dt(i.log,`${r}.log`)}}function Nf(e){let t="Native local execution state",r=Nc(e,t);if(bc(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Kn)throw new Error(`Native local execution schema must be ${Kn}`);let i=Nc(r.workspace,"Native local workspace");bc(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Nc(r.execution,"Native local execution");bc(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=wf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Dt(o.operationId,"Native local execution.operationId"),stage:kc(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:kc(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ty(o.executionId,"Native local execution.executionId"),status:kc(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Sc(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(rI);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Kn,change:Dt(r.change,"Native local change"),basedOnStateVersion:Sc(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:yf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:yf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ty(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function le(e){return Nf({schema:Kn,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Da.resolve(e.projectRoot),worktreeRoot:Da.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Bt(e){let t;try{t=await ry.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Nf(r)}async function G(e,t,r={}){let i=Nf(t);await ry.mkdir(Da.dirname(e),{recursive:!0}),await pe(e,i,r)}async function bf(e){let t=null,r=null;try{t=await Bt(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=le(e);return await G(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}xe();zs();qt();Ys();wa();Kr();ia();Q();Xr();Kr();import{promises as iI}from"node:fs";function Ir(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
191
191
  `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Xt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function nI(e){return e.archived?je(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?je(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?je(e.language,"Verification passed; ready to archive","验收通过,可归档"):je(e.language,"Verification passed","验收通过")}function aI(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?je(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?nI(e):e.verification_result==="blocked"?je(t,"Blocked","已阻塞"):e.verification_result==="fail"?je(t,"Failed","未通过"):je(t,"Pending","待处理")}function oI(e){if(e.verification?.assurance==="semantic-verification-unavailable")return je(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return je(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return je(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===ne?ne:"host-attested"),r=t===ne&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","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":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function sI(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>id(r,u),n=(u,d)=>je(r,u,d),a=e.acceptance.map(u=>`| ${Xt(u.id)} | ${Xt(u.result)} | ${Xt(u.source)} | ${Xt(u.text)} | ${Xt(Ir(u.reason))} |`).join(`
192
192
  `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(u=>{let d=u.argv_display.map(Ir).join(" ");return`| ${Xt(Ir(u.name))} | ${Xt(d||"—")} | ${Xt(u.cwd_ref)} | ${u.status} | ${u.exit_code??"—"} | ${u.duration_ms} ms |`})].join(`
193
193
  `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(u=>`- **${u.owner}**: ${Ir(u.reason)}${u.acceptance_ids.length>0?` (acceptance: ${u.acceptance_ids.join(", ")})`:""} — next: \`${u.resolution_action}\``).join(`
@@ -246,12 +246,12 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
246
246
  `:""}## ${i("conclusion")}
247
247
 
248
248
  ${Ir(e.verification.summary)}
249
- `}function cI(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 iy(e){let t;try{t=await iI.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=cI(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Qi(e){await Je(e.file,sI(e.state,e.supervisor))}K();Xr();Ar();lt();var ay=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lI="comet-state.yaml",uI="state.json",KV=Is("en");function Tr(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function he(e,t){if(!ay.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ue.join(e.changesDir,t);if(!ge(e.changesDir,r))throw new Error("Native change path escaped");return r}function mt(e,t){return ue.join(he(e,t),lI)}function q(e,t){return ue.join(ke(e,t),uI)}async function Ba(e,t){try{let r=await ui.readFile(mt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Fe(e){return X(e).currentBranch}async function H(e,t){return Be(mt(e,t))}async function Re(e){let t=await Li({file:mt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ue.join(he(e.paths,t.name),"verification.md");await U(e.paths.nativeRoot,r),await ui.rm(r,{force:!0})}return t}async function Ef(e){let t=he(e.paths,e.state.name),r=ue.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ui.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!ay.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=ue.join(t,...s.split("/")),l=await ui.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=ue.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await ui.lstat(f);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:u,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function xf(e){let t=he(e.paths,e.state.name),r=await ie({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(qw(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await ie({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:_("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Ws({briefMarkdown:r.text,specs:i}),formalHash:_("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:_("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function Cf(e){return _("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function oy(e){return R(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await Ef({paths:e.paths,state:t}),i=await xf({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Ot({changeDir:he(e.paths,t.name),acceptanceIds:n.map(({id:u})=>u),validation:ci({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await $a(he(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let s=o?e.coordinationMode??t.coordination_mode:void 0;if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!o&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let c={...t,spec_changes:r,shape_confirmation_hash:Cf({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s})};delete c.children_contract_hash,delete c.coordination_mode,o&&(c.coordination_mode=s);let l=zw({state:c,acceptance:n.map(u=>({...u}))});a&&(l.children_contract_hash=Xi({acceptance:l.acceptance,children:a.contract}));let f=await Re({paths:e.paths,previous:t,next:l});return await G(q(e.paths,t.name),le({portableState:f,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function sy(e){return R(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await Qt({paths:e.paths,state:t});let r=await Ef({paths:e.paths,state:t}),i=await xf({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Ot({changeDir:he(e.paths,t.name),acceptanceIds:n.map(({id:p})=>p),validation:ci({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await $a(he(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,s=t.coordination_mode;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let c=Cf({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s});if(t.shape_confirmation_hash===void 0||c!==t.shape_confirmation_hash){let p=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Af({paths:e.paths,state:t,reason:p}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}let l=Ww({state:{...t,spec_changes:r},acceptance:n.map(p=>({...p}))});if(delete l.children_contract_hash,delete l.coordination_mode,a){l.children_contract_hash=Xi({acceptance:l.acceptance,children:a.contract}),o&&(l.coordination_mode=s);let p=[...t.history].reverse().find(({outcome:m})=>m==="pass"||m==="fail");if(p?.outcome==="fail"&&p.unresolved_ids.length>0){let m=await Qe({paths:e.paths,state:l}),g=new Map((m?.children??[]).map(({name:N,status:k})=>[N,k])),w=new Set(a.contract.children.filter(({name:N})=>{let k=g.get(N);return k!=="done"&&k!=="integrated"&&k!=="archived"}).flatMap(({covers:N})=>N)),y=p.unresolved_ids.filter(N=>!w.has(N));if(y.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${y.join(", ")}`)}}let f=null,u=a?.contract.schema==="comet.native.children.v2"?await D(e.paths,t.name):null,d=null,h=null;if(a?.contract.schema==="comet.native.children.v2"){if(d=t.workspace.change_branch??t.workspace.target_branch,!d)throw new Error("Native Supervisor v2 requires a target branch");if(h=xi(e.paths.projectRoot,d),!h)throw new Error(`Native Supervisor target branch has no commit: ${d}`);u||(u=await vc({paths:e.paths,parent:t.name,targetBranch:d,contract:a.contract})),u||(f=await bw({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:d,sourceConfig:await Te(e.paths.projectRoot)}))}let v=await Re({paths:e.paths,previous:t,next:l});if(await G(q(e.paths,t.name),le({portableState:v,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a?.contract.schema==="comet.native.children.v2"&&d&&h){let p=u?Sw({state:u,contract:a.contract}):f?af({parent:v.name,targetBranch:d,targetCommit:h,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null;if(!p)throw new Error("Native Supervisor integration state is unavailable");await W(e.paths,p)}return v})}async function Pc(e){let t=await Ef(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,f)=>{let u=e.state.spec_changes[f];return u!==void 0&&l.capability===u.capability&&l.source===u.source&&(l.operation===u.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await xf({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:f})=>({source:l,text:f}));if(!fg(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Ot({changeDir:he(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:ci({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Cf({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Xi({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Qt(e){let t=await Pc(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Af({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function cy(e){return R(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Qt({paths:e.paths,state:t}),await Ot({changeDir:he(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:ci(t)})||t.children_contract_hash){let a=await Qe({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Jw({state:t,input:e.input}),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Rc(e){let t=await H(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 i=await Qe({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function Pf(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:ks(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function ly(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Pf(t,r,i),executionCount:e.executionCount}}function uy(e,t){let r=ue.relative(ue.resolve(e),ue.resolve(t));if(ue.isAbsolute(r)||r===".."||r.startsWith(`..${ue.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(ue.sep).join("/");return ks(e,i),i}function kf(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return ea({id:e.id,name:e.id,executable:r,argv:i,cwdRef:uy(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function dI(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Zi(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:F(i),argv_display:Uu(r.argv.slice(1)).map(n=>F(n)),argv_truncated:!1,cwd_ref:uy(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:dI(r)}})}function fI(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function La(e){if(e.local===null||e.local.change!==e.state.name)return le({portableState:e.state,projectRoot:e.projectRoot,branch:Fe(e.projectRoot)});let t=e.local.execution?.operationId??Sf();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function en(e){try{let t=await Dt(q(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function dy(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function pI(e){let{state:t,local:r,envelope:i}=e;if(!Es(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function hI(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Cc(e){let t=await en({paths:e.paths,state:e.state}),r=Zw({state:e.state,summary:e.summary}),i=await Re({paths:e.paths,previous:e.state,next:r});return await G(q(e.paths,e.state.name),La({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function ny(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>kf(i,r)===ea(t[n]))}async function mI(e){return R(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Qt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=q(e.paths,t.name),i=(await bf({file:r,portableState:t,projectRoot:e.projectRoot,branch:Fe(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&ny(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Zi({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=Ha({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await Re({paths:e.paths,previous:t,next:c});throw await G(q(e.paths,t.name),le({portableState:l,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&ny(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Sf(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?ly(s,o,n,e.projectRoot):s?{...s,operationId:n}:Pf(o,n,e.projectRoot)})};return await G(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function Ec(e){return R(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=q(e.paths,t.name),i=await Dt(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await G(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function fy(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){br(t,c);let l=ea(c);i.has(l)||(i.add(l),r.push(c))}let n=await mI({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=ke(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Ec({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:l}:d)})});let f=await Ur({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await Ec({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:d)})})}await Ec({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Ec({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await Dt(q(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Zi({local:s,projectRoot:t,supplied:[]})}}async function vI(e){let t=q(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=mf)throw new Error(`Native Verifier request-checks exceeded ${mf} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let h of r.checks){let v=kf(h,e.projectRoot);n.set(v,h),h.status!=="interrupted"&&i.set(v,h),a.set(h.id,v)}let o=new Map,s=new Map;for(let h of e.response.checks){let v=fI(h);br(e.projectRoot,v);let p=ea(v),m=s.get(v.id);if(m!==void 0&&m!==p)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let g=a.get(v.id);if(g!==void 0&&g!==p)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,p);let w=n.get(p);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(p)||o.set(p,v)}let c=[...o.entries()],l=c.filter(([h])=>!i.has(h));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,u=new Map(c.map(([,h])=>[h.id,h.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(h=>{let v=kf(h,e.projectRoot),p=o.get(v);return p&&h.status==="interrupted"?ly(h,p,r.execution.operationId,e.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>Pf(h,r.execution.operationId,e.projectRoot))]};return await G(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,h])=>h),requestedNames:u,reusedCheckIds:c.filter(([h])=>i.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function xc(e){return R(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=q(e.paths,t.name),i=await Dt(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await G(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function gI(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await xc({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await Ur({projectRoot:e.projectRoot,runtimeDir:ke(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await xc({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await xc({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await xc({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Zi({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function py(e){return R(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Qt({paths:e.paths,state:t});let i=(await bf({file:q(e.paths,t.name),portableState:t,projectRoot:r,branch:Fe(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Zi({local:i,projectRoot:r,supplied:e.checks});let n=Gw(t),a=await Re({paths:e.paths,previous:t,next:n}),o=q(e.paths,t.name),s=Sf();return await G(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function hy(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await R(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await H(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Qt({paths:e.paths,state:r});let n=await en({paths:e.paths,state:r}),a=pI({state:r,local:n,envelope:e.envelope}),o;try{o=Xu(a.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,h=await Cc({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${h.loop.execution_failure_count}/${Oa} was recorded`,{cause:u})}let s=hI(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Zi({local:n,projectRoot:i,supplied:e.checks}));let u=Uw({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await vI({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:u.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:u.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,h=await Cc({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${h.loop.execution_failure_count}/${Oa} was recorded`,{cause:u})}let f=await Re({paths:e.paths,previous:r,next:l.state});return await G(q(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?La({local:n,state:f,projectRoot:i}):le({portableState:f,projectRoot:i,branch:Fe(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await Qi({file:ue.join(he(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await gI({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await R(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Cc({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Oa} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function my(e){return R(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=await en({paths:e.paths,state:t});if(dy({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Cc({paths:e.paths,state:t,summary:e.summary})})}async function vy(e){return R(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Qt({paths:e.paths,state:t});let r=await en({paths:e.paths,state:t}),i=dy({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Zi({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Yw({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Re({paths:e.paths,previous:t,next:a});return await G(q(e.paths,t.name),La({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Qi({file:ue.join(he(e.paths,t.name),"verification.md"),state:o}),o})}async function gy(e){return R(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Qt({paths:e.paths,state:t});let r=await D(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ia(r).stateVersion!==r.stateVersion)return by({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await W(e.paths,Ta(r,t))}let i=Kw(t),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Qi({file:ue.join(he(e.paths,t.name),"verification.md"),state:n}),n})}async function wI(e){let t=await H(e.paths,e.name),r=await Ks(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await D(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await ui.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Ia(n);if(i||a.stateVersion!==n.stateVersion){let o=await by({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await ui.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await W(e.paths,Ta(n,t)),{state:t,action:"recorded-final-verification"}}async function Rf(e){return R(e.paths,`recover Supervisor final verification ${e.name}`,()=>wI(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function wy(e){return R(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Qt({paths:e.paths,state:t});let r=Xw({state:t,summary:e.summary}),i=await Re({paths:e.paths,previous:t,next:r});return await G(q(e.paths,t.name),le({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Qi({file:ue.join(he(e.paths,t.name),"verification.md"),state:i}),i})}async function yy(e){return R(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Qt({paths:e.paths,state:t});let r=await en({paths:e.paths,state:t}),i=Qw(t,{reason:e.reason}),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),La({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Ny(e){return R(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await en({paths:e.paths,state:t}),i=ey(t),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),La({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Ac(e){return R(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=Ha({state:t,reason:e.reason}),i=await Re({paths:e.paths,previous:t,next:r});return await G(q(e.paths,t.name),le({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function _c(e){return R(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Af({paths:e.paths,state:t,reason:e.reason})})}async function Af(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...we(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:F(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.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"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function by(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...we(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:F(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ic(e){if(e.state.verification===null)return"not-applicable";let t=ue.join(he(e.paths,e.state.name),"verification.md");return await iy({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Qi({file:t,state:e.state}),"rebuilt")}Ft();K();ua();var ky=["evidence.md","repair.md","archive.md","checkpoint.md"],bI="verification.md";async function kI(e,t){let r=await Ks(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Sy(e,t){await Va.mkdir(e.transactionsDir,{recursive:!0}),await pe(Us(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ey(e,t,r={}){let i=r.removeVerificationReport===!1?ky:[...ky,bI];await Promise.all([Va.rm(ke(e,t),{recursive:!0,force:!0}),Va.rm(Ou(e,t),{recursive:!0,force:!0}),...i.map(n=>Va.rm(NI.join(Pt(e,t),n),{force:!0}))])}async function xy(e,t){await G(q(e,t.name),le({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Cy(e,t){try{let r=await la(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Py(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=X(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function SI(e){let t=Pt(e.paths,e.state.name),r=await ie({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await ie({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ws({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Ry(e,t){let r=await ig(e,t);if(r.status==="runtime-incompatible")throw new Sr(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Ay(e){return R(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await kI(e.paths,e.name),r=await Ba(e.paths,e.name)?await Be(mt(e.paths,e.name)):null;if(!t&&r)return await Ey(e.paths,e.name,{removeVerificationReport:!1}),await xy(e.paths,r),r;let i=null,n=null;for(t||(i=await Ry(e.paths,e.name),n=await Cy(e.paths,e.name),Py(e.paths,n),t={schema:Js,id:yI(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Sy(e.paths,t));;){let a=hg(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Ry(e.paths,e.name),n??=await Cy(e.paths,e.name),Py(e.paths,n),r=pg({state:i,acceptance:await SI({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Xn(mt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ey(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Be(mt(e.paths,e.name)),await xy(e.paths,r)),t={...t,status:a.nextStatus},await Sy(e.paths,t)}return await Va.rm(Us(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Be(mt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}rt();import{promises as Iy}from"node:fs";import Ty from"node:path";xe();ja();ve();ai();import{promises as _f}from"node:fs";import EI from"node:path";var xI=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),CI=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),PI=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),RI=new Set(["status","summary"]);function Tc(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function jc(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function AI(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function di(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function _I(e,t,r,i){let n=Tc(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=jc(n,xI,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Tc(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=jc(o,CI,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Tc(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=jc(c,RI,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[f,u]of n.children.entries()){let d=Tc(u,`Native Supervisor child ${f}`);if(!d)return`Native Supervisor child ${f} must be an object`;let{acceptanceScope:h,contractHash:v,...p}=d,m=jc(p,PI,`Native Supervisor child ${f}`);if(m)return m;let g=r.children[f],w=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(h!==void 0&&JSON.stringify(h)!==JSON.stringify(w)||v!==void 0&&v!==_("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(d.name!==g.name||d.summary!==g.summary||!AI(d.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let y=g.depends_on.length===0?"ready":"pending";if(d.status!==y)return`Native Supervisor child ${g.name} has progressed beyond its initial ${y} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function Ma(e){let t=Yi(e.paths,e.state.name),r;try{let c=await _f.lstat(t);if(!c.isFile()||c.isSymbolicLink())return di(t,"","Native Supervisor overlay is not a regular file");r=await _f.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:di(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return di(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=EI.join(e.paths.changesDir,e.state.name),a;try{a=await Ot({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return di(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await D(e.paths,e.state.name)}catch(c){return di(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return di(t,r,"Native Supervisor overlay disappeared during inspection");let s=_I(i,e.state,a.contract,o);return s?di(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function _y(e){let t=await Ma({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await _f.rm(t.file,{force:!1})}Ft();wa();function If(e,t){let r=X(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function II(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function TI(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:we(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:F(t),completed_at:i});return I({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?II(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function jI(e){try{let t=await Dt(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Tf(e){return R(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Ic({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=If(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await Ma({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await _y({paths:e.paths,state:t,expected:i}),n=!0);let a=q(e.paths,e.name),o=await jI(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await G(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Ic({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=Ha({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Li({file:mt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await Iy.rm(Ty.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=le({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await G(a,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let f=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",u=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=f||u;if(d){let v=TI(t,u?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",u);t=await Li({file:mt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let h=le({portableState:t,projectRoot:e.paths.projectRoot,branch:X(e.paths.projectRoot).currentBranch});return await Iy.mkdir(Ty.dirname(q(e.paths,t.name)),{recursive:!0}),await G(a,h,{containedRoot:e.paths.runtimeDir}),await Ic({paths:e.paths,state:t}),{state:t,local:h,action:d?"reverify":"resume-stable-boundary",reason:s,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import jy from"node:path";function $y(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function qe(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.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:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:$y(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.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(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:$y(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>jy.relative(t.projectRoot,jy.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}Qn();Vr();rt();rf();ia();import{randomUUID as Vy}from"node:crypto";import{promises as Oy}from"node:fs";import qa from"node:path";ai();xe();Kr();function tn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function me(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function L(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Of(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>L(r,`${t}[${i}]`))}function $I(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=tn(t,`Native Builder check ${r}`);if(me(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:L(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function jf(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=tn(t,`Native Runtime check ${r}`);if(me(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:L(i.id,`Native Runtime check ${r} id`),name:L(i.name,`Native Runtime check ${r} name`),executable:L(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:L(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function Hy(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:L(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function OI(e){let t=tn(e,"Native Supervisor evidence");return me(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence"),{summary:L(t.summary,"Native Supervisor evidence summary"),checks:Of(t.checks,"Native Supervisor evidence checks"),acceptance:Cs(t.acceptance),...t.receiptRef===null?{}:{receiptRef:L(t.receiptRef,"Native Supervisor receipt ref")}}}function HI(e){let t=tn(e,"Native Runner input");if(t.kind==="builder-handoff"){me(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=tn(t.review,"Native Builder review");if(me(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:L(t.summary,"Native Builder summary"),addressed_acceptance_ids:Of(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:$I(t.checks),known_limits:Of(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:L(r.summary,"Native Builder review summary"),reviewer_execution_ref:L(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return me(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:jf(t.checks)};if(t.kind==="verifier-response")return me(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return me(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:L(t.summary,"Native Verifier execution error summary"),...Hy(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return me(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:L(t.summary,"Native unavailable Verifier summary"),...Hy(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return me(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),candidateCommit:L(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return me(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),reason:L(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return me(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return me(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),reason:L(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(me(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:OI(t.evidence)}}if(t.kind==="supervisor-checks"){if(me(t,["kind","child","runId","checks","materials"],"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),checks:jf(t.checks),materials:t.materials.map(r=>{let i=tn(r,"Native Supervisor material");return me(i,["name","content"],"Native Supervisor material"),{name:L(i.name,"Native Supervisor material name"),content:L(i.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate")return me(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:L(t.child,"Native Supervisor child"),checks:jf(t.checks)};throw new Error("Native Runner input kind is invalid")}async function My(e,t){let r=qa.resolve(t,e),i=await Oy.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Oy.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return HI(n)}function Dy(e){return`${ne}:${e}:${Vy()}`}function By(e,t,r,i){if(qa.resolve(T(e.projectRoot,["rev-parse","--show-toplevel"]))!==qa.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(T(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!qt(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(T(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{T(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function DI(e,t){let r=X(e.projectRoot),i=qa.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==qa.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=T(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!qt(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{T(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Fa(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==ne)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function BI(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function Ly(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Fa(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=BI(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:ne,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:he(t,r.name),supervisorStateRef:a?Yi(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:u})=>({capability:l,operation:f,ref:u})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function $f(e){Fa(e.state);let t=await Dt(q(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function Fy(e){let t=e.input,r=await H(e.paths,e.name),i=await Ma({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:v})=>v==="integrated"||v==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:v})=>v==="integrated"||v==="archived");if(n&&t.kind==="supervisor-checks"){let v=await tf({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials});return{state:r,supervisorState:await D(e.paths,e.name),supervisorTask:null,checks:[],checkExecution:v,requestChecks:null,verifierDispatch:null,continuation:te(r)}}if(n&&t.kind==="supervisor-builder-result")return R(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:N})=>N===t.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{By(p.task,t.candidateCommit,"builder",`comet/supervisor/${v.parent}/${t.child}`)}catch(N){throw await W(e.paths,gc(v,{child:t.child,runId:t.runId,reason:N.message})),N}let m=p.task.projectRoot,g=Cw(v,t),w=of(g,{role:"verifier",child:t.child,projectRoot:m,runId:Vy()});await W(e.paths,w.state);let y=await H(e.paths,e.name);return{state:y,supervisorTask:w.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(y)}});if(n&&t.kind==="supervisor-builder-failure")return R(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:w})=>w===t.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let m=sf(v,{child:t.child,runId:t.runId,reason:t.reason});await W(e.paths,m);let g=await H(e.paths,e.name);return{state:g,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(g)}});if(n&&t.kind==="supervisor-reconnect")return R(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:w})=>w===t.child)?.task;if(!p||p.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{DI(p,`comet/supervisor/${v.parent}/${t.child}`)}catch(w){throw await W(e.paths,gc(v,{child:t.child,runId:t.runId,reason:w.message})),w}let m=Ew(v,{child:t.child,runId:t.runId});await W(e.paths,m.state);let g=await H(e.paths,e.name);return{state:g,supervisorState:m.state,supervisorTask:m.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(g)}});if(n&&t.kind==="supervisor-cancel")return R(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=sf(v,{child:t.child,runId:t.runId,reason:t.reason});await W(e.paths,p);let m=await H(e.paths,e.name);return{state:m,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(m)}});if(n&&t.kind==="supervisor-verifier-result")return R(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:y})=>y===t.child);if(!p?.task||p.task.role!=="verifier"||!p.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{By(p.task,p.candidateCommit,"verifier",`comet/supervisor/${v.parent}/${t.child}`)}catch(y){throw await W(e.paths,gc(v,{child:t.child,runId:t.runId,reason:y.message})),y}let m=t.evidence.receiptRef||t.verdict==="pass"?await pc({paths:e.paths,parent:e.name,task:p.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!m||m.checks.some(({status:y,exitCode:N})=>y!=="passed"||N!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=Pw(v,{...t,evidence:{...t.evidence,checks:m?.checks.map(({name:y,status:N})=>`${y}: ${N}`)??[],execution:structuredClone(p.task)}});await W(e.paths,g);let w=await H(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(w)}});if(n&&t.kind==="supervisor-integrate"){let v=await Rw({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks}),p=await Rc({paths:e.paths,name:e.name,trigger:"v2-integrate"}),m=p.state;return{state:m,supervisorState:v,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:p.parentAdvance,continuation:te(m)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="verifier-response"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let p=Yu().captureExecutionIdentity({identityProvider:ne,executionRef:Dy("builder")}),m=await cy({paths:e.paths,name:e.name,input:{identity:p,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}}});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(m)}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let v=await H(e.paths,e.name);if(v.builder_handoff!==null&&v.builder_handoff.identity_provider!==ne){let y=await Ac({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:y,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(y)}}Fa(v);let m=(v.loop.next_action==="run-final-full-verification"&&v.verification?.verdict==="pass"&&v.verification.checks.every(({status:y})=>y==="passed")?v.verification.checks:null)??(await fy({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}})).checks,g=Dy("verifier"),w=await py({paths:e.paths,name:e.name,checks:m,verifierExecutionId:g,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:w,checks:m,requestChecks:null,verifierDispatch:Ly({paths:e.paths,state:w,checks:m,verifierExecutionRef:g,supervisor:a?n:null}),continuation:te(w)}}if(t.kind==="verifier-execution-error"){let v=await H(e.paths,e.name);Fa(v),await $f({paths:e.paths,state:v});let p=await my({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:p,checks:[],requestChecks:null,verifierDispatch:null,continuation:te(p)}}if(t.kind==="verifier-unavailable"){let v=await vy({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:v,checks:v.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:te(v)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await H(e.paths,e.name),c=Fa(s),l=await $f({paths:e.paths,state:s}),f=Yu(),u=f.captureExecutionIdentity({identityProvider:ne,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let v=await D(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared before final verification");d=Ia(v)}let h=await hy({paths:e.paths,name:e.name,envelope:f.envelopeVerifierResponse({candidateId:c.candidate_id,identity:u,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&h.response.kind==="final-result"){if(h.state.verification_result==="pass"&&(h.checks.length===0||h.checks.some(({status:m})=>m!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let v=d??await D(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared during verification");let p=Ta(v,h.state);return await W(e.paths,p),{...h,supervisorState:p,verifierDispatch:null,continuation:te(h.state)}}return{...h,verifierDispatch:h.requestChecks===null?null:Ly({paths:e.paths,state:h.state,checks:h.checks,verifierExecutionRef:await $f({paths:e.paths,state:h.state}),supervisor:a?n:null}),continuation:te(h.state)}}Kr();ai();Hi();Wn();import za from"path";import{realpathSync as kT}from"fs";rt();var Zt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function qy(e){return e?e.command?`${Zt.next} ${e.command}`:e.ask_user?`${Zt.next} ${e.ask_user}`:null:null}function Wy(e,t){let r=[e.summary],i=qy(e.next);return i&&r.push(i),e.user_message&&r.push("",Zt.relay,e.user_message),t!==void 0&&r.push("",Zt.details,JSON.stringify(t,null,2)),`${r.join(`
249
+ `}function cI(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 iy(e){let t;try{t=await iI.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=cI(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Qi(e){await Je(e.file,sI(e.state,e.supervisor))}K();Xr();Ar();ut();var ay=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lI="comet-state.yaml",uI="state.json",KV=Is("en");function Tr(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function he(e,t){if(!ay.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ue.join(e.changesDir,t);if(!ge(e.changesDir,r))throw new Error("Native change path escaped");return r}function vt(e,t){return ue.join(he(e,t),lI)}function q(e,t){return ue.join(ke(e,t),uI)}async function Ba(e,t){try{let r=await ui.readFile(vt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Fe(e){return X(e).currentBranch}async function H(e,t){return Be(vt(e,t))}async function Re(e){let t=await Li({file:vt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ue.join(he(e.paths,t.name),"verification.md");await U(e.paths.nativeRoot,r),await ui.rm(r,{force:!0})}return t}async function Ef(e){let t=he(e.paths,e.state.name),r=ue.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ui.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!ay.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=ue.join(t,...s.split("/")),l=await ui.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=ue.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await ui.lstat(f);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:u,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function xf(e){let t=he(e.paths,e.state.name),r=await ie({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(qw(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await ie({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:_("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Ws({briefMarkdown:r.text,specs:i}),formalHash:_("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:_("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function Cf(e){return _("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function oy(e){return R(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await Ef({paths:e.paths,state:t}),i=await xf({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Ht({changeDir:he(e.paths,t.name),acceptanceIds:n.map(({id:u})=>u),validation:ci({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await $a(he(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let s=o?e.coordinationMode??t.coordination_mode:void 0;if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!o&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let c={...t,spec_changes:r,shape_confirmation_hash:Cf({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s})};delete c.children_contract_hash,delete c.coordination_mode,o&&(c.coordination_mode=s);let l=zw({state:c,acceptance:n.map(u=>({...u}))});a&&(l.children_contract_hash=Xi({acceptance:l.acceptance,children:a.contract}));let f=await Re({paths:e.paths,previous:t,next:l});return await G(q(e.paths,t.name),le({portableState:f,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function sy(e){return R(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await Qt({paths:e.paths,state:t});let r=await Ef({paths:e.paths,state:t}),i=await xf({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Ht({changeDir:he(e.paths,t.name),acceptanceIds:n.map(({id:p})=>p),validation:ci({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await $a(he(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,s=t.coordination_mode;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let c=Cf({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s});if(t.shape_confirmation_hash===void 0||c!==t.shape_confirmation_hash){let p=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Af({paths:e.paths,state:t,reason:p}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}let l=Ww({state:{...t,spec_changes:r},acceptance:n.map(p=>({...p}))});if(delete l.children_contract_hash,delete l.coordination_mode,a){l.children_contract_hash=Xi({acceptance:l.acceptance,children:a.contract}),o&&(l.coordination_mode=s);let p=[...t.history].reverse().find(({outcome:m})=>m==="pass"||m==="fail");if(p?.outcome==="fail"&&p.unresolved_ids.length>0){let m=await Qe({paths:e.paths,state:l}),g=new Map((m?.children??[]).map(({name:N,status:k})=>[N,k])),w=new Set(a.contract.children.filter(({name:N})=>{let k=g.get(N);return k!=="done"&&k!=="integrated"&&k!=="archived"}).flatMap(({covers:N})=>N)),y=p.unresolved_ids.filter(N=>!w.has(N));if(y.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${y.join(", ")}`)}}let f=null,u=a?.contract.schema==="comet.native.children.v2"?await D(e.paths,t.name):null,d=null,h=null;if(a?.contract.schema==="comet.native.children.v2"){if(d=t.workspace.change_branch??t.workspace.target_branch,!d)throw new Error("Native Supervisor v2 requires a target branch");if(h=xi(e.paths.projectRoot,d),!h)throw new Error(`Native Supervisor target branch has no commit: ${d}`);u||(u=await vc({paths:e.paths,parent:t.name,targetBranch:d,contract:a.contract})),u||(f=await bw({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:d,sourceConfig:await Te(e.paths.projectRoot)}))}let v=await Re({paths:e.paths,previous:t,next:l});if(await G(q(e.paths,t.name),le({portableState:v,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a?.contract.schema==="comet.native.children.v2"&&d&&h){let p=u?Sw({state:u,contract:a.contract}):f?af({parent:v.name,targetBranch:d,targetCommit:h,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null;if(!p)throw new Error("Native Supervisor integration state is unavailable");await W(e.paths,p)}return v})}async function Pc(e){let t=await Ef(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,f)=>{let u=e.state.spec_changes[f];return u!==void 0&&l.capability===u.capability&&l.source===u.source&&(l.operation===u.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await xf({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:f})=>({source:l,text:f}));if(!fg(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Ht({changeDir:he(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:ci({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Cf({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Xi({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Qt(e){let t=await Pc(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Af({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function cy(e){return R(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Qt({paths:e.paths,state:t}),await Ht({changeDir:he(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:ci(t)})||t.children_contract_hash){let a=await Qe({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Jw({state:t,input:e.input}),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Rc(e){let t=await H(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 i=await Qe({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function Pf(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:ks(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function ly(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Pf(t,r,i),executionCount:e.executionCount}}function uy(e,t){let r=ue.relative(ue.resolve(e),ue.resolve(t));if(ue.isAbsolute(r)||r===".."||r.startsWith(`..${ue.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(ue.sep).join("/");return ks(e,i),i}function kf(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return ea({id:e.id,name:e.id,executable:r,argv:i,cwdRef:uy(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function dI(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Zi(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:F(i),argv_display:Uu(r.argv.slice(1)).map(n=>F(n)),argv_truncated:!1,cwd_ref:uy(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:dI(r)}})}function fI(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function La(e){if(e.local===null||e.local.change!==e.state.name)return le({portableState:e.state,projectRoot:e.projectRoot,branch:Fe(e.projectRoot)});let t=e.local.execution?.operationId??Sf();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function en(e){try{let t=await Bt(q(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function dy(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function pI(e){let{state:t,local:r,envelope:i}=e;if(!Es(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function hI(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Cc(e){let t=await en({paths:e.paths,state:e.state}),r=Zw({state:e.state,summary:e.summary}),i=await Re({paths:e.paths,previous:e.state,next:r});return await G(q(e.paths,e.state.name),La({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function ny(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>kf(i,r)===ea(t[n]))}async function mI(e){return R(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Qt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=q(e.paths,t.name),i=(await bf({file:r,portableState:t,projectRoot:e.projectRoot,branch:Fe(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&ny(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Zi({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=Ha({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await Re({paths:e.paths,previous:t,next:c});throw await G(q(e.paths,t.name),le({portableState:l,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&ny(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Sf(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?ly(s,o,n,e.projectRoot):s?{...s,operationId:n}:Pf(o,n,e.projectRoot)})};return await G(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function Ec(e){return R(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=q(e.paths,t.name),i=await Bt(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await G(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function fy(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){br(t,c);let l=ea(c);i.has(l)||(i.add(l),r.push(c))}let n=await mI({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=ke(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Ec({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:l}:d)})});let f=await Ur({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await Ec({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:d)})})}await Ec({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Ec({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await Bt(q(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Zi({local:s,projectRoot:t,supplied:[]})}}async function vI(e){let t=q(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=mf)throw new Error(`Native Verifier request-checks exceeded ${mf} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let h of r.checks){let v=kf(h,e.projectRoot);n.set(v,h),h.status!=="interrupted"&&i.set(v,h),a.set(h.id,v)}let o=new Map,s=new Map;for(let h of e.response.checks){let v=fI(h);br(e.projectRoot,v);let p=ea(v),m=s.get(v.id);if(m!==void 0&&m!==p)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let g=a.get(v.id);if(g!==void 0&&g!==p)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,p);let w=n.get(p);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(p)||o.set(p,v)}let c=[...o.entries()],l=c.filter(([h])=>!i.has(h));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,u=new Map(c.map(([,h])=>[h.id,h.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(h=>{let v=kf(h,e.projectRoot),p=o.get(v);return p&&h.status==="interrupted"?ly(h,p,r.execution.operationId,e.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>Pf(h,r.execution.operationId,e.projectRoot))]};return await G(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,h])=>h),requestedNames:u,reusedCheckIds:c.filter(([h])=>i.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function xc(e){return R(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=q(e.paths,t.name),i=await Bt(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await G(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function gI(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await xc({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await Ur({projectRoot:e.projectRoot,runtimeDir:ke(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await xc({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await xc({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await xc({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Zi({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function py(e){return R(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Qt({paths:e.paths,state:t});let i=(await bf({file:q(e.paths,t.name),portableState:t,projectRoot:r,branch:Fe(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Zi({local:i,projectRoot:r,supplied:e.checks});let n=Gw(t),a=await Re({paths:e.paths,previous:t,next:n}),o=q(e.paths,t.name),s=Sf();return await G(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function hy(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await R(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await H(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Qt({paths:e.paths,state:r});let n=await en({paths:e.paths,state:r}),a=pI({state:r,local:n,envelope:e.envelope}),o;try{o=Xu(a.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,h=await Cc({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${h.loop.execution_failure_count}/${Oa} was recorded`,{cause:u})}let s=hI(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Zi({local:n,projectRoot:i,supplied:e.checks}));let u=Uw({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await vI({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:u.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:u.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,h=await Cc({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${h.loop.execution_failure_count}/${Oa} was recorded`,{cause:u})}let f=await Re({paths:e.paths,previous:r,next:l.state});return await G(q(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?La({local:n,state:f,projectRoot:i}):le({portableState:f,projectRoot:i,branch:Fe(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await Qi({file:ue.join(he(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await gI({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await R(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Cc({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Oa} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function my(e){return R(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=await en({paths:e.paths,state:t});if(dy({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Cc({paths:e.paths,state:t,summary:e.summary})})}async function vy(e){return R(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Qt({paths:e.paths,state:t});let r=await en({paths:e.paths,state:t}),i=dy({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Zi({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Yw({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Re({paths:e.paths,previous:t,next:a});return await G(q(e.paths,t.name),La({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Qi({file:ue.join(he(e.paths,t.name),"verification.md"),state:o}),o})}async function gy(e){return R(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Qt({paths:e.paths,state:t});let r=await D(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ia(r).stateVersion!==r.stateVersion)return by({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await W(e.paths,Ta(r,t))}let i=Kw(t),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Qi({file:ue.join(he(e.paths,t.name),"verification.md"),state:n}),n})}async function wI(e){let t=await H(e.paths,e.name),r=await Ks(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await D(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await ui.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Ia(n);if(i||a.stateVersion!==n.stateVersion){let o=await by({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await ui.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await W(e.paths,Ta(n,t)),{state:t,action:"recorded-final-verification"}}async function Rf(e){return R(e.paths,`recover Supervisor final verification ${e.name}`,()=>wI(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function wy(e){return R(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Qt({paths:e.paths,state:t});let r=Xw({state:t,summary:e.summary}),i=await Re({paths:e.paths,previous:t,next:r});return await G(q(e.paths,t.name),le({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Qi({file:ue.join(he(e.paths,t.name),"verification.md"),state:i}),i})}async function yy(e){return R(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Qt({paths:e.paths,state:t});let r=await en({paths:e.paths,state:t}),i=Qw(t,{reason:e.reason}),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),La({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Ny(e){return R(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Tr({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await en({paths:e.paths,state:t}),i=ey(t),n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),La({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Ac(e){return R(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=Ha({state:t,reason:e.reason}),i=await Re({paths:e.paths,previous:t,next:r});return await G(q(e.paths,t.name),le({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function _c(e){return R(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);if(Tr({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Af({paths:e.paths,state:t,reason:e.reason})})}async function Af(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...we(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:F(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.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"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function by(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...we(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:F(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await Re({paths:e.paths,previous:t,next:i});return await G(q(e.paths,t.name),le({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ic(e){if(e.state.verification===null)return"not-applicable";let t=ue.join(he(e.paths,e.state.name),"verification.md");return await iy({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Qi({file:t,state:e.state}),"rebuilt")}qt();K();ua();var ky=["evidence.md","repair.md","archive.md","checkpoint.md"],bI="verification.md";async function kI(e,t){let r=await Ks(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Sy(e,t){await Va.mkdir(e.transactionsDir,{recursive:!0}),await pe(Us(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ey(e,t,r={}){let i=r.removeVerificationReport===!1?ky:[...ky,bI];await Promise.all([Va.rm(ke(e,t),{recursive:!0,force:!0}),Va.rm(Ou(e,t),{recursive:!0,force:!0}),...i.map(n=>Va.rm(NI.join(Rt(e,t),n),{force:!0}))])}async function xy(e,t){await G(q(e,t.name),le({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Cy(e,t){try{let r=await la(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Py(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=X(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function SI(e){let t=Rt(e.paths,e.state.name),r=await ie({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await ie({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ws({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Ry(e,t){let r=await ig(e,t);if(r.status==="runtime-incompatible")throw new Sr(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Ay(e){return R(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await kI(e.paths,e.name),r=await Ba(e.paths,e.name)?await Be(vt(e.paths,e.name)):null;if(!t&&r)return await Ey(e.paths,e.name,{removeVerificationReport:!1}),await xy(e.paths,r),r;let i=null,n=null;for(t||(i=await Ry(e.paths,e.name),n=await Cy(e.paths,e.name),Py(e.paths,n),t={schema:Js,id:yI(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Sy(e.paths,t));;){let a=hg(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Ry(e.paths,e.name),n??=await Cy(e.paths,e.name),Py(e.paths,n),r=pg({state:i,acceptance:await SI({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Xn(vt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ey(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Be(vt(e.paths,e.name)),await xy(e.paths,r)),t={...t,status:a.nextStatus},await Sy(e.paths,t)}return await Va.rm(Us(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Be(vt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}it();import{promises as Iy}from"node:fs";import Ty from"node:path";xe();ja();ve();ai();import{promises as _f}from"node:fs";import EI from"node:path";var xI=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),CI=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),PI=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),RI=new Set(["status","summary"]);function Tc(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function jc(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function AI(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function di(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function _I(e,t,r,i){let n=Tc(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=jc(n,xI,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Tc(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=jc(o,CI,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Tc(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=jc(c,RI,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[f,u]of n.children.entries()){let d=Tc(u,`Native Supervisor child ${f}`);if(!d)return`Native Supervisor child ${f} must be an object`;let{acceptanceScope:h,contractHash:v,...p}=d,m=jc(p,PI,`Native Supervisor child ${f}`);if(m)return m;let g=r.children[f],w=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(h!==void 0&&JSON.stringify(h)!==JSON.stringify(w)||v!==void 0&&v!==_("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(d.name!==g.name||d.summary!==g.summary||!AI(d.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let y=g.depends_on.length===0?"ready":"pending";if(d.status!==y)return`Native Supervisor child ${g.name} has progressed beyond its initial ${y} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function Ma(e){let t=Yi(e.paths,e.state.name),r;try{let c=await _f.lstat(t);if(!c.isFile()||c.isSymbolicLink())return di(t,"","Native Supervisor overlay is not a regular file");r=await _f.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:di(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return di(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=EI.join(e.paths.changesDir,e.state.name),a;try{a=await Ht({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return di(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await D(e.paths,e.state.name)}catch(c){return di(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return di(t,r,"Native Supervisor overlay disappeared during inspection");let s=_I(i,e.state,a.contract,o);return s?di(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function _y(e){let t=await Ma({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await _f.rm(t.file,{force:!1})}qt();wa();function If(e,t){let r=X(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function II(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function TI(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:we(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:F(t),completed_at:i});return I({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?II(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function jI(e){try{let t=await Bt(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Tf(e){return R(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Ic({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=If(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await Ma({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await _y({paths:e.paths,state:t,expected:i}),n=!0);let a=q(e.paths,e.name),o=await jI(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await G(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Ic({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=Ha({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Li({file:vt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await Iy.rm(Ty.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=le({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await G(a,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let f=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",u=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=f||u;if(d){let v=TI(t,u?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",u);t=await Li({file:vt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let h=le({portableState:t,projectRoot:e.paths.projectRoot,branch:X(e.paths.projectRoot).currentBranch});return await Iy.mkdir(Ty.dirname(q(e.paths,t.name)),{recursive:!0}),await G(a,h,{containedRoot:e.paths.runtimeDir}),await Ic({paths:e.paths,state:t}),{state:t,local:h,action:d?"reverify":"resume-stable-boundary",reason:s,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import jy from"node:path";function $y(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function qe(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.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:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:$y(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.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(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:$y(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>jy.relative(t.projectRoot,jy.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}Qn();Vr();it();rf();ia();import{randomUUID as Vy}from"node:crypto";import{promises as Oy}from"node:fs";import qa from"node:path";ai();xe();Kr();function tn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function me(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function L(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Of(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>L(r,`${t}[${i}]`))}function $I(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=tn(t,`Native Builder check ${r}`);if(me(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:L(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function jf(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=tn(t,`Native Runtime check ${r}`);if(me(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:L(i.id,`Native Runtime check ${r} id`),name:L(i.name,`Native Runtime check ${r} name`),executable:L(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:L(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function Hy(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:L(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function OI(e){let t=tn(e,"Native Supervisor evidence");return me(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence"),{summary:L(t.summary,"Native Supervisor evidence summary"),checks:Of(t.checks,"Native Supervisor evidence checks"),acceptance:Cs(t.acceptance),...t.receiptRef===null?{}:{receiptRef:L(t.receiptRef,"Native Supervisor receipt ref")}}}function HI(e){let t=tn(e,"Native Runner input");if(t.kind==="builder-handoff"){me(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=tn(t.review,"Native Builder review");if(me(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:L(t.summary,"Native Builder summary"),addressed_acceptance_ids:Of(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:$I(t.checks),known_limits:Of(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:L(r.summary,"Native Builder review summary"),reviewer_execution_ref:L(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return me(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:jf(t.checks)};if(t.kind==="verifier-response")return me(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return me(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:L(t.summary,"Native Verifier execution error summary"),...Hy(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return me(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:L(t.summary,"Native unavailable Verifier summary"),...Hy(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return me(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),candidateCommit:L(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return me(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),reason:L(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return me(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return me(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),reason:L(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(me(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:OI(t.evidence)}}if(t.kind==="supervisor-checks"){if(me(t,["kind","child","runId","checks","materials"],"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:L(t.child,"Native Supervisor child"),runId:L(t.runId,"Native Supervisor runId"),checks:jf(t.checks),materials:t.materials.map(r=>{let i=tn(r,"Native Supervisor material");return me(i,["name","content"],"Native Supervisor material"),{name:L(i.name,"Native Supervisor material name"),content:L(i.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate")return me(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:L(t.child,"Native Supervisor child"),checks:jf(t.checks)};throw new Error("Native Runner input kind is invalid")}async function My(e,t){let r=qa.resolve(t,e),i=await Oy.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Oy.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return HI(n)}function Dy(e){return`${ne}:${e}:${Vy()}`}function By(e,t,r,i){if(qa.resolve(T(e.projectRoot,["rev-parse","--show-toplevel"]))!==qa.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(T(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!Wt(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(T(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{T(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function DI(e,t){let r=X(e.projectRoot),i=qa.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==qa.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=T(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!Wt(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{T(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Fa(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==ne)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function BI(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function Ly(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Fa(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=BI(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:ne,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:he(t,r.name),supervisorStateRef:a?Yi(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:u})=>({capability:l,operation:f,ref:u})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function $f(e){Fa(e.state);let t=await Bt(q(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function Fy(e){let t=e.input,r=await H(e.paths,e.name),i=await Ma({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:v})=>v==="integrated"||v==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:v})=>v==="integrated"||v==="archived");if(n&&t.kind==="supervisor-checks"){let v=await tf({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials});return{state:r,supervisorState:await D(e.paths,e.name),supervisorTask:null,checks:[],checkExecution:v,requestChecks:null,verifierDispatch:null,continuation:Z(r)}}if(n&&t.kind==="supervisor-builder-result")return R(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:N})=>N===t.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{By(p.task,t.candidateCommit,"builder",`comet/supervisor/${v.parent}/${t.child}`)}catch(N){throw await W(e.paths,gc(v,{child:t.child,runId:t.runId,reason:N.message})),N}let m=p.task.projectRoot,g=Cw(v,t),w=of(g,{role:"verifier",child:t.child,projectRoot:m,runId:Vy()});await W(e.paths,w.state);let y=await H(e.paths,e.name);return{state:y,supervisorTask:w.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(y)}});if(n&&t.kind==="supervisor-builder-failure")return R(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:w})=>w===t.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let m=sf(v,{child:t.child,runId:t.runId,reason:t.reason});await W(e.paths,m);let g=await H(e.paths,e.name);return{state:g,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(g)}});if(n&&t.kind==="supervisor-reconnect")return R(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:w})=>w===t.child)?.task;if(!p||p.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{DI(p,`comet/supervisor/${v.parent}/${t.child}`)}catch(w){throw await W(e.paths,gc(v,{child:t.child,runId:t.runId,reason:w.message})),w}let m=Ew(v,{child:t.child,runId:t.runId});await W(e.paths,m.state);let g=await H(e.paths,e.name);return{state:g,supervisorState:m.state,supervisorTask:m.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(g)}});if(n&&t.kind==="supervisor-cancel")return R(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=sf(v,{child:t.child,runId:t.runId,reason:t.reason});await W(e.paths,p);let m=await H(e.paths,e.name);return{state:m,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(m)}});if(n&&t.kind==="supervisor-verifier-result")return R(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let v=await D(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=v.children.find(({name:y})=>y===t.child);if(!p?.task||p.task.role!=="verifier"||!p.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{By(p.task,p.candidateCommit,"verifier",`comet/supervisor/${v.parent}/${t.child}`)}catch(y){throw await W(e.paths,gc(v,{child:t.child,runId:t.runId,reason:y.message})),y}let m=t.evidence.receiptRef||t.verdict==="pass"?await pc({paths:e.paths,parent:e.name,task:p.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!m||m.checks.some(({status:y,exitCode:N})=>y!=="passed"||N!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=Pw(v,{...t,evidence:{...t.evidence,checks:m?.checks.map(({name:y,status:N})=>`${y}: ${N}`)??[],execution:structuredClone(p.task)}});await W(e.paths,g);let w=await H(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(w)}});if(n&&t.kind==="supervisor-integrate"){let v=await Rw({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks}),p=await Rc({paths:e.paths,name:e.name,trigger:"v2-integrate"}),m=p.state;return{state:m,supervisorState:v,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:p.parentAdvance,continuation:Z(m)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="verifier-response"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let p=Yu().captureExecutionIdentity({identityProvider:ne,executionRef:Dy("builder")}),m=await cy({paths:e.paths,name:e.name,input:{identity:p,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}}});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(m)}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let v=await H(e.paths,e.name);if(v.builder_handoff!==null&&v.builder_handoff.identity_provider!==ne){let y=await Ac({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:y,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(y)}}Fa(v);let m=(v.loop.next_action==="run-final-full-verification"&&v.verification?.verdict==="pass"&&v.verification.checks.every(({status:y})=>y==="passed")?v.verification.checks:null)??(await fy({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}})).checks,g=Dy("verifier"),w=await py({paths:e.paths,name:e.name,checks:m,verifierExecutionId:g,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:w,checks:m,requestChecks:null,verifierDispatch:Ly({paths:e.paths,state:w,checks:m,verifierExecutionRef:g,supervisor:a?n:null}),continuation:Z(w)}}if(t.kind==="verifier-execution-error"){let v=await H(e.paths,e.name);Fa(v),await $f({paths:e.paths,state:v});let p=await my({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:p,checks:[],requestChecks:null,verifierDispatch:null,continuation:Z(p)}}if(t.kind==="verifier-unavailable"){let v=await vy({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:v,checks:v.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Z(v)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await H(e.paths,e.name),c=Fa(s),l=await $f({paths:e.paths,state:s}),f=Yu(),u=f.captureExecutionIdentity({identityProvider:ne,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let v=await D(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared before final verification");d=Ia(v)}let h=await hy({paths:e.paths,name:e.name,envelope:f.envelopeVerifierResponse({candidateId:c.candidate_id,identity:u,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&h.response.kind==="final-result"){if(h.state.verification_result==="pass"&&(h.checks.length===0||h.checks.some(({status:m})=>m!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let v=d??await D(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared during verification");let p=Ta(v,h.state);return await W(e.paths,p),{...h,supervisorState:p,verifierDispatch:null,continuation:Z(h.state)}}return{...h,verifierDispatch:h.requestChecks===null?null:Ly({paths:e.paths,state:h.state,checks:h.checks,verifierExecutionRef:await $f({paths:e.paths,state:h.state}),supervisor:a?n:null}),continuation:Z(h.state)}}Kr();ai();Hi();Wn();import za from"path";import{realpathSync as kT}from"fs";it();var Zt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function qy(e){return e?e.command?`${Zt.next} ${e.command}`:e.ask_user?`${Zt.next} ${e.ask_user}`:null:null}function Wy(e,t){let r=[e.summary],i=qy(e.next);return i&&r.push(i),e.user_message&&r.push("",Zt.relay,e.user_message),t!==void 0&&r.push("",Zt.details,JSON.stringify(t,null,2)),`${r.join(`
250
250
  `)}
251
251
  `}function zy(e,t,r){let i=[e.summary],n=qy(e.next);return n&&i.push(n),e.user_message&&i.push("",Zt.relay,e.user_message),i.push("",`${Zt.detail} ${t}`),r!==void 0&&i.push("",Zt.details,JSON.stringify(r,null,2)),i.join(`
252
- `)}sa();ve();at();ye();ve();var LI=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});Ar();kt();ua();ye();lt();K();oa();Q();ye();St();na();xe();K();kt();Nr();ve();ve();sc();Gi();St();var Jy={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},VI=Me("comet-native-runtime:v3:scope-reopen"),OM=[{skillVersion:"3",skillHash:Me("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Me("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Me("comet-native-runtime:v1")}];sa();St();sa();St();ld();Bs();var Uy=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],mF=new Set(Uy),GI=new Set([...Uy,"minimum_runtime_version","revision"]),vF=new Set([...GI,"operation"]),gF=512*1024,UI=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),wF=new Set([...UI,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);qs();at();ye();at();qs();ve();var SF={maxAcceptanceCriteria:Fs.maxCriteria};var RF={maxSpecs:64,maxFileBytes:Ko,maxTotalBytes:4*1024*1024};Ar();aa();Gi();sc();import{execFile as rT}from"node:child_process";bs();Gu();ye();import{promisify as iT}from"node:util";ye();Q();ye();St();K();kt();Hn();Nr();var BF={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};xe();Q();Fd();K();yt();var aq=512*1024;Ar();xe();Nr();var Wa=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};aa();lc();Gi();var Cq=64*1024;var Pq=3600*1e3;var Rq=iT(rT);lc();var $c=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};ua();St();kt();var lW={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};Q();yt();K();kt();ec();var yW=16*1024*1024,NW=256*1024,bW=16*1024;ye();Q();Xr();ye();Ar();var PW=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});St();na();xe();K();kt();Wn();var _W=16*1024;ye();lt();xe();var FW=16*1024;ec();var T2=16*1024*1024,Oc=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Hc=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};ye();K();lt();function j(e,t,r){return e==="zh-CN"?r:t}var Hf={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Yy(e,t){return typeof e=="string"&&Hf[e]?j(t,Hf[e].en,Hf[e].zh):typeof e=="string"?e:""}function Df(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 cT(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 i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Xy(e,t){let r=[];e.failed>0&&r.push(j(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(j(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(j(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=j(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Qy(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 Bf(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function lT(e,t,r){return e==="done"?j(r,"complete","已完成"):e==="await-user"?j(r,"waiting for a user decision","等待用户决定"):e==="blocked"?j(r,"paused: needs attention","已暂停,需要处理"):t?j(r,"waiting for a user decision","等待用户决定"):j(r,"ready to continue","可继续推进")}function uT(e,t,r){let i=Bf(e),n=[];r&&n.push(r);let a=j(i,`Change ${e.change}`,`需求 ${e.change}`),o=Yy(e.phase,i),s=lT(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Xy(t,i));let c=e.userCommunication,l=Zy(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Zy(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:j(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 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:j(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:j(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function dT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function fT(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Yy(e.phase,t),n=e.status==="await-user"?j(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?j(t,"paused","已暂停"):e.status==="done"?j(t,"complete","已完成"):j(t,"in progress","进行中"),a=Df(e.acceptance)?`${j(t,", ",",")}${Xy(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function pT(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 hT(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 mT(e){if(e.healthy){let i=e.repaired?j("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):j("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=vT(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:j("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:j("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function vT(e){return Qy(e)?Zy(e,Bf(e)):void 0}function eN(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(hT(t))return mT(t);if(dT(t)){let i=pT(t.items);return{summary:[t.total===t.items.length?j(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):j(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>fT(a,i))].join(`
253
- `)}}let r=t.continuation;if(Qy(r))return uT(r,gT(t),wT(t,Bf(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:j(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function gT(e){if(Df(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Df(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return cT(r.acceptance)}return null}function wT(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return j(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?j(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function tN(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:j("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:j("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:j("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:j("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:j("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:j("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:j("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:j("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:j("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}jd();var rN=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Vf=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",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 remove Record a complete capability removal intent.","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.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:rN,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> [--language en|zh-CN] [--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:["--language en|zh-CN Artifact language; defaults to project configuration.","--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 portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","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 remove <change-name> <capability>
254
- 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:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],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 sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},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 Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail 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>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
252
+ `)}sa();ve();ot();ye();ve();var LI=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});Ar();St();ua();ye();ut();K();oa();Q();ye();Et();na();xe();K();St();Nr();ve();ve();sc();Gi();Et();var Jy={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},VI=Me("comet-native-runtime:v3:scope-reopen"),OM=[{skillVersion:"3",skillHash:Me("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Me("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Me("comet-native-runtime:v1")}];sa();Et();sa();Et();ld();Bs();var Uy=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],mF=new Set(Uy),GI=new Set([...Uy,"minimum_runtime_version","revision"]),vF=new Set([...GI,"operation"]),gF=512*1024,UI=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),wF=new Set([...UI,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);qs();ot();ye();ot();qs();ve();var SF={maxAcceptanceCriteria:Fs.maxCriteria};var RF={maxSpecs:64,maxFileBytes:Ko,maxTotalBytes:4*1024*1024};Ar();aa();Gi();sc();import{execFile as rT}from"node:child_process";bs();Gu();ye();import{promisify as iT}from"node:util";ye();Q();ye();Et();K();St();Hn();Nr();var BF={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};xe();Q();Fd();K();Nt();var aq=512*1024;Ar();xe();Nr();var Wa=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};aa();lc();Gi();var Cq=64*1024;var Pq=3600*1e3;var Rq=iT(rT);lc();var $c=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};ua();Et();St();var lW={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};Q();Nt();K();St();ec();var yW=16*1024*1024,NW=256*1024,bW=16*1024;ye();Q();Xr();ye();Ar();var PW=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Et();na();xe();K();St();Wn();var _W=16*1024;ye();ut();xe();var FW=16*1024;ec();var T2=16*1024*1024,Oc=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Hc=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};ye();K();ut();function j(e,t,r){return e==="zh-CN"?r:t}var Hf={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Yy(e,t){return typeof e=="string"&&Hf[e]?j(t,Hf[e].en,Hf[e].zh):typeof e=="string"?e:""}function Df(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 cT(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 i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Xy(e,t){let r=[];e.failed>0&&r.push(j(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(j(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(j(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=j(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Qy(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 Bf(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function lT(e,t,r){return e==="done"?j(r,"complete","已完成"):e==="await-user"?j(r,"waiting for a user decision","等待用户决定"):e==="blocked"?j(r,"paused: needs attention","已暂停,需要处理"):t?j(r,"waiting for a user decision","等待用户决定"):j(r,"ready to continue","可继续推进")}function uT(e,t,r){let i=Bf(e),n=[];r&&n.push(r);let a=j(i,`Change ${e.change}`,`需求 ${e.change}`),o=Yy(e.phase,i),s=lT(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Xy(t,i));let c=e.userCommunication,l=Zy(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Zy(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:j(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 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:j(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:j(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function dT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function fT(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Yy(e.phase,t),n=e.status==="await-user"?j(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?j(t,"paused","已暂停"):e.status==="done"?j(t,"complete","已完成"):j(t,"in progress","进行中"),a=Df(e.acceptance)?`${j(t,", ",",")}${Xy(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function pT(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 hT(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 mT(e){if(e.healthy){let i=e.repaired?j("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):j("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=vT(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:j("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:j("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function vT(e){return Qy(e)?Zy(e,Bf(e)):void 0}function eN(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(hT(t))return mT(t);if(dT(t)){let i=pT(t.items);return{summary:[t.total===t.items.length?j(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):j(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>fT(a,i))].join(`
253
+ `)}}let r=t.continuation;if(Qy(r))return uT(r,gT(t),wT(t,Bf(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:j(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function gT(e){if(Df(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Df(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return cT(r.acceptance)}return null}function wT(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return j(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?j(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function tN(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:j("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:j("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:j("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:j("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:j("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:j("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:j("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:j("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:j("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}jd();var rN=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Vf=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",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 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.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:rN,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> [--language en|zh-CN] [--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:["--language en|zh-CN Artifact language; defaults to project configuration.","--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 portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","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 remove <change-name> <capability>
254
+ 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:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],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 sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},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 the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",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 Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail 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>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
255
255
  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>]
256
256
  comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--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 Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--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.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," 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 fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}]. Returns checkExecution with operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing 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 --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
257
257
  comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,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.","--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."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Lf(e,t){return`${e}:
@@ -259,11 +259,11 @@ ${t.map(r=>` ${r}`).join(`
259
259
  `)}`}function yT(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Vf[r]||t.length>1&&Vf[t[0]]?.subcommands?r:t[0]}function NT(e=[]){let t=yT(e),r=Vf[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Lf("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...rN];return n&&n.length>0&&i.push("",Lf("Options",n)),i.push("",`Output:
260
260
  ${r.output}`),r.examples&&i.push("",Lf("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
261
261
  `)}
262
- `}}var bT=NT().usage;var X2=10*1024*1024,z=class extends Error{};function Bt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new z(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function er(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new z(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new z(`${t} requires a value`);return e.splice(i,2),n}function nN(e){if(e.length>0)throw new z(`Unexpected argument: ${e[0]}`)}function aN(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new z(`${t} is required`);return r}function Mf(e,t){let r=za.normalize(iN(e)),i=za.normalize(iN(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function iN(e){let t=za.resolve(e);try{return kT.native(t)}catch{return t}}function ST(e){let t=za.resolve(e),r=X(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=X(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Mf(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Mf(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Mf(process.cwd(),r.currentWorktreeRoot)?za.resolve(process.cwd()):r.currentWorktreeRoot}async function oN(e){return e?ST(e):ls(process.cwd())}async function sN(e){let t=await Zm({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function cN(e){return JSON.stringify(e,null,2)+`
263
- `}function Ze(e,t,r){return{command:e,exitCode:0,data:t,text:r??cN(t)}}function ET(e,t){if(t instanceof z)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Oc)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 Hc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ls)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 da)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 Er)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Vs)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof $c)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Wa)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 i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function lN(e,t){let r=ET(e,t),i=r.error;if(!i)return r;let n=tN({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function uN(e,t,r=!1){let i=e.envelope??eN(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
262
+ `}}var bT=NT().usage;var X2=10*1024*1024,z=class extends Error{};function Lt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new z(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function er(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new z(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new z(`${t} requires a value`);return e.splice(i,2),n}function nN(e){if(e.length>0)throw new z(`Unexpected argument: ${e[0]}`)}function aN(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new z(`${t} is required`);return r}function Mf(e,t){let r=za.normalize(iN(e)),i=za.normalize(iN(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function iN(e){let t=za.resolve(e);try{return kT.native(t)}catch{return t}}function ST(e){let t=za.resolve(e),r=X(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=X(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Mf(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Mf(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Mf(process.cwd(),r.currentWorktreeRoot)?za.resolve(process.cwd()):r.currentWorktreeRoot}async function oN(e){return e?ST(e):ls(process.cwd())}async function sN(e){let t=await Zm({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function cN(e){return JSON.stringify(e,null,2)+`
263
+ `}function et(e,t,r){return{command:e,exitCode:0,data:t,text:r??cN(t)}}function ET(e,t){if(t instanceof z)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Oc)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 Hc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ls)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 da)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 Er)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Vs)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof $c)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Wa)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 i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function lN(e,t){let r=ET(e,t),i=r.error;if(!i)return r;let n=tN({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function uN(e,t,r=!1){let i=e.envelope??eN(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
264
264
  `}:e.error?{exitCode:e.exitCode,stderr:i?zy(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Wy(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==cN(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
265
265
  ${Zt.details}
266
266
  ${JSON.stringify(e.data,null,2)}
267
- `}:{exitCode:e.exitCode,stdout:e.text}}var xT=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function CT(e){let t=er(e,"--expected-state-version"),r=er(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new z("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new z("--expected-state-version must be a positive integer");if(!xT.has(r))throw new z("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function tr(e,t){let r=await Qe({paths:e,state:t}),n=(r?.confirmed?await D(e,t.name,{diagnostics:!0}):null)?.children.flatMap(({task:a})=>a?[a.child]:[])??[];return{...r?{childSummary:r.children.reduce((a,o)=>({...a,[o.status]:(a[o.status]??0)+1}),{total:r.children.length}),readyChildren:n.length>0?n:r.readyChildren}:{},continuation:te(t,r)}}function PT(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function dN(e){return{action:e.action,reason:e.reason,message:e.message}}async function fN(e,t){let r=aN(e,"change name"),i=er(e,"--summary"),n=er(e,"--runner-input"),a=Bt(e,"--confirmed"),o=Bt(e,"--accept-result"),s=Bt(e,"--revise-implementation"),c=Bt(e,"--revise-requirements"),l=Bt(e,"--retry-verifier"),f=Bt(e,"--resolve-verifier-blocker"),u=er(e,"--coordination-mode"),d=u;if(u!==void 0&&!hs.includes(u))throw new z("--coordination-mode must be multi-session or single-session");let h=er(e,"--max-parallel"),v=h===void 0?2:Number(h);if(!Number.isSafeInteger(v)||v<1)throw new z("--max-parallel must be a positive integer");let p=CT(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new z("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(d!==void 0&&(a||o||s||c||l||f||n!==void 0))throw new z("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");nN(e);let m=await sN(t);if(!await Ba(m.paths,r)){if(n)throw new z("--runner-input is only valid for portable Native changes");if(!i)throw new z("--summary is required");let S=await Ay({paths:m.paths,name:r});return Ze("next",{state:qe(S,m.paths),migration:{completed:!0,summary:i},continuation:te(S)})}let g=await H(m.paths,r),w=If(m.paths,g);if(w)return Ze("next",{state:qe(g,m.paths),recovery:{action:"await-user",reason:"workspace-mismatch",message:w},...await tr(m.paths,g)});if(n){if(i||a||o||s||c||l||f||d!==void 0||p)throw new z("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let S=await Rf({paths:m.paths,name:r});if(S.action==="rerun-final-verification")return Ze("next",{state:qe(S.state,m.paths),...await tr(m.paths,S.state)});let E=await Tf({paths:m.paths,name:r,preserveRunningExecution:!0}),A=E.state;if(E.action==="await-user"||E.action==="done"||E.reason!=="available")return Ze("next",{state:qe(A,m.paths),recovery:dN(E),...await tr(m.paths,A)});if(A.phase==="build"){let de=await Pc({paths:m.paths,state:A});if(de.drifted){let Oe=await _c({paths:m.paths,name:r,reason:de.reason??"Native confirmed requirements changed"});return Ze("next",{state:qe(Oe,m.paths),...await tr(m.paths,Oe)})}let rr=await D(m.paths,r),vt=await Qe({paths:m.paths,state:A});if(vt&&!vt.allDone&&!rr)throw new z("Native parent Build advances child changes and does not accept a Builder handoff")}let M=await My(n,t),$=await Fy({paths:m.paths,name:r,input:M,maxVerifyFailures:m.config.native.max_verify_failures});return Ze("next",{...PT($),state:qe($.state,m.paths),...await tr(m.paths,$.state),coordination:ne})}let y=await Rf({paths:m.paths,name:r});if(y.action==="rerun-final-verification")return Ze("next",{state:qe(y.state,m.paths),...await tr(m.paths,y.state)});let N=await Tf({paths:m.paths,name:r}),k=N.state;if(d!==void 0&&k.phase!=="shape")throw new z("--coordination-mode is only valid when confirming Shape");if(!i)throw new z("--summary is required");let b,P=null;if(a)if(k.phase==="shape"&&k.status==="await-user"&&k.loop.next_action==="confirm-shape"){if(!p)throw new z("--expected-state-version and --expected-action are required for Shape confirmation");b=await sy({paths:m.paths,name:r,expectedContinuation:p})}else{if(k.phase==="shape")throw new z("--confirmed is only valid from the persisted Shape user confirmation boundary");if(k.phase==="verify"&&k.status==="await-user"&&k.loop.next_action==="confirm-verifier-unavailable")b=await wy({paths:m.paths,name:r,summary:i,expectedContinuation:p});else throw new z("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(o){if(!p&&(k.phase!=="verify"||k.status!=="await-user"||k.loop.next_action!=="confirm-skill-coordinated-pass"))throw new z("--accept-result is only valid for a pending Verify pass decision");b=await gy({paths:m.paths,name:r,expectedContinuation:p})}else if(s){if(k.phase!=="verify")throw new z("--revise-implementation is only valid from Verify");b=await Ac({paths:m.paths,name:r,reason:i,expectedContinuation:p})}else if(c){if(!p&&k.phase!=="verify"&&k.phase!=="archive")throw new z("--revise-requirements is only valid from Verify or Archive");b=await _c({paths:m.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:p})}else if(l)b=await Ny({paths:m.paths,name:r,expectedContinuation:p});else if(f)b=await yy({paths:m.paths,name:r,reason:i,expectedContinuation:p});else{if(N.reason!=="available")return Ze("next",{state:qe(k,m.paths),recovery:dN(N),...await tr(m.paths,k)});if(k.phase==="build"){let E=await Pc({paths:m.paths,state:k});if(E.drifted)b=await _c({paths:m.paths,name:r,reason:E.reason??"Native confirmed requirements changed"});else{let A=await Qe({paths:m.paths,state:k});if(A){let M=A,$=[],de=[],rr=null,vt=await D(m.paths,r);if(vt&&!A.allDone){let Oe=await xw({paths:m.paths,parent:r,maxParallel:k.coordination_mode==="single-session"?1:v});$=Oe.state.children.flatMap(({task:ae})=>ae?[ae]:[]),rr=Oe.tasks.map(({child:ae})=>ae),de=Oe.state.children.flatMap(({name:ae,blocker:Ff})=>Ff?[{child:ae,message:Ff}]:[]),($.length>0||Oe.state.stateVersion!==vt.stateVersion)&&(M=await Qe({paths:m.paths,state:k})??M)}if(M.allDone&&!(k.loop.stage==="repairing"&&k.verification_result==="fail"))P=await Rc({paths:m.paths,name:r,trigger:"recovery"}),b=P.state;else return Ze("next",{state:qe(k,m.paths),childSummary:M.children.reduce((Oe,ae)=>({...Oe,[ae.status]:(Oe[ae.status]??0)+1}),{total:M.children.length}),readyChildren:rr??M.readyChildren,...$.length>0?{supervisorTasks:$}:{},...de.length>0?{supervisorBlockers:de}:{},continuation:te(k,M)})}}}if(k.phase==="shape"&&(b=await oy({paths:m.paths,name:r,...d===void 0?{}:{coordinationMode:d},expectedContinuation:p})),b)return Ze("next",{state:qe(b,m.paths),...P?{parentAdvance:P.parentAdvance}:{},...await tr(m.paths,b)});let S=k.phase==="shape"?await Qe({paths:m.paths,state:k}):null;return{command:"next",exitCode:65,data:{state:qe(k,m.paths),continuation:te(k,S)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return Ze("next",{state:qe(b,m.paths),...d===void 0?{}:{coordinationMode:d},...await tr(m.paths,b)})}async function pN(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Bt(n,"--json"),Bt(n,"--verbose"),c=er(n,"--project-root");let u=[...n,...a],d=await oN(c);l=await t(u,d)}catch(u){l=lN(e,u)}let f=uN(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
267
+ `}:{exitCode:e.exitCode,stdout:e.text}}var xT=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function CT(e){let t=er(e,"--expected-state-version"),r=er(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new z("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new z("--expected-state-version must be a positive integer");if(!xT.has(r))throw new z("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function tr(e,t){let r=await Qe({paths:e,state:t}),n=(r?.confirmed?await D(e,t.name,{diagnostics:!0}):null)?.children.flatMap(({task:a})=>a?[a.child]:[])??[];return{...r?{childSummary:r.children.reduce((a,o)=>({...a,[o.status]:(a[o.status]??0)+1}),{total:r.children.length}),readyChildren:n.length>0?n:r.readyChildren}:{},continuation:Z(t,r)}}function PT(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function dN(e){return{action:e.action,reason:e.reason,message:e.message}}async function fN(e,t){let r=aN(e,"change name"),i=er(e,"--summary"),n=er(e,"--runner-input"),a=Lt(e,"--confirmed"),o=Lt(e,"--accept-result"),s=Lt(e,"--revise-implementation"),c=Lt(e,"--revise-requirements"),l=Lt(e,"--retry-verifier"),f=Lt(e,"--resolve-verifier-blocker"),u=er(e,"--coordination-mode"),d=u;if(u!==void 0&&!hs.includes(u))throw new z("--coordination-mode must be multi-session or single-session");let h=er(e,"--max-parallel"),v=h===void 0?2:Number(h);if(!Number.isSafeInteger(v)||v<1)throw new z("--max-parallel must be a positive integer");let p=CT(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new z("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(d!==void 0&&(a||o||s||c||l||f||n!==void 0))throw new z("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");nN(e);let m=await sN(t);if(!await Ba(m.paths,r)){if(n)throw new z("--runner-input is only valid for portable Native changes");if(!i)throw new z("--summary is required");let S=await Ay({paths:m.paths,name:r});return et("next",{state:qe(S,m.paths),migration:{completed:!0,summary:i},continuation:Z(S)})}let g=await H(m.paths,r),w=If(m.paths,g);if(w){let S=Z(g),E=g.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return et("next",{state:qe(g,m.paths),...await tr(m.paths,g),recovery:{action:"await-user",reason:"workspace-mismatch",message:w},continuation:{...S,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...S.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${w}. ${E}`,suggestedReply:null,agentInstruction:E}}})}if(n){if(i||a||o||s||c||l||f||d!==void 0||p)throw new z("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let S=await Rf({paths:m.paths,name:r});if(S.action==="rerun-final-verification")return et("next",{state:qe(S.state,m.paths),...await tr(m.paths,S.state)});let E=await Tf({paths:m.paths,name:r,preserveRunningExecution:!0}),A=E.state;if(E.action==="await-user"||E.action==="done"||E.reason!=="available")return et("next",{state:qe(A,m.paths),recovery:dN(E),...await tr(m.paths,A)});if(A.phase==="build"){let de=await Pc({paths:m.paths,state:A});if(de.drifted){let Oe=await _c({paths:m.paths,name:r,reason:de.reason??"Native confirmed requirements changed"});return et("next",{state:qe(Oe,m.paths),...await tr(m.paths,Oe)})}let rr=await D(m.paths,r),gt=await Qe({paths:m.paths,state:A});if(gt&&!gt.allDone&&!rr)throw new z("Native parent Build advances child changes and does not accept a Builder handoff")}let M=await My(n,t),$=await Fy({paths:m.paths,name:r,input:M,maxVerifyFailures:m.config.native.max_verify_failures});return et("next",{...PT($),state:qe($.state,m.paths),...await tr(m.paths,$.state),coordination:ne})}let y=await Rf({paths:m.paths,name:r});if(y.action==="rerun-final-verification")return et("next",{state:qe(y.state,m.paths),...await tr(m.paths,y.state)});let N=await Tf({paths:m.paths,name:r}),k=N.state;if(d!==void 0&&k.phase!=="shape")throw new z("--coordination-mode is only valid when confirming Shape");if(!i)throw new z("--summary is required");let b,P=null;if(a)if(k.phase==="shape"&&k.status==="await-user"&&k.loop.next_action==="confirm-shape"){if(!p)throw new z("--expected-state-version and --expected-action are required for Shape confirmation");b=await sy({paths:m.paths,name:r,expectedContinuation:p})}else{if(k.phase==="shape")throw new z("--confirmed is only valid from the persisted Shape user confirmation boundary");if(k.phase==="verify"&&k.status==="await-user"&&k.loop.next_action==="confirm-verifier-unavailable")b=await wy({paths:m.paths,name:r,summary:i,expectedContinuation:p});else throw new z("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(o){if(!p&&(k.phase!=="verify"||k.status!=="await-user"||k.loop.next_action!=="confirm-skill-coordinated-pass"))throw new z("--accept-result is only valid for a pending Verify pass decision");b=await gy({paths:m.paths,name:r,expectedContinuation:p})}else if(s){if(k.phase!=="verify")throw new z("--revise-implementation is only valid from Verify");b=await Ac({paths:m.paths,name:r,reason:i,expectedContinuation:p})}else if(c){if(!p&&k.phase!=="verify"&&k.phase!=="archive")throw new z("--revise-requirements is only valid from Verify or Archive");b=await _c({paths:m.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:p})}else if(l)b=await Ny({paths:m.paths,name:r,expectedContinuation:p});else if(f)b=await yy({paths:m.paths,name:r,reason:i,expectedContinuation:p});else{if(N.reason!=="available")return et("next",{state:qe(k,m.paths),recovery:dN(N),...await tr(m.paths,k)});if(k.phase==="build"){let E=await Pc({paths:m.paths,state:k});if(E.drifted)b=await _c({paths:m.paths,name:r,reason:E.reason??"Native confirmed requirements changed"});else{let A=await Qe({paths:m.paths,state:k});if(A){let M=A,$=[],de=[],rr=null,gt=await D(m.paths,r);if(gt&&!A.allDone){let Oe=await xw({paths:m.paths,parent:r,maxParallel:k.coordination_mode==="single-session"?1:v});$=Oe.state.children.flatMap(({task:ae})=>ae?[ae]:[]),rr=Oe.tasks.map(({child:ae})=>ae),de=Oe.state.children.flatMap(({name:ae,blocker:Ff})=>Ff?[{child:ae,message:Ff}]:[]),($.length>0||Oe.state.stateVersion!==gt.stateVersion)&&(M=await Qe({paths:m.paths,state:k})??M)}if(M.allDone&&!(k.loop.stage==="repairing"&&k.verification_result==="fail"))P=await Rc({paths:m.paths,name:r,trigger:"recovery"}),b=P.state;else return et("next",{state:qe(k,m.paths),childSummary:M.children.reduce((Oe,ae)=>({...Oe,[ae.status]:(Oe[ae.status]??0)+1}),{total:M.children.length}),readyChildren:rr??M.readyChildren,...$.length>0?{supervisorTasks:$}:{},...de.length>0?{supervisorBlockers:de}:{},continuation:Z(k,M)})}}}if(k.phase==="shape"&&(b=await oy({paths:m.paths,name:r,...d===void 0?{}:{coordinationMode:d},expectedContinuation:p})),b)return et("next",{state:qe(b,m.paths),...P?{parentAdvance:P.parentAdvance}:{},...await tr(m.paths,b)});let S=k.phase==="shape"?await Qe({paths:m.paths,state:k}):null;return{command:"next",exitCode:65,data:{state:qe(k,m.paths),continuation:Z(k,S)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return et("next",{state:qe(b,m.paths),...d===void 0?{}:{coordinationMode:d},...await tr(m.paths,b)})}async function pN(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Lt(n,"--json"),Lt(n,"--verbose"),c=er(n,"--project-root");let u=[...n,...a],d=await oN(c);l=await t(u,d)}catch(u){l=lN(e,u)}let f=uN(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
268
268
  `)?"":`
269
269
  `)),f.exitCode}process.exitCode=await pN("next",fN);