@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 Ep=Object.create;var wa=Object.defineProperty;var xp=Object.getOwnPropertyDescriptor;var Cp=Object.getOwnPropertyNames;var Pp=Object.getPrototypeOf,Rp=Object.prototype.hasOwnProperty;var yi=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var E=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(i){throw r=[i],i}};var k=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},vc=(t,e)=>{for(var r in e)wa(t,r,{get:e[r],enumerable:!0})},Ap=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Cp(e))!Rp.call(t,n)&&n!==r&&wa(t,n,{get:()=>e[n],enumerable:!(i=xp(e,n))||i.enumerable});return t};var mr=(t,e,r)=>(r=t!=null?Ep(Pp(t)):{},Ap(e||!t||!t.__esModule?wa(r,"default",{value:t,enumerable:!0}):r,t));var R=k(W=>{"use strict";var ya=Symbol.for("yaml.alias"),gc=Symbol.for("yaml.document"),Ni=Symbol.for("yaml.map"),wc=Symbol.for("yaml.pair"),Na=Symbol.for("yaml.scalar"),bi=Symbol.for("yaml.seq"),He=Symbol.for("yaml.node.type"),_p=t=>!!t&&typeof t=="object"&&t[He]===ya,Ip=t=>!!t&&typeof t=="object"&&t[He]===gc,Tp=t=>!!t&&typeof t=="object"&&t[He]===Ni,jp=t=>!!t&&typeof t=="object"&&t[He]===wc,yc=t=>!!t&&typeof t=="object"&&t[He]===Na,$p=t=>!!t&&typeof t=="object"&&t[He]===bi;function Nc(t){if(t&&typeof t=="object")switch(t[He]){case Ni:case bi:return!0}return!1}function Op(t){if(t&&typeof t=="object")switch(t[He]){case ya:case Ni:case Na:case bi:return!0}return!1}var Hp=t=>(yc(t)||Nc(t))&&!!t.anchor;W.ALIAS=ya;W.DOC=gc;W.MAP=Ni;W.NODE_TYPE=He;W.PAIR=wc;W.SCALAR=Na;W.SEQ=bi;W.hasAnchor=Hp;W.isAlias=_p;W.isCollection=Nc;W.isDocument=Ip;W.isMap=Tp;W.isNode=Op;W.isPair=jp;W.isScalar=yc;W.isSeq=$p});var vr=k(ba=>{"use strict";var B=R(),X=Symbol("break visit"),bc=Symbol("skip children"),xe=Symbol("remove node");function ki(t,e){let r=kc(e);B.isDocument(t)?Ht(null,t.contents,r,Object.freeze([t]))===xe&&(t.contents=null):Ht(null,t,r,Object.freeze([]))}ki.BREAK=X;ki.SKIP=bc;ki.REMOVE=xe;function Ht(t,e,r,i){let n=Sc(t,e,r,i);if(B.isNode(n)||B.isPair(n))return Ec(t,i,n),Ht(t,n,r,i);if(typeof n!="symbol"){if(B.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=Ht(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===xe&&(e.items.splice(a,1),a-=1)}}}else if(B.isPair(e)){i=Object.freeze(i.concat(e));let a=Ht("key",e.key,r,i);if(a===X)return X;a===xe&&(e.key=null);let o=Ht("value",e.value,r,i);if(o===X)return X;o===xe&&(e.value=null)}}return n}async function Si(t,e){let r=kc(e);B.isDocument(t)?await Dt(null,t.contents,r,Object.freeze([t]))===xe&&(t.contents=null):await Dt(null,t,r,Object.freeze([]))}Si.BREAK=X;Si.SKIP=bc;Si.REMOVE=xe;async function Dt(t,e,r,i){let n=await Sc(t,e,r,i);if(B.isNode(n)||B.isPair(n))return Ec(t,i,n),Dt(t,n,r,i);if(typeof n!="symbol"){if(B.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=await Dt(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===xe&&(e.items.splice(a,1),a-=1)}}}else if(B.isPair(e)){i=Object.freeze(i.concat(e));let a=await Dt("key",e.key,r,i);if(a===X)return X;a===xe&&(e.key=null);let o=await Dt("value",e.value,r,i);if(o===X)return X;o===xe&&(e.value=null)}}return n}function kc(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Sc(t,e,r,i){if(typeof r=="function")return r(t,e,i);if(B.isMap(e))return r.Map?.(t,e,i);if(B.isSeq(e))return r.Seq?.(t,e,i);if(B.isPair(e))return r.Pair?.(t,e,i);if(B.isScalar(e))return r.Scalar?.(t,e,i);if(B.isAlias(e))return r.Alias?.(t,e,i)}function Ec(t,e,r){let i=e[e.length-1];if(B.isCollection(i))i.items[t]=r;else if(B.isPair(i))t==="key"?i.key=r:i.value=r;else if(B.isDocument(i))i.contents=r;else{let n=B.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}ba.visit=ki;ba.visitAsync=Si});var ka=k(Cc=>{"use strict";var xc=R(),Dp=vr(),Lp={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bp=t=>t.replace(/[!,[\]{}]/g,e=>Lp[e]),gr=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.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(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=e.match(/^(.*!)([^!]*)$/s);n||r(`The ${e} 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==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,i]of Object.entries(this.tags))if(e.startsWith(i))return r+Bp(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(e&&i.length>0&&xc.isNode(e.contents)){let a={};Dp.visit(e.contents,(o,s)=>{xc.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:"||(!e||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};gr.defaultYaml={explicit:!1,version:"1.2"};gr.defaultTags={"!!":"tag:yaml.org,2002:"};Cc.Directives=gr});var Ei=k(wr=>{"use strict";var Pc=R(),Vp=vr();function Mp(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(r)}return!0}function Rc(t){let e=new Set;return Vp.visit(t,{Value(r,i){i.anchor&&e.add(i.anchor)}}),e}function Ac(t,e){for(let r=1;;++r){let i=`${t}${r}`;if(!e.has(i))return i}}function Fp(t,e){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Rc(t));let o=Ac(e,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Pc.isScalar(o.node)||Pc.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}}wr.anchorIsValid=Mp;wr.anchorNames=Rc;wr.createNodeAnchors=Fp;wr.findNewAnchor=Ac});var Sa=k(_c=>{"use strict";function yr(t,e,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=yr(t,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=yr(t,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=yr(t,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=yr(t,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return t.call(e,r,i)}_c.applyReviver=yr});var qe=k(Tc=>{"use strict";var qp=R();function Ic(t,e,r){if(Array.isArray(t))return t.map((i,n)=>Ic(i,String(n),r));if(t&&typeof t.toJSON=="function"){if(!r||!qp.hasAnchor(t))return t.toJSON(e,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(t,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=t.toJSON(e,r);return r.onCreate&&r.onCreate(n),n}return typeof t=="bigint"&&!r?.keep?Number(t):t}Tc.toJS=Ic});var xi=k($c=>{"use strict";var Wp=Sa(),jc=R(),zp=qe(),Ea=class{constructor(e){Object.defineProperty(this,jc.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!jc.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=zp.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Wp.applyReviver(a,{"":s},"",s):s}};$c.NodeBase=Ea});var Nr=k(Oc=>{"use strict";var Jp=Ei(),Gp=vr(),Lt=R(),Up=xi(),Kp=qe(),xa=class extends Up.NodeBase{constructor(e){super(Lt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Gp.visit(e,{Node:(a,o)=>{(Lt.isAlias(o)||Lt.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(e,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||(Kp.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=Ci(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(e,r,i){let n=`*${this.source}`;if(e){if(Jp.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Ci(t,e,r){if(Lt.isAlias(e)){let i=e.resolve(t),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Lt.isCollection(e)){let i=0;for(let n of e.items){let a=Ci(t,n,r);a>i&&(i=a)}return i}else if(Lt.isPair(e)){let i=Ci(t,e.key,r),n=Ci(t,e.value,r);return Math.max(i,n)}return 1}Oc.Alias=xa});var H=k(Ca=>{"use strict";var Yp=R(),Xp=xi(),Qp=qe(),Zp=t=>!t||typeof t!="function"&&typeof t!="object",We=class extends Xp.NodeBase{constructor(e){super(Yp.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:Qp.toJS(this.value,e,r)}toString(){return String(this.value)}};We.BLOCK_FOLDED="BLOCK_FOLDED";We.BLOCK_LITERAL="BLOCK_LITERAL";We.PLAIN="PLAIN";We.QUOTE_DOUBLE="QUOTE_DOUBLE";We.QUOTE_SINGLE="QUOTE_SINGLE";Ca.Scalar=We;Ca.isScalarValue=Zp});var br=k(Dc=>{"use strict";var eh=Nr(),ht=R(),Hc=H(),th="tag:yaml.org,2002:";function rh(t,e,r){if(e){let i=r.filter(a=>a.tag===e),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return r.find(i=>i.identify?.(t)&&!i.format)}function ih(t,e,r){if(ht.isDocument(t)&&(t=t.contents),ht.isNode(t))return t;if(ht.isPair(t)){let d=r.schema[ht.MAP].createNode?.(r.schema,null,r);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new eh.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=th+e.slice(2));let l=rh(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new Hc.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[ht.MAP]:Symbol.iterator in Object(t)?o[ht.SEQ]:o[ht.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,t,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,t,r):new Hc.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Dc.createNode=ih});var Ri=k(Pi=>{"use strict";var nh=br(),Ce=R(),ah=xi();function Pa(t,e,r){let i=r;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return nh.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Lc=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Ra=class extends ah.NodeBase{constructor(e,r){super(e),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(e){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(i=>Ce.isNode(i)||Ce.isPair(i)?i.clone(e):i),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(Lc(e))this.add(r);else{let[i,...n]=e,a=this.get(i,!0);if(Ce.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Pa(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(e){let[r,...i]=e;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ce.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(e,r){let[i,...n]=e,a=this.get(i,!0);return n.length===0?!r&&Ce.isScalar(a)?a.value:a:Ce.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!Ce.isPair(r))return!1;let i=r.value;return i==null||e&&Ce.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[r,...i]=e;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ce.isCollection(n)?n.hasIn(i):!1}setIn(e,r){let[i,...n]=e;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ce.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Pa(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Pi.Collection=Ra;Pi.collectionFromPath=Pa;Pi.isEmptyPath=Lc});var kr=k(Ai=>{"use strict";var oh=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Aa(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var sh=(t,e,r)=>t.endsWith(`
4
+ var Ep=Object.create;var wa=Object.defineProperty;var xp=Object.getOwnPropertyDescriptor;var Cp=Object.getOwnPropertyNames;var Pp=Object.getPrototypeOf,Rp=Object.prototype.hasOwnProperty;var yi=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var E=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(i){throw r=[i],i}};var k=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},vc=(t,e)=>{for(var r in e)wa(t,r,{get:e[r],enumerable:!0})},Ap=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Cp(e))!Rp.call(t,n)&&n!==r&&wa(t,n,{get:()=>e[n],enumerable:!(i=xp(e,n))||i.enumerable});return t};var mr=(t,e,r)=>(r=t!=null?Ep(Pp(t)):{},Ap(e||!t||!t.__esModule?wa(r,"default",{value:t,enumerable:!0}):r,t));var R=k(W=>{"use strict";var ya=Symbol.for("yaml.alias"),gc=Symbol.for("yaml.document"),Ni=Symbol.for("yaml.map"),wc=Symbol.for("yaml.pair"),Na=Symbol.for("yaml.scalar"),bi=Symbol.for("yaml.seq"),De=Symbol.for("yaml.node.type"),_p=t=>!!t&&typeof t=="object"&&t[De]===ya,Ip=t=>!!t&&typeof t=="object"&&t[De]===gc,Tp=t=>!!t&&typeof t=="object"&&t[De]===Ni,jp=t=>!!t&&typeof t=="object"&&t[De]===wc,yc=t=>!!t&&typeof t=="object"&&t[De]===Na,$p=t=>!!t&&typeof t=="object"&&t[De]===bi;function Nc(t){if(t&&typeof t=="object")switch(t[De]){case Ni:case bi:return!0}return!1}function Op(t){if(t&&typeof t=="object")switch(t[De]){case ya:case Ni:case Na:case bi:return!0}return!1}var Hp=t=>(yc(t)||Nc(t))&&!!t.anchor;W.ALIAS=ya;W.DOC=gc;W.MAP=Ni;W.NODE_TYPE=De;W.PAIR=wc;W.SCALAR=Na;W.SEQ=bi;W.hasAnchor=Hp;W.isAlias=_p;W.isCollection=Nc;W.isDocument=Ip;W.isMap=Tp;W.isNode=Op;W.isPair=jp;W.isScalar=yc;W.isSeq=$p});var vr=k(ba=>{"use strict";var B=R(),X=Symbol("break visit"),bc=Symbol("skip children"),Ce=Symbol("remove node");function ki(t,e){let r=kc(e);B.isDocument(t)?Ht(null,t.contents,r,Object.freeze([t]))===Ce&&(t.contents=null):Ht(null,t,r,Object.freeze([]))}ki.BREAK=X;ki.SKIP=bc;ki.REMOVE=Ce;function Ht(t,e,r,i){let n=Sc(t,e,r,i);if(B.isNode(n)||B.isPair(n))return Ec(t,i,n),Ht(t,n,r,i);if(typeof n!="symbol"){if(B.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=Ht(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Ce&&(e.items.splice(a,1),a-=1)}}}else if(B.isPair(e)){i=Object.freeze(i.concat(e));let a=Ht("key",e.key,r,i);if(a===X)return X;a===Ce&&(e.key=null);let o=Ht("value",e.value,r,i);if(o===X)return X;o===Ce&&(e.value=null)}}return n}async function Si(t,e){let r=kc(e);B.isDocument(t)?await Dt(null,t.contents,r,Object.freeze([t]))===Ce&&(t.contents=null):await Dt(null,t,r,Object.freeze([]))}Si.BREAK=X;Si.SKIP=bc;Si.REMOVE=Ce;async function Dt(t,e,r,i){let n=await Sc(t,e,r,i);if(B.isNode(n)||B.isPair(n))return Ec(t,i,n),Dt(t,n,r,i);if(typeof n!="symbol"){if(B.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=await Dt(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Ce&&(e.items.splice(a,1),a-=1)}}}else if(B.isPair(e)){i=Object.freeze(i.concat(e));let a=await Dt("key",e.key,r,i);if(a===X)return X;a===Ce&&(e.key=null);let o=await Dt("value",e.value,r,i);if(o===X)return X;o===Ce&&(e.value=null)}}return n}function kc(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Sc(t,e,r,i){if(typeof r=="function")return r(t,e,i);if(B.isMap(e))return r.Map?.(t,e,i);if(B.isSeq(e))return r.Seq?.(t,e,i);if(B.isPair(e))return r.Pair?.(t,e,i);if(B.isScalar(e))return r.Scalar?.(t,e,i);if(B.isAlias(e))return r.Alias?.(t,e,i)}function Ec(t,e,r){let i=e[e.length-1];if(B.isCollection(i))i.items[t]=r;else if(B.isPair(i))t==="key"?i.key=r:i.value=r;else if(B.isDocument(i))i.contents=r;else{let n=B.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}ba.visit=ki;ba.visitAsync=Si});var ka=k(Cc=>{"use strict";var xc=R(),Dp=vr(),Lp={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bp=t=>t.replace(/[!,[\]{}]/g,e=>Lp[e]),gr=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.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(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=e.match(/^(.*!)([^!]*)$/s);n||r(`The ${e} 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==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,i]of Object.entries(this.tags))if(e.startsWith(i))return r+Bp(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(e&&i.length>0&&xc.isNode(e.contents)){let a={};Dp.visit(e.contents,(o,s)=>{xc.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:"||(!e||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};gr.defaultYaml={explicit:!1,version:"1.2"};gr.defaultTags={"!!":"tag:yaml.org,2002:"};Cc.Directives=gr});var Ei=k(wr=>{"use strict";var Pc=R(),Vp=vr();function Mp(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(r)}return!0}function Rc(t){let e=new Set;return Vp.visit(t,{Value(r,i){i.anchor&&e.add(i.anchor)}}),e}function Ac(t,e){for(let r=1;;++r){let i=`${t}${r}`;if(!e.has(i))return i}}function Fp(t,e){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Rc(t));let o=Ac(e,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Pc.isScalar(o.node)||Pc.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}}wr.anchorIsValid=Mp;wr.anchorNames=Rc;wr.createNodeAnchors=Fp;wr.findNewAnchor=Ac});var Sa=k(_c=>{"use strict";function yr(t,e,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=yr(t,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=yr(t,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=yr(t,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=yr(t,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return t.call(e,r,i)}_c.applyReviver=yr});var qe=k(Tc=>{"use strict";var qp=R();function Ic(t,e,r){if(Array.isArray(t))return t.map((i,n)=>Ic(i,String(n),r));if(t&&typeof t.toJSON=="function"){if(!r||!qp.hasAnchor(t))return t.toJSON(e,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(t,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=t.toJSON(e,r);return r.onCreate&&r.onCreate(n),n}return typeof t=="bigint"&&!r?.keep?Number(t):t}Tc.toJS=Ic});var xi=k($c=>{"use strict";var Wp=Sa(),jc=R(),zp=qe(),Ea=class{constructor(e){Object.defineProperty(this,jc.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!jc.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=zp.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Wp.applyReviver(a,{"":s},"",s):s}};$c.NodeBase=Ea});var Nr=k(Oc=>{"use strict";var Jp=Ei(),Gp=vr(),Lt=R(),Up=xi(),Kp=qe(),xa=class extends Up.NodeBase{constructor(e){super(Lt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Gp.visit(e,{Node:(a,o)=>{(Lt.isAlias(o)||Lt.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(e,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||(Kp.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=Ci(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(e,r,i){let n=`*${this.source}`;if(e){if(Jp.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Ci(t,e,r){if(Lt.isAlias(e)){let i=e.resolve(t),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Lt.isCollection(e)){let i=0;for(let n of e.items){let a=Ci(t,n,r);a>i&&(i=a)}return i}else if(Lt.isPair(e)){let i=Ci(t,e.key,r),n=Ci(t,e.value,r);return Math.max(i,n)}return 1}Oc.Alias=xa});var H=k(Ca=>{"use strict";var Yp=R(),Xp=xi(),Qp=qe(),Zp=t=>!t||typeof t!="function"&&typeof t!="object",We=class extends Xp.NodeBase{constructor(e){super(Yp.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:Qp.toJS(this.value,e,r)}toString(){return String(this.value)}};We.BLOCK_FOLDED="BLOCK_FOLDED";We.BLOCK_LITERAL="BLOCK_LITERAL";We.PLAIN="PLAIN";We.QUOTE_DOUBLE="QUOTE_DOUBLE";We.QUOTE_SINGLE="QUOTE_SINGLE";Ca.Scalar=We;Ca.isScalarValue=Zp});var br=k(Dc=>{"use strict";var eh=Nr(),ht=R(),Hc=H(),th="tag:yaml.org,2002:";function rh(t,e,r){if(e){let i=r.filter(a=>a.tag===e),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return r.find(i=>i.identify?.(t)&&!i.format)}function ih(t,e,r){if(ht.isDocument(t)&&(t=t.contents),ht.isNode(t))return t;if(ht.isPair(t)){let d=r.schema[ht.MAP].createNode?.(r.schema,null,r);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new eh.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=th+e.slice(2));let l=rh(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new Hc.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[ht.MAP]:Symbol.iterator in Object(t)?o[ht.SEQ]:o[ht.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,t,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,t,r):new Hc.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Dc.createNode=ih});var Ri=k(Pi=>{"use strict";var nh=br(),Pe=R(),ah=xi();function Pa(t,e,r){let i=r;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return nh.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Lc=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Ra=class extends ah.NodeBase{constructor(e,r){super(e),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(e){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(i=>Pe.isNode(i)||Pe.isPair(i)?i.clone(e):i),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(Lc(e))this.add(r);else{let[i,...n]=e,a=this.get(i,!0);if(Pe.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Pa(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(e){let[r,...i]=e;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Pe.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(e,r){let[i,...n]=e,a=this.get(i,!0);return n.length===0?!r&&Pe.isScalar(a)?a.value:a:Pe.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!Pe.isPair(r))return!1;let i=r.value;return i==null||e&&Pe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[r,...i]=e;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Pe.isCollection(n)?n.hasIn(i):!1}setIn(e,r){let[i,...n]=e;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Pe.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Pa(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Pi.Collection=Ra;Pi.collectionFromPath=Pa;Pi.isEmptyPath=Lc});var kr=k(Ai=>{"use strict";var oh=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Aa(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var sh=(t,e,r)=>t.endsWith(`
6
6
  `)?Aa(r,e):r.includes(`
7
7
  `)?`
8
8
  `+Aa(r,e):(t.endsWith(" ")?"":" ")+r;Ai.indentComment=Aa;Ai.lineComment=sh;Ai.stringifyComment=oh});var Vc=k(Sr=>{"use strict";var ch="flow",_a="block",_i="quoted";function lh(t,e,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;n<a&&(a=0);let c=Math.max(1+a,1+n-e.length);if(t.length<=c)return t;let l=[],u={},d=n-e.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let f,h,g=!1,p=-1,v=-1,m=-1;r===_a&&(p=Bc(t,p,e.length),p!==-1&&(d=p+c));for(let N;N=t[p+=1];){if(r===_i&&N==="\\"){switch(v=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}m=p}if(N===`
@@ -11,7 +11,7 @@ var Ep=Object.create;var wa=Object.defineProperty;var xp=Object.getOwnPropertyDe
11
11
  `&&y!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===_i){for(;h===" "||h===" ";)h=N,N=t[p+=1],g=!0;let y=p>m+1?p-2:v-1;if(u[y])return t;l.push(y),u[y]=!0,d=y+c,f=void 0}else g=!0}h=N}if(g&&s&&s(),l.length===0)return t;o&&o();let b=t.slice(0,l[0]);for(let N=0;N<l.length;++N){let y=l[N],x=l[N+1]||t.length;y===0?b=`
12
12
  ${e}${t.slice(0,x)}`:(r===_i&&u[y]&&(b+=`${t[y]}\\`),b+=`
13
13
  ${e}${t.slice(y+1,x)}`)}return b}function Bc(t,e,r){let i=e,n=e+1,a=t[n];for(;a===" "||a===" ";)if(e<n+r)a=t[++e];else{do a=t[++e];while(a&&a!==`
14
- `);i=e,n=e+1,a=t[n]}return i}Sr.FOLD_BLOCK=_a;Sr.FOLD_FLOW=ch;Sr.FOLD_QUOTED=_i;Sr.foldFlowLines=lh});var xr=k(Mc=>{"use strict";var he=H(),ze=Vc(),Ti=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ji=t=>/^(%|---|\.\.\.)/m.test(t);function uh(t,e,r){if(!e||e<0)return!1;let i=e-r,n=t.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
14
+ `);i=e,n=e+1,a=t[n]}return i}Sr.FOLD_BLOCK=_a;Sr.FOLD_FLOW=ch;Sr.FOLD_QUOTED=_i;Sr.foldFlowLines=lh});var xr=k(Mc=>{"use strict";var me=H(),ze=Vc(),Ti=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ji=t=>/^(%|---|\.\.\.)/m.test(t);function uh(t,e,r){if(!e||e<0)return!1;let i=e-r,n=t.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
15
15
  `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Er(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(ji(t)?" ":""),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 u=r.substr(c+2,4);switch(u){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:u.substr(0,2)==="00"?o+="\\x"+u.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,29 +20,29 @@ ${e}${t.slice(y+1,x)}`)}return b}function Bc(t,e,r){let i=e,n=e+1,a=t[n];for(;a=
20
20
  ${r}`)+"'";return e.implicitKey?i:ze.foldFlowLines(i,r,ze.FOLD_FLOW,Ti(e,!1))}function Bt(t,e){let{singleQuote:r}=e.options,i;if(r===!1)i=Er;else{let n=t.includes('"'),a=t.includes("'");n&&!a?i=Ia:a&&!n?i=Er:i=r?Ia:Er}return i(t,e)}var Ta;try{Ta=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Ta=/\n+(?!\n|$)/g}function Ii({comment:t,type:e,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Bt(r,i);let l=i.indent||(i.forceBlockIndent||ji(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===he.Scalar.BLOCK_FOLDED?!1:e===he.Scalar.BLOCK_LITERAL?!0:!uh(r,c,l.length);if(!r)return u?`|
23
+ |$)`,"g")}catch{Ta=/\n+(?!\n|$)/g}function Ii({comment:t,type:e,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Bt(r,i);let l=i.indent||(i.forceBlockIndent||ji(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===me.Scalar.BLOCK_FOLDED?!1:e===me.Scalar.BLOCK_LITERAL?!0:!uh(r,c,l.length);if(!r)return u?`|
24
24
  `:`>
25
25
  `;let d,f;for(f=r.length;f>0;--f){let x=r[f-1];if(x!==`
26
26
  `&&x!==" "&&x!==" ")break}let h=r.substring(f),g=h.indexOf(`
27
27
  `);g===-1?d="-":r===h||g!==h.length-1?(d="+",a&&a()):d="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
28
28
  `&&(h=h.slice(0,-1)),h=h.replace(Ta,`$&${l}`));let p=!1,v,m=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")p=!0;else if(x===`
29
29
  `)m=v;else break}let b=r.substring(0,m<v?m+1:v);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let y=(p?l?"2":"1":"")+d;if(t&&(y+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let x=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,P=Ti(i,!0);o!=="folded"&&e!==he.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{w=!0});let S=ze.foldFlowLines(`${b}${x}${h}`,l,ze.FOLD_BLOCK,P);if(!w)return`>${y}
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,P=Ti(i,!0);o!=="folded"&&e!==me.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{w=!0});let S=ze.foldFlowLines(`${b}${x}${h}`,l,ze.FOLD_BLOCK,P);if(!w)return`>${y}
31
31
  ${l}${S}`}return r=r.replace(/\n+/g,`$&${l}`),`|${y}
32
32
  ${l}${b}${r}${h}`}function dh(t,e,r,i){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=e;if(s&&a.includes(`
33
33
  `)||u&&/[[\]{},]/.test(a))return Bt(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?Bt(a,e):Ii(t,e,r,i);if(!s&&!u&&n!==he.Scalar.PLAIN&&a.includes(`
34
+ `)?Bt(a,e):Ii(t,e,r,i);if(!s&&!u&&n!==me.Scalar.PLAIN&&a.includes(`
35
35
  `))return Ii(t,e,r,i);if(ji(a)){if(c==="")return e.forceBlockIndent=!0,Ii(t,e,r,i);if(s&&c===l)return Bt(a,e)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:g}=e.doc.schema;if(g.some(f)||h?.some(f))return Bt(a,e)}return s?d:ze.foldFlowLines(d,c,ze.FOLD_FLOW,Ti(e,!1))}function fh(t,e,r,i){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==he.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=he.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case he.Scalar.BLOCK_FOLDED:case he.Scalar.BLOCK_LITERAL:return n||a?Bt(o.value,e):Ii(o,e,r,i);case he.Scalar.QUOTE_DOUBLE:return Er(o.value,e);case he.Scalar.QUOTE_SINGLE:return Ia(o.value,e);case he.Scalar.PLAIN:return dh(o,e,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Mc.stringifyString=fh});var Cr=k(ja=>{"use strict";var ph=Ei(),Je=R(),hh=kr(),mh=xr();function vh(t,e){let r=Object.assign({blockQuote:!0,commentString:hh.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},t.schema.toStringOptions,e),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function gh(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let r,i;if(Je.isScalar(e)){i=e.value;let n=t.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===e.format)??n.find(a=>!a.format)}else i=e,r=t.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 wh(t,e,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Je.isScalar(t)||Je.isCollection(t))&&t.anchor;a&&ph.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function yh(t,e,r,i){if(Je.isPair(t))return t.toString(e,r,i);if(Je.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Je.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=gh(e.doc.schema.tags,a));let o=wh(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,r,i):Je.isScalar(a)?mh.stringifyString(a,e,r,i):a.toString(e,r,i);return o?Je.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${e.indent}${s}`:s}ja.createStringifyContext=vh;ja.stringify=yh});var zc=k(Wc=>{"use strict";var De=R(),Fc=H(),qc=Cr(),Pr=kr();function Nh({key:t,value:e},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=De.isNode(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(De.isCollection(t)||!De.isNode(t)&&typeof t=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let h=!d&&(!t||f&&e==null&&!r.inFlow||De.isCollection(t)||(De.isScalar(t)?t.type===Fc.Scalar.BLOCK_FOLDED||t.type===Fc.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let g=!1,p=!1,v=qc.stringify(t,r,()=>g=!0,()=>p=!0);if(!h&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||e==null)return g&&i&&i(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||e==null&&h)return v=`? ${v}`,f&&!g?v+=Pr.lineComment(v,r.indent,l(f)):p&&n&&n(),v;g&&(f=null),h?(f&&(v+=Pr.lineComment(v,r.indent,l(f))),v=`? ${v}
38
- ${s}:`):(v=`${v}:`,f&&(v+=Pr.lineComment(v,r.indent,l(f))));let m,b,N;De.isNode(e)?(m=!!e.spaceBefore,b=e.commentBefore,N=e.comment):(m=!1,b=null,N=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!h&&!f&&De.isScalar(e)&&(r.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!h&&De.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let y=!1,x=qc.stringify(e,r,()=>y=!0,()=>p=!0),w=" ";if(f||m||b){if(w=m?`
36
+ ${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:g}=e.doc.schema;if(g.some(f)||h?.some(f))return Bt(a,e)}return s?d:ze.foldFlowLines(d,c,ze.FOLD_FLOW,Ti(e,!1))}function fh(t,e,r,i){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==me.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=me.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case me.Scalar.BLOCK_FOLDED:case me.Scalar.BLOCK_LITERAL:return n||a?Bt(o.value,e):Ii(o,e,r,i);case me.Scalar.QUOTE_DOUBLE:return Er(o.value,e);case me.Scalar.QUOTE_SINGLE:return Ia(o.value,e);case me.Scalar.PLAIN:return dh(o,e,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Mc.stringifyString=fh});var Cr=k(ja=>{"use strict";var ph=Ei(),Je=R(),hh=kr(),mh=xr();function vh(t,e){let r=Object.assign({blockQuote:!0,commentString:hh.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},t.schema.toStringOptions,e),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function gh(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let r,i;if(Je.isScalar(e)){i=e.value;let n=t.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===e.format)??n.find(a=>!a.format)}else i=e,r=t.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 wh(t,e,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Je.isScalar(t)||Je.isCollection(t))&&t.anchor;a&&ph.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function yh(t,e,r,i){if(Je.isPair(t))return t.toString(e,r,i);if(Je.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Je.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=gh(e.doc.schema.tags,a));let o=wh(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,r,i):Je.isScalar(a)?mh.stringifyString(a,e,r,i):a.toString(e,r,i);return o?Je.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${e.indent}${s}`:s}ja.createStringifyContext=vh;ja.stringify=yh});var zc=k(Wc=>{"use strict";var Le=R(),Fc=H(),qc=Cr(),Pr=kr();function Nh({key:t,value:e},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=Le.isNode(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Le.isCollection(t)||!Le.isNode(t)&&typeof t=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let h=!d&&(!t||f&&e==null&&!r.inFlow||Le.isCollection(t)||(Le.isScalar(t)?t.type===Fc.Scalar.BLOCK_FOLDED||t.type===Fc.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let g=!1,p=!1,v=qc.stringify(t,r,()=>g=!0,()=>p=!0);if(!h&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||e==null)return g&&i&&i(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||e==null&&h)return v=`? ${v}`,f&&!g?v+=Pr.lineComment(v,r.indent,l(f)):p&&n&&n(),v;g&&(f=null),h?(f&&(v+=Pr.lineComment(v,r.indent,l(f))),v=`? ${v}
38
+ ${s}:`):(v=`${v}:`,f&&(v+=Pr.lineComment(v,r.indent,l(f))));let m,b,N;Le.isNode(e)?(m=!!e.spaceBefore,b=e.commentBefore,N=e.comment):(m=!1,b=null,N=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!h&&!f&&Le.isScalar(e)&&(r.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!h&&Le.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let y=!1,x=qc.stringify(e,r,()=>y=!0,()=>p=!0),w=" ";if(f||m||b){if(w=m?`
39
39
  `:"",b){let P=l(b);w+=`
40
40
  ${Pr.indentComment(P,r.indent)}`}x===""&&!r.inFlow?w===`
41
41
  `&&N&&(w=`
42
42
 
43
43
  `):w+=`
44
- ${r.indent}`}else if(!h&&De.isCollection(e)){let P=x[0],S=x.indexOf(`
45
- `),A=S!==-1,G=r.inFlow??e.flow??e.items.length===0;if(A||!G){let pe=!1;if(A&&(P==="&"||P==="!")){let O=x.indexOf(" ");P==="&"&&O!==-1&&O<S&&x[O+1]==="!"&&(O=x.indexOf(" ",O+1)),(O===-1||S<O)&&(pe=!0)}pe||(w=`
44
+ ${r.indent}`}else if(!h&&Le.isCollection(e)){let P=x[0],S=x.indexOf(`
45
+ `),A=S!==-1,G=r.inFlow??e.flow??e.items.length===0;if(A||!G){let he=!1;if(A&&(P==="&"||P==="!")){let O=x.indexOf(" ");P==="&"&&O!==-1&&O<S&&x[O+1]==="!"&&(O=x.indexOf(" ",O+1)),(O===-1||S<O)&&(he=!0)}he||(w=`
46
46
  ${r.indent}`)}}else(x===""||x[0]===`
47
47
  `)&&(w="");return v+=w+x,r.inFlow?y&&i&&i():N&&!y?v+=Pr.lineComment(v,r.indent,l(N)):p&&n&&n(),v}Wc.stringifyPair=Nh});var Oa=k($a=>{"use strict";var Jc=yi("process");function bh(t,...e){t==="debug"&&console.log(...e)}function kh(t,e){(t==="debug"||t==="warn")&&(typeof Jc.emitWarning=="function"?Jc.emitWarning(e):console.warn(e))}$a.debug=bh;$a.warn=kh});var Li=k(Di=>{"use strict";var Hi=R(),Gc=H(),$i="<<",Oi={identify:t=>t===$i||typeof t=="symbol"&&t.description===$i,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Gc.Scalar(Symbol($i)),{addToJSMap:Uc}),stringify:()=>$i},Sh=(t,e)=>(Oi.identify(e)||Hi.isScalar(e)&&(!e.type||e.type===Gc.Scalar.PLAIN)&&Oi.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===Oi.tag&&r.default);function Uc(t,e,r){let i=Kc(t,r);if(Hi.isSeq(i))for(let n of i.items)Ha(t,e,n);else if(Array.isArray(i))for(let n of i)Ha(t,e,n);else Ha(t,e,i)}function Ha(t,e,r){let i=Kc(t,r);if(!Hi.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Kc(t,e){return t&&Hi.isAlias(e)?e.resolve(t.doc,t):e}Di.addMergeToJSMap=Uc;Di.isMergeKey=Sh;Di.merge=Oi});var La=k(Qc=>{"use strict";var Eh=Oa(),Yc=Li(),xh=Cr(),Xc=R(),Da=qe();function Ch(t,e,{key:r,value:i}){if(Xc.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,i);else if(Yc.isMergeKey(t,r))Yc.addMergeToJSMap(t,e,i);else{let n=Da.toJS(r,"",t);if(e instanceof Map)e.set(n,Da.toJS(i,n,t));else if(e instanceof Set)e.add(n);else{let a=Ph(r,n,t),o=Da.toJS(i,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function Ph(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(Xc.isNode(t)&&r?.doc){let i=xh.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=t.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),Eh.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(e)}Qc.addPairToJSMap=Ch});var Ge=k(Ba=>{"use strict";var Zc=br(),Rh=zc(),Ah=La(),Bi=R();function _h(t,e,r){let i=Zc.createNode(t,void 0,r),n=Zc.createNode(e,void 0,r);return new Vi(i,n)}var Vi=class t{constructor(e,r=null){Object.defineProperty(this,Bi.NODE_TYPE,{value:Bi.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:i}=this;return Bi.isNode(r)&&(r=r.clone(e)),Bi.isNode(i)&&(i=i.clone(e)),new t(r,i)}toJSON(e,r){let i=r?.mapAsMap?new Map:{};return Ah.addPairToJSMap(r,i,this)}toString(e,r,i){return e?.doc?Rh.stringifyPair(this,e,r,i):JSON.stringify(this)}};Ba.Pair=Vi;Ba.createPair=_h});var Va=k(tl=>{"use strict";var mt=R(),el=Cr(),Mi=kr();function Ih(t,e,r){return(e.inFlow??t.flow?jh:Th)(t,e,r)}function Th({comment:t,items:e},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let g=0;g<e.length;++g){let p=e[g],v=null;if(mt.isNode(p))!d&&p.spaceBefore&&f.push(""),Fi(r,f,p.commentBefore,d),p.comment&&(v=p.comment);else if(mt.isPair(p)){let b=mt.isNode(p.key)?p.key:null;b&&(!d&&b.spaceBefore&&f.push(""),Fi(r,f,b.commentBefore,d))}d=!1;let m=el.stringify(p,u,()=>v=null,()=>d=!0);v&&(m+=Mi.lineComment(m,a,l(v))),d&&v&&(d=!1),f.push(i+m)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let g=1;g<f.length;++g){let p=f[g];h+=p?`
48
48
  ${c}${p}`:`
@@ -68,7 +68,7 @@ ${l}
68
68
  `+N.comment:b.comment=N.comment);let y=new nu.Pair(b);r.options.keepSourceTokens&&(y.srcToken=u),s.items.push(y)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}cu.resolveBlockMap=yv});var du=k(uu=>{"use strict";var Nv=Ye(),bv=Vr(),kv=Co();function Sv({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??Nv.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let f=bv.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?t(r,d,f,n):e(r,f.end,u,null,f,n);r.schema.compat&&kv.flowIndentCheck(i.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[i.offset,c,l??c],s}uu.resolveBlockSeq=Sv});var zt=k(fu=>{"use strict";function Ev(t,e,r,i){let n="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}fu.resolveEnd=Ev});var vu=k(mu=>{"use strict";var xv=R(),Cv=Ge(),pu=Ke(),Pv=Ye(),Rv=zt(),hu=Vr(),Av=un(),_v=Po(),Ro="Block collections are not allowed within flow collections",Ao=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Iv({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?pu.YAMLMap:Pv.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let m=i.items[v],{start:b,key:N,sep:y,value:x}=m,w=hu.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:N??y?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!y&&!x){v===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(l.comment?l.comment+=`
69
69
  `+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&Av.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)w.comma&&n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(w.comma||n(w.start,"MISSING_CHAR",`Missing , between ${s} items`),w.comment){let P="";e:for(let S of b)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];xv.isPair(S)&&(S=S.value??S.key),S.comment?S.comment+=`
70
70
  `+P:S.comment=P,w.comment=w.comment.substring(P.length+1)}}if(!o&&!y&&!w.found){let P=x?t(r,x,w,n):e(r,w.end,y,null,w,n);l.items.push(P),d=P.range[2],Ao(x)&&n(P.range,"BLOCK_IN_FLOW",Ro)}else{r.atKey=!0;let P=w.end,S=N?t(r,N,w,n):e(r,P,b,null,w,n);Ao(N)&&n(S.range,"BLOCK_IN_FLOW",Ro),r.atKey=!1;let A=hu.resolveProps(y??[],{flow:s,indicator:"map-value-ind",next:x,offset:S.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(A.found){if(!o&&!w.found&&r.options.strict){if(y)for(let O of y){if(O===A.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<A.found.offset-1024&&n(A.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(A.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let G=x?t(r,x,A,n):A.found?e(r,A.end,y,null,A,n):null;G?Ao(x)&&n(G.range,"BLOCK_IN_FLOW",Ro):A.comment&&(S.comment?S.comment+=`
71
- `+A.comment:S.comment=A.comment);let pe=new Cv.Pair(S,G);if(r.options.keepSourceTokens&&(pe.srcToken=m),o){let O=l;_v.mapIncludes(r,O.items,S)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(pe)}else{let O=new pu.YAMLMap(r.schema);O.flow=!0,O.items.push(pe);let hr=(G??S).range;O.range=[S.range[0],hr[1],hr[2]],l.items.push(O)}d=G?G.range[2]:A.end}}let f=o?"}":"]",[h,...g]=i.end,p=d;if(h?.source===f)p=h.offset+h.source.length;else{let v=s[0].toUpperCase()+s.substring(1),m=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",m),h&&h.source.length!==1&&g.unshift(h)}if(g.length>0){let v=Rv.resolveEnd(g,p,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
71
+ `+A.comment:S.comment=A.comment);let he=new Cv.Pair(S,G);if(r.options.keepSourceTokens&&(he.srcToken=m),o){let O=l;_v.mapIncludes(r,O.items,S)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(he)}else{let O=new pu.YAMLMap(r.schema);O.flow=!0,O.items.push(he);let hr=(G??S).range;O.range=[S.range[0],hr[1],hr[2]],l.items.push(O)}d=G?G.range[2]:A.end}}let f=o?"}":"]",[h,...g]=i.end,p=d;if(h?.source===f)p=h.offset+h.source.length;else{let v=s[0].toUpperCase()+s.substring(1),m=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",m),h&&h.source.length!==1&&g.unshift(h)}if(g.length>0){let v=Rv.resolveEnd(g,p,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
72
72
  `+v.comment:l.comment=v.comment),l.range=[i.offset,p,v.offset]}else l.range=[i.offset,p,p];return l}mu.resolveFlowCollection=Iv});var wu=k(gu=>{"use strict";var Tv=R(),jv=H(),$v=Ke(),Ov=Ye(),Hv=lu(),Dv=du(),Lv=vu();function _o(t,e,r,i,n,a){let o=r.type==="block-map"?Hv.resolveBlockMap(t,e,r,i,a):r.type==="block-seq"?Dv.resolveBlockSeq(t,e,r,i,a):Lv.resolveFlowCollection(t,e,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Bv(t,e,r,i,n){let a=i.tag,o=a?e.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=i,g=f&&a?f.offset>a.offset?f:a:f??a;g&&(!h||h.offset<g.offset)&&n(g,"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===$v.YAMLMap.tagName&&s==="map"||o===Ov.YAMLSeq.tagName&&s==="seq")return _o(t,e,r,n,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=e.schema.knownTags[o];if(f?.collection===s)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),_o(t,e,r,n,o)}let l=_o(t,e,r,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),e.options)??l,d=Tv.isNode(u)?u:new jv.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}gu.composeCollection=Bv});var To=k(yu=>{"use strict";var Io=H();function Vv(t,e,r){let i=e.offset,n=Mv(e,t.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Io.Scalar.BLOCK_FOLDED:Io.Scalar.BLOCK_LITERAL,o=e.source?Fv(e.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let v=o[p][1];if(v===""||v==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return e.source&&(v+=e.source.length),{value:p,type:a,comment:n.comment,range:[i,v,v]}}let c=e.indent+n.indent,l=e.offset+n.length,u=0;for(let p=0;p<s;++p){let[v,m]=o[p];if(m===""||m==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=p,c===0&&!t.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+m.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let d="",f="",h=!1;for(let p=0;p<u;++p)d+=o[p][0].slice(c)+`
74
74
  `;for(let p=u;p<s;++p){let[v,m]=o[p];l+=v.length+m.length+1;let b=m[m.length-1]==="\r";if(b&&(m=m.slice(0,-1)),m&&v.length<c){let y=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-m.length-(b?2:1),"BAD_INDENT",y),v=""}a===Io.Scalar.BLOCK_LITERAL?(d+=f+v.slice(c)+m,f=`
@@ -116,41 +116,41 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
116
116
  `});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function Du(t,e){if(e)for(let r of e)switch(r.type){case"space":case"comment":t.push(r);break;case"newline":return t.push(r),!0}return!1}function Bo(t,e,r){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=r,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let a of i)a.offset+=n;delete t.props,Object.assign(t,{type:r,source:e,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
117
117
  `};delete t.items,Object.assign(t,{type:r,source:e,end:[n]});break}default:{let i="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:r,indent:i,source:e,end:n})}}}dn.createScalarToken=Sg;dn.resolveAsScalar=kg;dn.setScalarValue=Eg});var Vu=k(Bu=>{"use strict";var Cg=t=>"type"in t?pn(t):fn(t);function pn(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=pn(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=fn(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=fn(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=fn(t);if(t.end)for(let r of t.end)e+=r.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let r of t.end)e+=r.source;return e}}}function fn({start:t,key:e,sep:r,value:i}){let n="";for(let a of t)n+=a.source;if(e&&(n+=pn(e)),r)for(let a of r)n+=a.source;return i&&(n+=pn(i)),n}Bu.stringify=Cg});var Wu=k(qu=>{"use strict";var Vo=Symbol("break visit"),Pg=Symbol("skip children"),Mu=Symbol("remove item");function yt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Fu(Object.freeze([]),t,e)}yt.BREAK=Vo;yt.SKIP=Pg;yt.REMOVE=Mu;yt.itemAtPath=(t,e)=>{let r=t;for(let[i,n]of e){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};yt.parentCollection=(t,e)=>{let r=yt.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Fu(t,e,r){let i=r(e,t);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Fu(Object.freeze(t.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Vo)return Vo;s===Mu&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(e,t))}}return typeof i=="function"?i(e,t):i}qu.visit=yt});var hn=k(Q=>{"use strict";var Mo=Lu(),Rg=Vu(),Ag=Wu(),Fo="\uFEFF",qo="",Wo="",zo="",_g=t=>!!t&&"items"in t,Ig=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Tg(t){switch(t){case Fo:return"<BOM>";case qo:return"<DOC>";case Wo:return"<FLOW_END>";case zo:return"<SCALAR>";default:return JSON.stringify(t)}}function jg(t){switch(t){case Fo:return"byte-order-mark";case qo:return"doc-mode";case Wo:return"flow-error-end";case zo: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(t[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}Q.createScalarToken=Mo.createScalarToken;Q.resolveAsScalar=Mo.resolveAsScalar;Q.setScalarValue=Mo.setScalarValue;Q.stringify=Rg.stringify;Q.visit=Ag.visit;Q.BOM=Fo;Q.DOCUMENT=qo;Q.FLOW_END=Wo;Q.SCALAR=zo;Q.isCollection=_g;Q.isScalar=Ig;Q.prettyToken=Tg;Q.tokenType=jg});var Uo=k(Ju=>{"use strict";var qr=hn();function me(t){switch(t){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(t[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}Q.createScalarToken=Mo.createScalarToken;Q.resolveAsScalar=Mo.resolveAsScalar;Q.setScalarValue=Mo.setScalarValue;Q.stringify=Rg.stringify;Q.visit=Ag.visit;Q.BOM=Fo;Q.DOCUMENT=qo;Q.FLOW_END=Wo;Q.SCALAR=zo;Q.isCollection=_g;Q.isScalar=Ig;Q.prettyToken=Tg;Q.tokenType=jg});var Uo=k(Ju=>{"use strict";var qr=hn();function ve(t){switch(t){case void 0:case" ":case`
120
120
  `:case"\r":case" ":return!0;default:return!1}}var zu=new Set("0123456789ABCDEFabcdef"),$g=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),mn=new Set(",[]{}"),Og=new Set(` ,[]{}
121
121
  \r `),Jo=t=>!t||Og.has(t),Go=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(e,r=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,r=this.buffer[e];for(;r===" "||r===" ";)r=this.buffer[++e];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[e+1]===`
123
123
  `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let r=this.buffer[e];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+e];if(r==="\r"){let n=this.buffer[i+e+1];if(n===`
124
124
  `||!n&&!this.atEnd)return e+i+1}return r===`
125
- `||i>=this.indentNext||!r&&!this.atEnd?e+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&me(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===qr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let r=e.length,i=e.indexOf("#");for(;i!==-1;){let a=e[i-1];if(a===" "||a===" "){r=i-1;break}else i=e.indexOf("#",i+1)}for(;;){let a=e[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-r),yield*this.pushNewline(),"stream"}return yield qr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&me(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&&!me(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&me(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 e=this.getLine();if(e===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(e[r]){case"#":yield*this.pushCount(e.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(Jo),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,r,i=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(e+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("..."))&&me(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield qr.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(Jo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||me(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 e=this.charAt(0),r=this.buffer.indexOf(e,this.pos+1);if(e==="'")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?e+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&ve(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===qr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let r=e.length,i=e.indexOf("#");for(;i!==-1;){let a=e[i-1];if(a===" "||a===" "){r=i-1;break}else i=e.indexOf("#",i+1)}for(;;){let a=e[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-r),yield*this.pushNewline(),"stream"}return yield qr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&ve(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&&!ve(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ve(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 e=this.getLine();if(e===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(e[r]){case"#":yield*this.pushCount(e.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(Jo),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,r,i=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(e+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("..."))&&ve(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield qr.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(Jo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ve(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 e=this.charAt(0),r=this.buffer.indexOf(e,this.pos+1);if(e==="'")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 e=this.pos;for(;;){let r=this.buffer[++e];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=>me(r)||r==="#")}*parseBlockScalar(){let e=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 e=this.pos;for(;;){let r=this.buffer[++e];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=>ve(r)||r==="#")}*parseBlockScalar(){let e=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
  `:e=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(e+1);if(a===-1)break;e=this.buffer.indexOf(`
131
131
  `,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+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];e=n-1}else if(!this.blockScalarKeep)do{let a=e-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)e=a;else break}while(!0);return yield qr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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(me(a)||e&&mn.has(a))break;r=i}else if(me(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)e=a;else break}while(!0);return yield qr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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(ve(a)||e&&mn.has(a))break;r=i}else if(ve(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==="#"||e&&mn.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&mn.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield qr.SCALAR,yield*this.pushToIndex(r+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,r){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Jo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(me(i)||r&&mn.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,r=this.buffer[e];for(;!me(r)&&r!==">";)r=this.buffer[++e];return yield*this.pushToIndex(r===">"?e+1:e,!1)}else{let e=this.pos+1,r=this.buffer[e];for(;r;)if($g.has(r))r=this.buffer[++e];else if(r==="%"&&zu.has(this.buffer[e+1])&&zu.has(this.buffer[e+2]))r=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&mn.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield qr.SCALAR,yield*this.pushToIndex(r+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,r){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Jo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ve(i)||r&&mn.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,r=this.buffer[e];for(;!ve(r)&&r!==">";)r=this.buffer[++e];return yield*this.pushToIndex(r===">"?e+1:e,!1)}else{let e=this.pos+1,r=this.buffer[e];for(;r;)if($g.has(r))r=this.buffer[++e];else if(r==="%"&&zu.has(this.buffer[e+1])&&zu.has(this.buffer[e+2]))r=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
137
137
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
138
138
  `?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||e&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(e){let r=this.pos,i=this.buffer[r];for(;!e(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Ju.Lexer=Go});var Yo=k(Gu=>{"use strict";var Ko=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<e?r=a+1:i=a}if(this.lineStarts[r]===e)return{line:r+1,col:1};if(r===0)return{line:0,col:e};let n=this.lineStarts[r-1];return{line:r,col:e-n+1}}}};Gu.LineCounter=Ko});var Qo=k(Qu=>{"use strict";var Hg=yi("process"),Uu=hn(),Dg=Uo();function Xe(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function Ku(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Xu(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function vn(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function Jt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function gn(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let r=0;r<e.length;++r)t.push(e[r])}function Yu(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Xe(e.start,"explicit-key-ind")&&!Xe(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Xu(e.value)?e.value.end?gn(e.value.end,e.sep):e.value.end=e.sep:gn(e.start,e.sep),delete e.sep)}var Xo=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Dg.Lexer,this.onNewLine=e}*parse(e,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(e,r))yield*this.next(i);r||(yield*this.end())}*next(e){if(this.source=e,Hg.env.LOG_TOKENS&&console.log("|",Uu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=Uu.tokenType(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let i=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:e}),this.offset+=e.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 e=this.peek(1);if(this.type==="doc-end"&&e?.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(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let r=e??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"&&Yu(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&&Ku(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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Ku(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let r=vn(this.peek(2)),i=Jt(r),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.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(e){let r=e.items[e.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):e.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)e.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){gn(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.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>e.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),e.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),e.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)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Xe(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(Xu(r.key)&&!Xe(r.sep,"newline")){let o=Jt(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(Xe(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Jt(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?e.items.push({start:a,key:null,sep:[this.sourceToken]}):Xe(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?(e.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(e);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Xe(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&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let r=e.items[e.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):e.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){gn(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=e.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;r.value||Xe(r.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let r=e.items[e.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(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?e.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?e.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?e.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":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);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===e.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=vn(i),a=Jt(n);Yu(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){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:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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=vn(e),i=Jt(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=vn(e),i=Jt(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Qu.Parser=Xo});var id=k(zr=>{"use strict";var Zu=Lo(),Lg=Hr(),Wr=Br(),Bg=Oa(),Vg=R(),Mg=Yo(),ed=Qo();function td(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Mg.LineCounter||null,prettyErrors:e}}function Fg(t,e={}){let{lineCounter:r,prettyErrors:i}=td(e),n=new ed.Parser(r?.addNewLine),a=new Zu.Composer(e),o=Array.from(a.compose(n.parse(t)));if(i&&r)for(let s of o)s.errors.forEach(Wr.prettifyError(t,r)),s.warnings.forEach(Wr.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function rd(t,e={}){let{lineCounter:r,prettyErrors:i}=td(e),n=new ed.Parser(r?.addNewLine),a=new Zu.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Wr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Wr.prettifyError(t,r)),o.warnings.forEach(Wr.prettifyError(t,r))),o}function qg(t,e,r){let i;typeof e=="function"?i=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=rd(t,r);if(!n)return null;if(n.warnings.forEach(a=>Bg.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 Wg(t,e,r){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:r===void 0&&e&&(r=e),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(t===void 0){let{keepUndefined:n}=r??e??{};if(!n)return}return Vg.isDocument(t)&&!i?t.toString(r):new Lg.Document(t,i,r).toString(r)}zr.parse=qg;zr.parseAllDocuments=Fg;zr.parseDocument=rd;zr.stringify=Wg});var Gt=k(_=>{"use strict";var zg=Lo(),Jg=Hr(),Gg=wo(),Zo=Br(),Ug=Nr(),Qe=R(),Kg=Ge(),Yg=H(),Xg=Ke(),Qg=Ye(),Zg=hn(),ew=Uo(),tw=Yo(),rw=Qo(),wn=id(),nd=vr();_.Composer=zg.Composer;_.Document=Jg.Document;_.Schema=Gg.Schema;_.YAMLError=Zo.YAMLError;_.YAMLParseError=Zo.YAMLParseError;_.YAMLWarning=Zo.YAMLWarning;_.Alias=Ug.Alias;_.isAlias=Qe.isAlias;_.isCollection=Qe.isCollection;_.isDocument=Qe.isDocument;_.isMap=Qe.isMap;_.isNode=Qe.isNode;_.isPair=Qe.isPair;_.isScalar=Qe.isScalar;_.isSeq=Qe.isSeq;_.Pair=Kg.Pair;_.Scalar=Yg.Scalar;_.YAMLMap=Xg.YAMLMap;_.YAMLSeq=Qg.YAMLSeq;_.CST=Zg;_.Lexer=ew.Lexer;_.LineCounter=tw.LineCounter;_.Parser=rw.Parser;_.parse=wn.parse;_.parseAllDocuments=wn.parseAllDocuments;_.parseDocument=wn.parseDocument;_.stringify=wn.stringify;_.visit=nd.visit;_.visitAsync=nd.visitAsync});import{execFileSync as iw}from"child_process";import Jr from"path";function Ut(t,e){return iw("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function nw(t,e){let r=Jr.normalize(t),i=Jr.normalize(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Pe(t){try{let e=Jr.resolve(Ut(t,["rev-parse","--show-toplevel"])),i=Ut(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Jr.resolve(i.slice(9)):e,a=null;try{a=Ut(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!nw(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ad(t){try{Ut(t,["rev-parse","--is-inside-work-tree"]);let e=Ut(t,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of e)n.startsWith("worktree ")?(i&&r.push(i),i={root:Jr.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 Kt(t){return ad(t).map(e=>e.root)}function Gr(t,e){try{let r=Ut(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Ze=E(()=>{"use strict"});function sw(t){return t.toLowerCase().startsWith(".env")}function Ur(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>sw(i))?"environment-file":r.some(i=>ow.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>aw.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var aw,ow,Kr=E(()=>{"use strict";aw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ow=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function et(t){return t!==0&&t!==0n&&t!=="0"}function Le(t,e){return et(t.dev)&&et(e.dev)&&et(t.ino)&&et(e.ino)}function j(t,e){let r=et(t.dev)&&et(e.dev);if(r&&t.dev!==e.dev)return!1;let i=et(t.ino)&&et(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var Yr=E(()=>{"use strict"});var Re=E(()=>{"use strict";Yr()});import{createHash as cw}from"node:crypto";import{promises as ve}from"node:fs";import ne from"node:path";import{TextDecoder as lw}from"node:util";function es(t,e){let r=ne.relative(t,e);return r===""||!ne.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ne.sep}`)}function uw(t){let e=ne.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ne.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let r=t.toLowerCase(),i=Ur(t);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${t}`);return t}function dw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function fw(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function yn(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return Le(r,i)?j(r,i):j(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function od(t){let e=await ve.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ve.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function pw(t,e){let r=ne.resolve(t),i=ne.resolve(e);if(!es(r,i))throw new Error("Native artifact path is outside its root");let n=[await od(r)],a=r;for(let o of ne.relative(r,i).split(ne.sep).filter(Boolean)){a=ne.join(a,o);let s=await od(a);if(!es(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function sd(t){for(let e of t){let r=await ve.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!fw(e,r)||await ve.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=uw(t.ref),r=t.maxBytes===null?null:dw(t.maxBytes??Nn),i=ne.resolve(t.root,...e.split("/")),n=await pw(t.root,ne.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await ve.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);let o=await ve.realpath(i);if(!es(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ve.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ve.lstat(i),ve.realpath(i)]);if(await sd(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!yn(a,c)||!yn(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?h.length:r+1-f,y=await s.read(h,0,Math.min(h.length,N),null);if(y.bytesRead===0)break;if(f+=y.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);d.push(Buffer.from(h.subarray(0,y.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[g,p,v]=await Promise.all([s.stat(),ve.lstat(i),ve.realpath(i)]);if(await sd(n),!p.isFile()||p.isSymbolicLink()||v!==o||!yn(c,g)||!yn(c,p))throw new Error(`Native artifact changed while reading: ${e}`);let m=Buffer.concat(d,f),b;try{b=new lw("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:N})}return{ref:e,size:f,hash:t.includeHash===!1?null:cw("sha256").update(m).digest("hex"),text:b}}finally{await s.close()}}var Nn,ae=E(()=>{"use strict";Kr();Re();Nn=1024*1024});import{randomUUID as hw}from"crypto";import{promises as F}from"fs";import ge from"path";function bn(t,e){let r=ge.relative(t,e);return r===""||!ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ge.sep}`)}function mw(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function kn(t,e){return j({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function vw(t,e){return kn(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function cd(t){let e=await F.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await F.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Yt(t){for(let e of t){let r=await F.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!mw(e,r)||await F.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function gw(t,e,r){let[i,n]=await Promise.all([F.lstat(t),F.realpath(t),r?Yt(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!kn(i,e)||r&&!bn(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function ww(t,e){let r=ge.resolve(t),i=ge.resolve(e);if(!bn(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await cd(r)],a=ge.relative(r,i).split(ge.sep).filter(Boolean),o=r;for(let s of a){await Yt(n),o=ge.join(o,s);try{await F.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await cd(o);if(!bn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Yt(n),n}async function yw(t){let e;try{e=await F.open(t,"r"),await e.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await e?.close()}}async function Nw(t,e,r={}){let i=ge.dirname(t),n=r.containedRoot?await ww(r.containedRoot,i):null;n||await F.mkdir(i,{recursive:!0});let a=ge.join(i,`.${ge.basename(t)}.${hw()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await F.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([F.lstat(a),F.realpath(a)]);if(await Yt(n),!l.isFile()||l.isSymbolicLink()||!kn(s,l)||!bn(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!kn(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 gw(a,c,n),await r.beforeCommit?.(),n){await Yt(n);let l=await F.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!vw(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await F.link(a,t),await F.unlink(a)):await F.rename(a,t),await yw(i)}catch(l){if(await o?.close(),!n)await F.rm(a,{force:!0});else try{await Yt(n),await F.rm(a,{force:!0})}catch{}throw l}}async function Ae(t,e,r={}){await Nw(t,e,r)}async function oe(t,e,r={}){await Ae(t,JSON.stringify(e,null,2)+`
143
- `,r)}var D=E(()=>{"use strict";Re()});function Ew(t,e){return ts[t][e]}function Sn(t){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ew(t,r)}
142
+ `,r)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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=vn(e),i=Jt(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=vn(e),i=Jt(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Qu.Parser=Xo});var id=k(zr=>{"use strict";var Zu=Lo(),Lg=Hr(),Wr=Br(),Bg=Oa(),Vg=R(),Mg=Yo(),ed=Qo();function td(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Mg.LineCounter||null,prettyErrors:e}}function Fg(t,e={}){let{lineCounter:r,prettyErrors:i}=td(e),n=new ed.Parser(r?.addNewLine),a=new Zu.Composer(e),o=Array.from(a.compose(n.parse(t)));if(i&&r)for(let s of o)s.errors.forEach(Wr.prettifyError(t,r)),s.warnings.forEach(Wr.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function rd(t,e={}){let{lineCounter:r,prettyErrors:i}=td(e),n=new ed.Parser(r?.addNewLine),a=new Zu.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Wr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Wr.prettifyError(t,r)),o.warnings.forEach(Wr.prettifyError(t,r))),o}function qg(t,e,r){let i;typeof e=="function"?i=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=rd(t,r);if(!n)return null;if(n.warnings.forEach(a=>Bg.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 Wg(t,e,r){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:r===void 0&&e&&(r=e),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(t===void 0){let{keepUndefined:n}=r??e??{};if(!n)return}return Vg.isDocument(t)&&!i?t.toString(r):new Lg.Document(t,i,r).toString(r)}zr.parse=qg;zr.parseAllDocuments=Fg;zr.parseDocument=rd;zr.stringify=Wg});var Gt=k(_=>{"use strict";var zg=Lo(),Jg=Hr(),Gg=wo(),Zo=Br(),Ug=Nr(),Qe=R(),Kg=Ge(),Yg=H(),Xg=Ke(),Qg=Ye(),Zg=hn(),ew=Uo(),tw=Yo(),rw=Qo(),wn=id(),nd=vr();_.Composer=zg.Composer;_.Document=Jg.Document;_.Schema=Gg.Schema;_.YAMLError=Zo.YAMLError;_.YAMLParseError=Zo.YAMLParseError;_.YAMLWarning=Zo.YAMLWarning;_.Alias=Ug.Alias;_.isAlias=Qe.isAlias;_.isCollection=Qe.isCollection;_.isDocument=Qe.isDocument;_.isMap=Qe.isMap;_.isNode=Qe.isNode;_.isPair=Qe.isPair;_.isScalar=Qe.isScalar;_.isSeq=Qe.isSeq;_.Pair=Kg.Pair;_.Scalar=Yg.Scalar;_.YAMLMap=Xg.YAMLMap;_.YAMLSeq=Qg.YAMLSeq;_.CST=Zg;_.Lexer=ew.Lexer;_.LineCounter=tw.LineCounter;_.Parser=rw.Parser;_.parse=wn.parse;_.parseAllDocuments=wn.parseAllDocuments;_.parseDocument=wn.parseDocument;_.stringify=wn.stringify;_.visit=nd.visit;_.visitAsync=nd.visitAsync});import{execFileSync as iw}from"child_process";import Jr from"path";function Ut(t,e){return iw("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function nw(t,e){let r=Jr.normalize(t),i=Jr.normalize(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Re(t){try{let e=Jr.resolve(Ut(t,["rev-parse","--show-toplevel"])),i=Ut(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Jr.resolve(i.slice(9)):e,a=null;try{a=Ut(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!nw(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ad(t){try{Ut(t,["rev-parse","--is-inside-work-tree"]);let e=Ut(t,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of e)n.startsWith("worktree ")?(i&&r.push(i),i={root:Jr.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 Kt(t){return ad(t).map(e=>e.root)}function Gr(t,e){try{let r=Ut(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Ze=E(()=>{"use strict"});function sw(t){return t.toLowerCase().startsWith(".env")}function Ur(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>sw(i))?"environment-file":r.some(i=>ow.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>aw.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var aw,ow,Kr=E(()=>{"use strict";aw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ow=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function et(t){return t!==0&&t!==0n&&t!=="0"}function Be(t,e){return et(t.dev)&&et(e.dev)&&et(t.ino)&&et(e.ino)}function j(t,e){let r=et(t.dev)&&et(e.dev);if(r&&t.dev!==e.dev)return!1;let i=et(t.ino)&&et(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var Yr=E(()=>{"use strict"});var Ae=E(()=>{"use strict";Yr()});import{createHash as cw}from"node:crypto";import{promises as ge}from"node:fs";import ne from"node:path";import{TextDecoder as lw}from"node:util";function es(t,e){let r=ne.relative(t,e);return r===""||!ne.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ne.sep}`)}function uw(t){let e=ne.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ne.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let r=t.toLowerCase(),i=Ur(t);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${t}`);return t}function dw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function fw(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function yn(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return Be(r,i)?j(r,i):j(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function od(t){let e=await ge.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ge.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function pw(t,e){let r=ne.resolve(t),i=ne.resolve(e);if(!es(r,i))throw new Error("Native artifact path is outside its root");let n=[await od(r)],a=r;for(let o of ne.relative(r,i).split(ne.sep).filter(Boolean)){a=ne.join(a,o);let s=await od(a);if(!es(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function sd(t){for(let e of t){let r=await ge.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!fw(e,r)||await ge.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=uw(t.ref),r=t.maxBytes===null?null:dw(t.maxBytes??Nn),i=ne.resolve(t.root,...e.split("/")),n=await pw(t.root,ne.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await ge.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);let o=await ge.realpath(i);if(!es(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ge.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ge.lstat(i),ge.realpath(i)]);if(await sd(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!yn(a,c)||!yn(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?h.length:r+1-f,y=await s.read(h,0,Math.min(h.length,N),null);if(y.bytesRead===0)break;if(f+=y.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);d.push(Buffer.from(h.subarray(0,y.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[g,p,v]=await Promise.all([s.stat(),ge.lstat(i),ge.realpath(i)]);if(await sd(n),!p.isFile()||p.isSymbolicLink()||v!==o||!yn(c,g)||!yn(c,p))throw new Error(`Native artifact changed while reading: ${e}`);let m=Buffer.concat(d,f),b;try{b=new lw("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:N})}return{ref:e,size:f,hash:t.includeHash===!1?null:cw("sha256").update(m).digest("hex"),text:b}}finally{await s.close()}}var Nn,ae=E(()=>{"use strict";Kr();Ae();Nn=1024*1024});import{randomUUID as hw}from"crypto";import{promises as F}from"fs";import we from"path";function bn(t,e){let r=we.relative(t,e);return r===""||!we.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${we.sep}`)}function mw(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function kn(t,e){return j({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function vw(t,e){return kn(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function cd(t){let e=await F.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await F.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Yt(t){for(let e of t){let r=await F.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!mw(e,r)||await F.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function gw(t,e,r){let[i,n]=await Promise.all([F.lstat(t),F.realpath(t),r?Yt(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!kn(i,e)||r&&!bn(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function ww(t,e){let r=we.resolve(t),i=we.resolve(e);if(!bn(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await cd(r)],a=we.relative(r,i).split(we.sep).filter(Boolean),o=r;for(let s of a){await Yt(n),o=we.join(o,s);try{await F.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await cd(o);if(!bn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Yt(n),n}async function yw(t){let e;try{e=await F.open(t,"r"),await e.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await e?.close()}}async function Nw(t,e,r={}){let i=we.dirname(t),n=r.containedRoot?await ww(r.containedRoot,i):null;n||await F.mkdir(i,{recursive:!0});let a=we.join(i,`.${we.basename(t)}.${hw()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await F.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([F.lstat(a),F.realpath(a)]);if(await Yt(n),!l.isFile()||l.isSymbolicLink()||!kn(s,l)||!bn(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!kn(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 gw(a,c,n),await r.beforeCommit?.(),n){await Yt(n);let l=await F.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!vw(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await F.link(a,t),await F.unlink(a)):await F.rename(a,t),await yw(i)}catch(l){if(await o?.close(),!n)await F.rm(a,{force:!0});else try{await Yt(n),await F.rm(a,{force:!0})}catch{}throw l}}async function _e(t,e,r={}){await Nw(t,e,r)}async function oe(t,e,r={}){await _e(t,JSON.stringify(e,null,2)+`
143
+ `,r)}var D=E(()=>{"use strict";Ae()});function Ew(t,e){return ts[t][e]}function Sn(t){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ew(t,r)}
144
144
  `).join(`
145
- `)}var ts,bw,kw,Sw,ld,Nt=E(()=>{"use strict";ts={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:"验证预期"}},bw={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:"结论"}},kw={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:"结论"}},Sw=new Map,ld=new Map;for(let t of Object.keys(ts)){for(let[e,r]of Object.entries(ts[t]))Sw.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(bw[t]))ld.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(kw[t]))ld.set(r.toLocaleLowerCase("en-US"),e)}});import tt from"path";function Aw(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||tt.posix.isAbsolute(r)||tt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function bt(t){let e=Aw(t,"native.artifact_root");return e.length===0?".":e.join("/")}function md(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Pn(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||tt.posix.isAbsolute(i)||tt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function Be(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function vd(t,e,r){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Rn(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>xn)throw new Error(`${e} exceeds ${xn} characters`);let r=0;for(let i=0;i<t.length;i+=1)t[i]==="?"?r+=1:t[i]==="*"&&(r+=1,t[i+1]==="*"&&(i+=1));if(r>Cn)throw new Error(`${e} contains more than ${Cn} wildcard tokens`);return t}function pd(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>Rn(i,e)))].sort((i,n)=>i.localeCompare(n,"en"))}function rs(t,e,r){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function _w(t){if(t===void 0)return{...re,include:[...re.include],exclude:[...re.exclude]};let e=Be(t,"native.snapshot");return{include:pd(e.include,"native.snapshot.include",re.include),exclude:pd(e.exclude,"native.snapshot.exclude",re.exclude),max_files:rs(e.max_files,re.max_files,"native.snapshot.max_files"),max_total_bytes:rs(e.max_total_bytes,re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:rs(e.max_duration_ms,re.max_duration_ms,"native.snapshot.max_duration_ms")}}function Iw(t){if(t===void 0)return;let e=Be(t,"native.pending_root_move"),r=e.id,i=e.from_artifact_root,n=e.to_artifact_root,a=e.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(e.cleanup!==void 0){let s=Be(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:bt(i),toArtifactRoot:bt(n),stage:a,...o?{cleanup:o}:{}}}function Tw(t){if(t===void 0)return;let e=Be(t,"native.finish");if(e.pull_request===void 0)return{};let r=Be(e.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(tt.posix.isAbsolute(i[0])||tt.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??xw;if(!Number.isSafeInteger(n)||n<1||n>fd)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${fd}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function jw(t,e={}){let r=Be(t,"native"),i=r.artifact_root??(e.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??ns;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Iw(r.pending_root_move),c=Tw(r.finish);return{artifact_root:bt(i),language:vd(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:_w(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function $w(t){let e=Be(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:md(e.artifact_layout),language:vd(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Ow(t){let r=Be(t,"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)=>Pn(i,`hook.allow_paths[${n}]`)))]}}function Hw(t){if(t===void 0)return{...En};let e=Be(t,"memory"),r=e.learning??En.learning,i=e.retrieval??En.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 as(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Dw(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||tt.posix.isAbsolute(r)||tt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(r.length>ud)throw new Error(`${e} exceeds ${ud} 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>dd)throw new Error(`${e} contains more than ${dd} wildcard tokens`);return r}function Lw(t){let r=as(t,"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)=>Dw(i,`knowledge.local.include[${n}]`)))]}}function Bw(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function Vw(t){let e=as(t,"knowledge.remote"),r=Bw(e.endpoint),i=e.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=e.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=e.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 Mw(t){if(t===void 0)return{...hd};let e=as(t,"knowledge"),r=e.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=e.local===void 0?void 0:Lw(e.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=e.remote===void 0?void 0:Vw(e.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 Fw(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function qw(t,e,r,i,n,a,o,s){let c=t.schema!==void 0;if(!(c||t.default_workflow!==void 0||t.workflows!==void 0||!s.allowPartialProject&&t.native!==void 0)||s.allowPartialProject&&!c)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Qr(t,e={}){let r=(0,is.parseDocument)(t,{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=Fw(n.ambient_resume),o=n.hook===void 0?void 0:Ow(n.hook),s=Hw(n.memory),c=Mw(n.knowledge),l=n.native===void 0?void 0:jw(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=n.classic===void 0?void 0:$w(n.classic),d=qw(n,o,s,c,l,u,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function An(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...En},knowledge:{...hd},native:{artifact_root:bt(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ns,snapshot:{...re,include:[...re.include],exclude:[...re.exclude]}}}}var is,Xr,xn,Cn,ud,dd,ns,En,hd,xw,fd,Cw,Pw,Rw,re,rt=E(()=>{"use strict";is=mr(Gt(),1),Xr=64*1024,xn=1024,Cn=64,ud=1024,dd=64,ns=5,En={learning:!0,retrieval:!0},hd={provider:"local"},xw=12e4,fd=6e5,Cw=[".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/**"],Pw=["**/.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"],Rw=[...Cw,...Pw].sort((t,e)=>t.localeCompare(e,"en")),re={include:["**/*"],exclude:[...Rw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as _n,promises as kt}from"fs";function os(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function gd(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Zr(t){return{dev:t.dev,ino:t.ino,birthtime:os(t)}}function In(t,e){let r=Zr(t),i=Zr(e);return Le(r,i)?j(r,i):j(r,i)&&os(t)===os(e)&&gd(t)===gd(e)&&t.size===e.size}async function ei(t,e,r={}){if(!Number.isSafeInteger(e)||e<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 kt.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new _e("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new _e("too-large",`${i} exceeds ${e} bytes`);let o=await kt.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:Zr(a)});let s=process.platform==="win32"?_n.O_RDONLY:_n.O_RDONLY|_n.O_NOFOLLOW|_n.O_NONBLOCK,c;try{c=await kt.open(t,s)}catch(l){throw l.code==="ELOOP"?new _e("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),kt.lstat(t,{bigint:n}),kt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!In(a,l)||!In(a,u))throw new _e("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Zr(l)}),await r.hooks?.afterOpen?.();let f=[],h=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:N}=await c.read(g,0,Math.min(g.length,b),null);if(N===0)break;if(h+=N,h>e)throw new _e("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[p,v,m]=await Promise.all([c.stat({bigint:n}),kt.lstat(t,{bigint:n}),kt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||m!==o||!In(a,p)||!In(a,v))throw new _e("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:m,identity:Zr(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:m}}finally{await c.close()}}var _e,ti=E(()=>{"use strict";Yr();_e=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Tn}from"fs";import it from"path";function Ww(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ss(t,e){let r=it.relative(t,e);return r===""||!it.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${it.sep}`)}async function wd(t,e){let r=it.resolve(t),i=await Tn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Tn.realpath(r)}async function yd(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=it.join(n,r[a]);let o;try{o=await Tn.lstat(n)}catch(u){if(Ww(u))return{exists:!1,kind:"missing"};throw u}let s=it.relative(t,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 Tn.realpath(n);if(!ss(e,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 Xt(t,e,r){let i=Pn(e,r.label),n=it.resolve(t),a=await wd(n,r.label),o=i.split("/"),s=it.resolve(n,...o);if(!ss(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await yd(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function nt(t,e,r,i){let n=await Xt(t,e,{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 wd(n.projectRoot,i.label);return ei(n.target,r,{...i,verify:async(o,s)=>{if(!ss(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await yd(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var St=E(()=>{"use strict";ti();rt()});import{createHash as zw}from"crypto";function Jw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function jn(t,e={}){return(await $n(t,e)).document}async function Gw(t){try{return(await nt(t,ri,Xr,{label:ri})).bytes}catch(e){if(Jw(e))return null;throw e}}function Uw(t){return t?{exists:!0,sha256:zw("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function $n(t,e={}){let r=await Gw(t);return{document:r?Qr(r.toString("utf8"),e):null,identity:Uw(r)}}async function cs(t){return(await jn(t))?.config??null}var ri,Qt=E(()=>{"use strict";rt();St();ri=".comet/config.yaml"});var Zt=E(()=>{"use strict";Yr()});var IE,ls=E(()=>{"use strict";Zt();Qt();St();IE=16*1024});var fs=E(()=>{"use strict";Zt();rt();Qt();St();ls()});import{existsSync as bd,promises as Et}from"fs";import I from"path";import Zw from"os";async function ps(t){try{return await Et.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ty(t){try{let e=await Et.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function tr(t,e){let r=I.relative(t,e);return r===""||!I.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${I.sep}`)}async function er(t){let e=[],r=t;for(;!await ps(r);){let n=I.dirname(r);if(n===r)break;e.push(I.basename(r)),r=n}let i=await Et.realpath(r);return I.resolve(i,...e.reverse())}async function hs(t){try{return(await Et.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Hn(t){let e=I.resolve(t);try{(await Et.stat(e)).isDirectory()||(e=I.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=I.resolve(Zw.homedir());for(;;){if(!(e===i&&r!==i)){let o=I.join(e,...On.split("/")),s=e===r||await ty(o);if(await ps(o)&&s)return e}if(await ps(I.join(e,".git")))return e;let a=I.dirname(e);if(a===e)return r;e=a}}function Dn(t){return bt(t)}async function ry(t,e){let r=Dn(e),i=I.resolve(t,...r.split("/")),n=await Et.realpath(t),a=await er(i);if(!tr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function xt(t,e){let r=Dn(e),i=await ry(t,r),n=I.join(i,"comet");if(await hs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([er(i),er(n)]);if(!tr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=I.resolve(t),c=I.join(s,".comet","runtime","native");if(await hs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Et.realpath(s),er(c)]);if(!tr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:I.join(t,...On.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:I.join(n,"specs"),changesDir:I.join(n,"changes"),archiveDir:I.join(n,"archive"),runtimeDir:c,changesRuntimeDir:I.join(c,"changes"),locksDir:I.join(c,"locks"),transactionsDir:I.join(c,"transactions")}}function kd(t){if(!ey.test(t))throw new Error(`Invalid Native change name: ${t}`)}function rr(t,e){kd(e);let r=I.join(t.changesRuntimeDir,e);if(!U(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function iy(t,e){kd(e);let r=I.join(t.changesDir,e,"runtime");if(!U(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function se(t,e){let r=rr(t,e);if(bd(r))return r;let i=iy(t,e);return bd(i)?i:r}function Ie(t,e){let r=I.resolve(e);if(U(t.runtimeDir,r))return t.runtimeDir;if(U(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function U(t,e){return tr(I.resolve(t),I.resolve(e))}async function V(t,e){let r=I.resolve(t),i=I.resolve(e);if(!tr(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await hs(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([er(r),er(i)]);if(!tr(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}var On,ey,$=E(()=>{"use strict";rt();On=".comet/config.yaml",ey=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function ay(t="docs",e="en"){return An(t,e)}async function Te(t){let e=(await jn(t))?.config??null;return e?.native?e:null}async function Sd(t){let e=await Hn(t.startPath),r=await Te(e);if(!r&&t.allowMissingConfig===!1)throw new Error(`${On} 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=t.explicitArtifactRoot?Dn(t.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??ay(i??"docs"),a=await xt(e,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ln,we=E(()=>{"use strict";rt();Qt();fs();D();$();Ln=Rn});import{AsyncLocalStorage as oy}from"async_hooks";var rx,ix,ni=E(()=>{"use strict";ti();$();Re();rx=16*1024,ix=new oy});import{createHash as sy}from"crypto";function ye(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function cy(t,e){e.has(t)&&ye("cyclic structures are not supported"),e.add(t);try{let r=Object.keys(t);for(let i=0;i<t.length;i+=1)Object.prototype.hasOwnProperty.call(t,i)||ye("sparse arrays are not supported");return(r.length!==t.length||r.some((i,n)=>i!==String(n)))&&ye("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&ye("symbol properties are not supported"),`[${t.map(i=>ms(i,e)).join(",")}]`}finally{e.delete(t)}}function ly(t,e){let r=Object.getPrototypeOf(t);r!==Object.prototype&&r!==null&&ye("only plain objects are supported"),e.has(t)&&ye("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&ye("symbol properties are not supported"),e.add(t);try{let i=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&ye("accessor properties are not supported"),`${JSON.stringify(o)}:${ms(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function ms(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||ye("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?cy(t,e):ly(t,e);case"bigint":case"function":case"symbol":case"undefined":return ye(`${typeof t} values are not supported`)}return ye("unsupported value type")}function vs(t){return ms(t,new Set)}function z(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return sy("sha256").update(`${t}
146
- ${vs(e)}`).digest("hex")}var Z=E(()=>{"use strict"});var lx,Ed,Bn=E(()=>{"use strict";Nt();Z();lx=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ed=Object.freeze({maxCriteria:1024})});var gs=E(()=>{"use strict";Bn()});function ws(){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 ir,xd,ai=E(()=>{"use strict";ir="comet.native.v4",xd=["multi-session","single-session"]});var Es={};vc(Es,{NativePortableStateVersionConflictError:()=>oi,appendNativePortableHistory:()=>ks,compareAndSwapNativePortableState:()=>Ad,createNativePortableState:()=>Rd,parseNativePortableState:()=>Ne,readNativePortableState:()=>Ve,writeNativePortableState:()=>Ss});import{promises as py}from"node:fs";function K(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Y(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function q(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function Ns(t,e){return t===null?null:q(t,e)}function Cd(t,e){let r=q(t,e);if(!gy.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function nr(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function T(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function yy(t,e){return t===null?null:T(t,e,Number.MIN_SAFE_INTEGER)}function L(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function je(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function Fn(t,e){return je(t,e,(r,i)=>q(r,`${e}[${i}]`))}function Ct(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function ar(t,e){let r=q(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function bs(t,e,r=!1){let i=q(t,e);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return i}function ce(t,e){let r=K(t,e);return Y(r,new Set(["text","truncated"]),e),{text:q(r.text,`${e}.text`,{empty:!0}),truncated:nr(r.truncated,`${e}.truncated`)}}function Ny(t,e){let r=`Native spec_changes[${e}]`,i=K(t,r);Y(i,new Set(["capability","operation","source"]),r);let n=q(i.capability,`${r}.capability`);if(!my.test(n))throw new Error(`${r}.capability is invalid`);let a=L(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:bs(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 by(t){let e="Native workspace",r=K(t,e);Y(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=L(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=Ns(r.change_branch,`${e}.change_branch`),a=Ns(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:L(r.finish,["merge","push","pull-request","keep"],`${e}.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 ky(t){let e="Native loop",r=K(t,e);Y(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"]),e);let i=Fn(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);Ct(i,`${e}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:L(r.stop_reason,["budget","stalled"],`${e}.stop_reason`);return{stage:L(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:T(r.goal_cycle,`${e}.goal_cycle`,1),iteration:T(r.iteration,`${e}.iteration`),attempt:T(r.attempt,`${e}.attempt`),retry_epoch:T(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:T(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:T(r.no_progress_count,`${e}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:T(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:i,next_action:Ns(r.next_action,`${e}.next_action`)}}function Sy(t,e){let r=`Native acceptance[${e}]`,i=K(t,r);Y(i,new Set(["id","source","text","result","reason"]),r);let n=q(i.id,`${r}.id`);if(!vy.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:bs(i.source,`${r}.source`),text:q(i.text,`${r}.text`),result:L(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ce(i.reason,`${r}.reason`)}}function Ey(t,e){let r=`Native builder_handoff.checks[${e}]`,i=K(t,r);return Y(i,new Set(["name","result","note"]),r),{name:ce(i.name,`${r}.name`),result:L(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ce(i.note,`${r}.note`)}}function xy(t){let e="Native builder_handoff",r=K(t,e);Y(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"]),e);let i=Fn(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);Ct(i,`${e}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:K(r.review,`${e}.review`);return n&&Y(n,new Set(["status","summary","reviewer_execution_ref"]),`${e}.review`),{candidate_id:q(r.candidate_id,`${e}.candidate_id`),identity_provider:q(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:q(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),summary:ce(r.summary,`${e}.summary`),addressed_acceptance_ids:i,checks:je(r.checks,`${e}.checks`,Ey),checks_truncated:nr(r.checks_truncated,`${e}.checks_truncated`),known_limits:je(r.known_limits,`${e}.known_limits`,(a,o)=>ce(a,`${e}.known_limits[${o}]`)),known_limits_truncated:nr(r.known_limits_truncated,`${e}.known_limits_truncated`),review:n?{status:L(n.status,["passed"],`${e}.review.status`),summary:ce(n.summary,`${e}.review.summary`),reviewer_execution_ref:q(n.reviewer_execution_ref,`${e}.review.reviewer_execution_ref`)}:null,submitted_at:ar(r.submitted_at,`${e}.submitted_at`)}}function Cy(t,e){let r=`Native blockers[${e}]`,i=K(t,r);Y(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Fn(i.acceptance_ids,`${r}.acceptance_ids`);return Ct(n,`${r}.acceptance_ids`),{owner:L(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ce(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:L(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Py(t,e){let r=`Native verification.checks[${e}]`,i=K(t,r);return Y(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:q(i.id,`${r}.id`),name:ce(i.name,`${r}.name`),argv_display:je(i.argv_display,`${r}.argv_display`,(n,a)=>ce(n,`${r}.argv_display[${a}]`)),argv_truncated:nr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:bs(i.cwd_ref,`${r}.cwd_ref`,!0),status:L(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:yy(i.exit_code,`${r}.exit_code`),duration_ms:T(i.duration_ms,`${r}.duration_ms`)}}function Ry(t){let e="Native verification",r=K(t,e);Y(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=je(r.checks,`${e}.checks`,Py);Ct(i.map(a=>a.id),`${e}.checks IDs`);let n=q(r.identity_provider,`${e}.identity_provider`);return{candidate_id:q(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:q(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),attempt:T(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":L(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:L(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:i,summary:ce(r.summary,`${e}.summary`),risks:je(r.risks,`${e}.risks`,(a,o)=>ce(a,`${e}.risks[${o}]`)),risks_truncated:nr(r.risks_truncated,`${e}.risks_truncated`),completed_at:ar(r.completed_at,`${e}.completed_at`)}}function Pd(t,e){let r=`Native history[${e}]`,i=K(t,r);Y(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Fn(i.unresolved_ids,`${r}.unresolved_ids`);return Ct(n,`${r}.unresolved_ids`),{goal_cycle:T(i.goal_cycle,`${r}.goal_cycle`,1),iteration:T(i.iteration,`${r}.iteration`),attempt:T(i.attempt,`${r}.attempt`),outcome:L(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ce(i.summary,`${r}.summary`),completed_at:ar(i.completed_at,`${r}.completed_at`)}}function Ay(t){let e="Native history_overflow.outcome_counts",r=K(t,e),i=["pass","fail","blocked","execution-error","recovery"];return Y(r,new Set(i),e),{pass:T(r.pass,`${e}.pass`),fail:T(r.fail,`${e}.fail`),blocked:T(r.blocked,`${e}.blocked`),"execution-error":T(r["execution-error"],`${e}.execution-error`),recovery:T(r.recovery,`${e}.recovery`)}}function _y(t){let e="Native history_overflow",r=K(t,e);Y(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let i=T(r.dropped_entries,`${e}.dropped_entries`),n=r.first_dropped_at===null?null:ar(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:ar(r.last_dropped_at,`${e}.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=Ay(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 Iy(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of t.blockers)for(let i of r.acceptance_ids)if(!e.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(t.builder_handoff){if(!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.builder_handoff.review?.reviewer_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.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(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Ty(t){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"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function Ne(t){let e=K(t,"Native portable state");if(Y(e,wy,"Native portable state"),e.schema!==ir)throw new Error(`Native portable state schema must be ${ir}`);let r=q(e.name,"Native state name");if(!hy.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=je(e.spec_changes,"Native spec_changes",Ny);Ct(i.map(s=>s.capability),"Native spec change capabilities");let n=je(e.acceptance,"Native acceptance",Sy);Ct(n.map(s=>s.id),"Native acceptance IDs");let a=je(e.history,"Native history",Pd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ir,name:r,language:L(e.language,["en","zh-CN"],"Native state language"),phase:L(e.phase,["shape","build","verify","archive"],"Native state phase"),status:L(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:T(e.state_version,"Native state_version",1),brief:"brief.md",...e.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Cd(e.shape_confirmation_hash,"Native Shape confirmation hash")},...e.children_contract_hash===void 0?{}:{children_contract_hash:Cd(e.children_contract_hash,"Native children contract hash")},...e.coordination_mode===void 0?{}:{coordination_mode:L(e.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:by(e.workspace),loop:ky(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:xy(e.builder_handoff),blockers:je(e.blockers,"Native blockers",Cy),verification:e.verification===null?null:Ry(e.verification),history:a,history_overflow:_y(e.history_overflow),verification_result:L(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:L(e.verification_report,["verification.md"],"Native verification_report"),archived:nr(e.archived,"Native archived"),created_at:ar(e.created_at,"Native created_at")};return Iy(o),Ty(o),o}function Rd(t){let e=t.createdAt instanceof Date?t.createdAt.toISOString():t.createdAt??new Date().toISOString();return Ne({schema:ir,name:t.name,language:t.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:t.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:t.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:ws(),verification_result:"pending",verification_report:null,archived:!1,created_at:e})}function ks(t,e){let r=Ne(t),i=Pd(e,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 Ne({...r,history:n,history_overflow:a})}function jy(t,e){let r=(0,Mn.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Ve(t){let e=await py.readFile(t,"utf8");return Ne(jy(e,"Native portable state"))}async function Ss(t,e,r={}){let i=Ne(e);await Ae(t,(0,Mn.stringify)(i),r)}async function $y(t,e){let r=Vn.get(t)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Vn.set(t,a),await r;try{return await e()}finally{i(),Vn.get(t)===a&&Vn.delete(t)}}async function Ad(t){return $y(t.file,async()=>{let e=T(t.expectedStateVersion,"Native expected state version",1),r=Ne(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Ve(t.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==e)throw new oi(e,i.state_version);return await Ss(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Ve(t.file);if(n.state_version!==e)throw new oi(e,n.state_version)}}),r})}var Mn,hy,my,vy,gy,wy,oi,Vn,Pt=E(()=>{"use strict";Mn=mr(Gt(),1);D();ai();hy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,my=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vy=/^A[1-9][0-9]*$/u,gy=/^[a-f0-9]{64}$/u,wy=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"]),oi=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"};Vn=new Map});var qn=E(()=>{"use strict"});var at,ot,st,Wn=E(()=>{"use strict";at="comet.native.v3",ot="comet.native.v2",st="comet.native.v1"});var Id=E(()=>{"use strict";J();gs();Pt();qn();ai();Wn()});var Td,Ix,Tx,xs=E(()=>{"use strict";ae();Id();Td="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Ix=new RegExp(`^portable-archive-(${Td})\\.json$`,"u"),Tx=new RegExp(`^portable-migration-(${Td})\\.json$`,"u")});import{createHash as Oy}from"node:crypto";import{constants as Un,promises as be}from"node:fs";import ke from"node:path";import{TextDecoder as Hy}from"node:util";function Yn(t,e){let r=ke.relative(t,e);return r===""||!ke.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ke.sep}`)}function Dy(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Ly(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function By(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function Kn(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Cs(t,e){let r=await be.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await be.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function jd(t,e,r){let i=ke.resolve(t),n=ke.resolve(e);if(!Yn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Cs(i,r)],o=i;for(let s of ke.relative(i,n).split(ke.sep).filter(Boolean)){await ct(a,r),o=ke.join(o,s);let c=await Cs(o,r);if(!Yn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await ct(a,r),a}async function ct(t,e){for(let r of t){let i=await be.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ly(r,i)||await be.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function Vy(t,e,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${r} exceeds ${e} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function or(t){let e=Dy(t.maxBytes),r=ke.resolve(t.file),i=await jd(t.root,ke.dirname(r),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>Cs(ke.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await ct(i,t.label);let a=await be.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=By(a),s=await be.realpath(r);if(!Yn(i[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>Yn(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?Un.O_RDONLY:Un.O_RDONLY|Un.O_NOFOLLOW|Un.O_NONBLOCK,l=await be.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[d,f]=await Promise.all([be.lstat(r),be.realpath(r)]);if(await ct(i,t.label),await ct(n,t.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Kn(o,u)||!Kn(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await Vy(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,p,v]=await Promise.all([l.stat(),be.lstat(r),be.realpath(r)]);if(await ct(i,t.label),await ct(n,t.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Kn(o,g)||!Kn(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:Oy("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function $d(t){let e=await or(t),r;try{r=new Hy("utf-8",{fatal:!0}).decode(e.bytes)}catch(i){throw new Error(`${t.label} is not valid UTF-8`,{cause:i})}return{...e,text:r}}async function Ps(t){let e=await jd(t.root,t.directory,t.label);return{verify:()=>ct(e,t.label)}}var Se=E(()=>{"use strict";D();Re()});import{TextDecoder as Fy}from"util";var Ux,Kx,Yx,Xx,Qx,Xn=E(()=>{"use strict";D();$();Se();Ux=256*1024,Kx=1024*1024,Yx=16*1024,Xx=64*1024*1024,Qx=new Fy("utf-8",{fatal:!0})});var le=E(()=>{"use strict";we();ni();xs();Xn()});var Bd=E(()=>{"use strict"});import{createHash as Wy}from"crypto";function ee(t){return Wy("sha256").update(t).digest("hex")}var Ee=E(()=>{"use strict"});import _s from"path";function Qn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function dN(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function fN(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
145
+ `)}var ts,bw,kw,Sw,ld,Nt=E(()=>{"use strict";ts={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:"验证预期"}},bw={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:"结论"}},kw={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:"结论"}},Sw=new Map,ld=new Map;for(let t of Object.keys(ts)){for(let[e,r]of Object.entries(ts[t]))Sw.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(bw[t]))ld.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(kw[t]))ld.set(r.toLocaleLowerCase("en-US"),e)}});import tt from"path";function Aw(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||tt.posix.isAbsolute(r)||tt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function bt(t){let e=Aw(t,"native.artifact_root");return e.length===0?".":e.join("/")}function md(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Pn(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||tt.posix.isAbsolute(i)||tt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function Ve(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function vd(t,e,r){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Rn(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>xn)throw new Error(`${e} exceeds ${xn} characters`);let r=0;for(let i=0;i<t.length;i+=1)t[i]==="?"?r+=1:t[i]==="*"&&(r+=1,t[i+1]==="*"&&(i+=1));if(r>Cn)throw new Error(`${e} contains more than ${Cn} wildcard tokens`);return t}function pd(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>Rn(i,e)))].sort((i,n)=>i.localeCompare(n,"en"))}function rs(t,e,r){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function _w(t){if(t===void 0)return{...re,include:[...re.include],exclude:[...re.exclude]};let e=Ve(t,"native.snapshot");return{include:pd(e.include,"native.snapshot.include",re.include),exclude:pd(e.exclude,"native.snapshot.exclude",re.exclude),max_files:rs(e.max_files,re.max_files,"native.snapshot.max_files"),max_total_bytes:rs(e.max_total_bytes,re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:rs(e.max_duration_ms,re.max_duration_ms,"native.snapshot.max_duration_ms")}}function Iw(t){if(t===void 0)return;let e=Ve(t,"native.pending_root_move"),r=e.id,i=e.from_artifact_root,n=e.to_artifact_root,a=e.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(e.cleanup!==void 0){let s=Ve(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:bt(i),toArtifactRoot:bt(n),stage:a,...o?{cleanup:o}:{}}}function Tw(t){if(t===void 0)return;let e=Ve(t,"native.finish");if(e.pull_request===void 0)return{};let r=Ve(e.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(tt.posix.isAbsolute(i[0])||tt.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??xw;if(!Number.isSafeInteger(n)||n<1||n>fd)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${fd}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function jw(t,e={}){let r=Ve(t,"native"),i=r.artifact_root??(e.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??ns;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Iw(r.pending_root_move),c=Tw(r.finish);return{artifact_root:bt(i),language:vd(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:_w(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function $w(t){let e=Ve(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:md(e.artifact_layout),language:vd(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Ow(t){let r=Ve(t,"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)=>Pn(i,`hook.allow_paths[${n}]`)))]}}function Hw(t){if(t===void 0)return{...En};let e=Ve(t,"memory"),r=e.learning??En.learning,i=e.retrieval??En.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 as(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Dw(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||tt.posix.isAbsolute(r)||tt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(r.length>ud)throw new Error(`${e} exceeds ${ud} 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>dd)throw new Error(`${e} contains more than ${dd} wildcard tokens`);return r}function Lw(t){let r=as(t,"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)=>Dw(i,`knowledge.local.include[${n}]`)))]}}function Bw(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function Vw(t){let e=as(t,"knowledge.remote"),r=Bw(e.endpoint),i=e.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=e.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=e.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 Mw(t){if(t===void 0)return{...hd};let e=as(t,"knowledge"),r=e.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=e.local===void 0?void 0:Lw(e.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=e.remote===void 0?void 0:Vw(e.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 Fw(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function qw(t,e,r,i,n,a,o,s){let c=t.schema!==void 0;if(!(c||t.default_workflow!==void 0||t.workflows!==void 0||!s.allowPartialProject&&t.native!==void 0)||s.allowPartialProject&&!c)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Qr(t,e={}){let r=(0,is.parseDocument)(t,{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=Fw(n.ambient_resume),o=n.hook===void 0?void 0:Ow(n.hook),s=Hw(n.memory),c=Mw(n.knowledge),l=n.native===void 0?void 0:jw(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=n.classic===void 0?void 0:$w(n.classic),d=qw(n,o,s,c,l,u,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function An(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...En},knowledge:{...hd},native:{artifact_root:bt(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ns,snapshot:{...re,include:[...re.include],exclude:[...re.exclude]}}}}var is,Xr,xn,Cn,ud,dd,ns,En,hd,xw,fd,Cw,Pw,Rw,re,rt=E(()=>{"use strict";is=mr(Gt(),1),Xr=64*1024,xn=1024,Cn=64,ud=1024,dd=64,ns=5,En={learning:!0,retrieval:!0},hd={provider:"local"},xw=12e4,fd=6e5,Cw=[".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/**"],Pw=["**/.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"],Rw=[...Cw,...Pw].sort((t,e)=>t.localeCompare(e,"en")),re={include:["**/*"],exclude:[...Rw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as _n,promises as kt}from"fs";function os(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function gd(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Zr(t){return{dev:t.dev,ino:t.ino,birthtime:os(t)}}function In(t,e){let r=Zr(t),i=Zr(e);return Be(r,i)?j(r,i):j(r,i)&&os(t)===os(e)&&gd(t)===gd(e)&&t.size===e.size}async function ei(t,e,r={}){if(!Number.isSafeInteger(e)||e<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 kt.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ie("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Ie("too-large",`${i} exceeds ${e} bytes`);let o=await kt.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:Zr(a)});let s=process.platform==="win32"?_n.O_RDONLY:_n.O_RDONLY|_n.O_NOFOLLOW|_n.O_NONBLOCK,c;try{c=await kt.open(t,s)}catch(l){throw l.code==="ELOOP"?new Ie("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),kt.lstat(t,{bigint:n}),kt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!In(a,l)||!In(a,u))throw new Ie("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Zr(l)}),await r.hooks?.afterOpen?.();let f=[],h=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:N}=await c.read(g,0,Math.min(g.length,b),null);if(N===0)break;if(h+=N,h>e)throw new Ie("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[p,v,m]=await Promise.all([c.stat({bigint:n}),kt.lstat(t,{bigint:n}),kt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||m!==o||!In(a,p)||!In(a,v))throw new Ie("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:m,identity:Zr(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:m}}finally{await c.close()}}var Ie,ti=E(()=>{"use strict";Yr();Ie=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as Tn}from"fs";import it from"path";function Ww(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ss(t,e){let r=it.relative(t,e);return r===""||!it.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${it.sep}`)}async function wd(t,e){let r=it.resolve(t),i=await Tn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Tn.realpath(r)}async function yd(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=it.join(n,r[a]);let o;try{o=await Tn.lstat(n)}catch(u){if(Ww(u))return{exists:!1,kind:"missing"};throw u}let s=it.relative(t,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 Tn.realpath(n);if(!ss(e,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 Xt(t,e,r){let i=Pn(e,r.label),n=it.resolve(t),a=await wd(n,r.label),o=i.split("/"),s=it.resolve(n,...o);if(!ss(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await yd(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function nt(t,e,r,i){let n=await Xt(t,e,{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 wd(n.projectRoot,i.label);return ei(n.target,r,{...i,verify:async(o,s)=>{if(!ss(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await yd(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var St=E(()=>{"use strict";ti();rt()});import{createHash as zw}from"crypto";function Jw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function jn(t,e={}){return(await $n(t,e)).document}async function Gw(t){try{return(await nt(t,ri,Xr,{label:ri})).bytes}catch(e){if(Jw(e))return null;throw e}}function Uw(t){return t?{exists:!0,sha256:zw("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function $n(t,e={}){let r=await Gw(t);return{document:r?Qr(r.toString("utf8"),e):null,identity:Uw(r)}}async function cs(t){return(await jn(t))?.config??null}var ri,Qt=E(()=>{"use strict";rt();St();ri=".comet/config.yaml"});var Zt=E(()=>{"use strict";Yr()});var IE,ls=E(()=>{"use strict";Zt();Qt();St();IE=16*1024});var fs=E(()=>{"use strict";Zt();rt();Qt();St();ls()});import{existsSync as bd,promises as Et}from"fs";import I from"path";import Zw from"os";async function ps(t){try{return await Et.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ty(t){try{let e=await Et.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function tr(t,e){let r=I.relative(t,e);return r===""||!I.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${I.sep}`)}async function er(t){let e=[],r=t;for(;!await ps(r);){let n=I.dirname(r);if(n===r)break;e.push(I.basename(r)),r=n}let i=await Et.realpath(r);return I.resolve(i,...e.reverse())}async function hs(t){try{return(await Et.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Hn(t){let e=I.resolve(t);try{(await Et.stat(e)).isDirectory()||(e=I.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=I.resolve(Zw.homedir());for(;;){if(!(e===i&&r!==i)){let o=I.join(e,...On.split("/")),s=e===r||await ty(o);if(await ps(o)&&s)return e}if(await ps(I.join(e,".git")))return e;let a=I.dirname(e);if(a===e)return r;e=a}}function Dn(t){return bt(t)}async function ry(t,e){let r=Dn(e),i=I.resolve(t,...r.split("/")),n=await Et.realpath(t),a=await er(i);if(!tr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function xt(t,e){let r=Dn(e),i=await ry(t,r),n=I.join(i,"comet");if(await hs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([er(i),er(n)]);if(!tr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=I.resolve(t),c=I.join(s,".comet","runtime","native");if(await hs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Et.realpath(s),er(c)]);if(!tr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:I.join(t,...On.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:I.join(n,"specs"),changesDir:I.join(n,"changes"),archiveDir:I.join(n,"archive"),runtimeDir:c,changesRuntimeDir:I.join(c,"changes"),locksDir:I.join(c,"locks"),transactionsDir:I.join(c,"transactions")}}function kd(t){if(!ey.test(t))throw new Error(`Invalid Native change name: ${t}`)}function rr(t,e){kd(e);let r=I.join(t.changesRuntimeDir,e);if(!U(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function iy(t,e){kd(e);let r=I.join(t.changesDir,e,"runtime");if(!U(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function se(t,e){let r=rr(t,e);if(bd(r))return r;let i=iy(t,e);return bd(i)?i:r}function Te(t,e){let r=I.resolve(e);if(U(t.runtimeDir,r))return t.runtimeDir;if(U(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function U(t,e){return tr(I.resolve(t),I.resolve(e))}async function V(t,e){let r=I.resolve(t),i=I.resolve(e);if(!tr(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await hs(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([er(r),er(i)]);if(!tr(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}var On,ey,$=E(()=>{"use strict";rt();On=".comet/config.yaml",ey=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function ay(t="docs",e="en"){return An(t,e)}async function je(t){let e=(await jn(t))?.config??null;return e?.native?e:null}async function Sd(t){let e=await Hn(t.startPath),r=await je(e);if(!r&&t.allowMissingConfig===!1)throw new Error(`${On} 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=t.explicitArtifactRoot?Dn(t.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??ay(i??"docs"),a=await xt(e,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ln,ye=E(()=>{"use strict";rt();Qt();fs();D();$();Ln=Rn});import{AsyncLocalStorage as oy}from"async_hooks";var rx,ix,ni=E(()=>{"use strict";ti();$();Ae();rx=16*1024,ix=new oy});import{createHash as sy}from"crypto";function Ne(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function cy(t,e){e.has(t)&&Ne("cyclic structures are not supported"),e.add(t);try{let r=Object.keys(t);for(let i=0;i<t.length;i+=1)Object.prototype.hasOwnProperty.call(t,i)||Ne("sparse arrays are not supported");return(r.length!==t.length||r.some((i,n)=>i!==String(n)))&&Ne("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Ne("symbol properties are not supported"),`[${t.map(i=>ms(i,e)).join(",")}]`}finally{e.delete(t)}}function ly(t,e){let r=Object.getPrototypeOf(t);r!==Object.prototype&&r!==null&&Ne("only plain objects are supported"),e.has(t)&&Ne("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Ne("symbol properties are not supported"),e.add(t);try{let i=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Ne("accessor properties are not supported"),`${JSON.stringify(o)}:${ms(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function ms(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Ne("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?cy(t,e):ly(t,e);case"bigint":case"function":case"symbol":case"undefined":return Ne(`${typeof t} values are not supported`)}return Ne("unsupported value type")}function vs(t){return ms(t,new Set)}function z(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return sy("sha256").update(`${t}
146
+ ${vs(e)}`).digest("hex")}var Z=E(()=>{"use strict"});var lx,Ed,Bn=E(()=>{"use strict";Nt();Z();lx=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ed=Object.freeze({maxCriteria:1024})});var gs=E(()=>{"use strict";Bn()});function ws(){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 ir,xd,ai=E(()=>{"use strict";ir="comet.native.v4",xd=["multi-session","single-session"]});var Es={};vc(Es,{NativePortableStateVersionConflictError:()=>oi,appendNativePortableHistory:()=>ks,compareAndSwapNativePortableState:()=>Ad,createNativePortableState:()=>Rd,parseNativePortableState:()=>be,readNativePortableState:()=>Me,writeNativePortableState:()=>Ss});import{promises as py}from"node:fs";function K(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Y(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function q(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function Ns(t,e){return t===null?null:q(t,e)}function Cd(t,e){let r=q(t,e);if(!gy.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function nr(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function T(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function yy(t,e){return t===null?null:T(t,e,Number.MIN_SAFE_INTEGER)}function L(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function $e(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function Fn(t,e){return $e(t,e,(r,i)=>q(r,`${e}[${i}]`))}function Ct(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function ar(t,e){let r=q(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function bs(t,e,r=!1){let i=q(t,e);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return i}function ce(t,e){let r=K(t,e);return Y(r,new Set(["text","truncated"]),e),{text:q(r.text,`${e}.text`,{empty:!0}),truncated:nr(r.truncated,`${e}.truncated`)}}function Ny(t,e){let r=`Native spec_changes[${e}]`,i=K(t,r);Y(i,new Set(["capability","operation","source"]),r);let n=q(i.capability,`${r}.capability`);if(!my.test(n))throw new Error(`${r}.capability is invalid`);let a=L(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:bs(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 by(t){let e="Native workspace",r=K(t,e);Y(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=L(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=Ns(r.change_branch,`${e}.change_branch`),a=Ns(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:L(r.finish,["merge","push","pull-request","keep"],`${e}.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 ky(t){let e="Native loop",r=K(t,e);Y(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"]),e);let i=Fn(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);Ct(i,`${e}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:L(r.stop_reason,["budget","stalled"],`${e}.stop_reason`);return{stage:L(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:T(r.goal_cycle,`${e}.goal_cycle`,1),iteration:T(r.iteration,`${e}.iteration`),attempt:T(r.attempt,`${e}.attempt`),retry_epoch:T(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:T(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:T(r.no_progress_count,`${e}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:T(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:i,next_action:Ns(r.next_action,`${e}.next_action`)}}function Sy(t,e){let r=`Native acceptance[${e}]`,i=K(t,r);Y(i,new Set(["id","source","text","result","reason"]),r);let n=q(i.id,`${r}.id`);if(!vy.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:bs(i.source,`${r}.source`),text:q(i.text,`${r}.text`),result:L(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ce(i.reason,`${r}.reason`)}}function Ey(t,e){let r=`Native builder_handoff.checks[${e}]`,i=K(t,r);return Y(i,new Set(["name","result","note"]),r),{name:ce(i.name,`${r}.name`),result:L(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ce(i.note,`${r}.note`)}}function xy(t){let e="Native builder_handoff",r=K(t,e);Y(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"]),e);let i=Fn(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);Ct(i,`${e}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:K(r.review,`${e}.review`);return n&&Y(n,new Set(["status","summary","reviewer_execution_ref"]),`${e}.review`),{candidate_id:q(r.candidate_id,`${e}.candidate_id`),identity_provider:q(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:q(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),summary:ce(r.summary,`${e}.summary`),addressed_acceptance_ids:i,checks:$e(r.checks,`${e}.checks`,Ey),checks_truncated:nr(r.checks_truncated,`${e}.checks_truncated`),known_limits:$e(r.known_limits,`${e}.known_limits`,(a,o)=>ce(a,`${e}.known_limits[${o}]`)),known_limits_truncated:nr(r.known_limits_truncated,`${e}.known_limits_truncated`),review:n?{status:L(n.status,["passed"],`${e}.review.status`),summary:ce(n.summary,`${e}.review.summary`),reviewer_execution_ref:q(n.reviewer_execution_ref,`${e}.review.reviewer_execution_ref`)}:null,submitted_at:ar(r.submitted_at,`${e}.submitted_at`)}}function Cy(t,e){let r=`Native blockers[${e}]`,i=K(t,r);Y(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Fn(i.acceptance_ids,`${r}.acceptance_ids`);return Ct(n,`${r}.acceptance_ids`),{owner:L(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ce(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:L(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Py(t,e){let r=`Native verification.checks[${e}]`,i=K(t,r);return Y(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:q(i.id,`${r}.id`),name:ce(i.name,`${r}.name`),argv_display:$e(i.argv_display,`${r}.argv_display`,(n,a)=>ce(n,`${r}.argv_display[${a}]`)),argv_truncated:nr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:bs(i.cwd_ref,`${r}.cwd_ref`,!0),status:L(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:yy(i.exit_code,`${r}.exit_code`),duration_ms:T(i.duration_ms,`${r}.duration_ms`)}}function Ry(t){let e="Native verification",r=K(t,e);Y(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=$e(r.checks,`${e}.checks`,Py);Ct(i.map(a=>a.id),`${e}.checks IDs`);let n=q(r.identity_provider,`${e}.identity_provider`);return{candidate_id:q(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:q(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),attempt:T(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":L(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:L(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:i,summary:ce(r.summary,`${e}.summary`),risks:$e(r.risks,`${e}.risks`,(a,o)=>ce(a,`${e}.risks[${o}]`)),risks_truncated:nr(r.risks_truncated,`${e}.risks_truncated`),completed_at:ar(r.completed_at,`${e}.completed_at`)}}function Pd(t,e){let r=`Native history[${e}]`,i=K(t,r);Y(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Fn(i.unresolved_ids,`${r}.unresolved_ids`);return Ct(n,`${r}.unresolved_ids`),{goal_cycle:T(i.goal_cycle,`${r}.goal_cycle`,1),iteration:T(i.iteration,`${r}.iteration`),attempt:T(i.attempt,`${r}.attempt`),outcome:L(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ce(i.summary,`${r}.summary`),completed_at:ar(i.completed_at,`${r}.completed_at`)}}function Ay(t){let e="Native history_overflow.outcome_counts",r=K(t,e),i=["pass","fail","blocked","execution-error","recovery"];return Y(r,new Set(i),e),{pass:T(r.pass,`${e}.pass`),fail:T(r.fail,`${e}.fail`),blocked:T(r.blocked,`${e}.blocked`),"execution-error":T(r["execution-error"],`${e}.execution-error`),recovery:T(r.recovery,`${e}.recovery`)}}function _y(t){let e="Native history_overflow",r=K(t,e);Y(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let i=T(r.dropped_entries,`${e}.dropped_entries`),n=r.first_dropped_at===null?null:ar(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:ar(r.last_dropped_at,`${e}.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=Ay(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 Iy(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of t.blockers)for(let i of r.acceptance_ids)if(!e.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(t.builder_handoff){if(!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.builder_handoff.review?.reviewer_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.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(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Ty(t){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"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function be(t){let e=K(t,"Native portable state");if(Y(e,wy,"Native portable state"),e.schema!==ir)throw new Error(`Native portable state schema must be ${ir}`);let r=q(e.name,"Native state name");if(!hy.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=$e(e.spec_changes,"Native spec_changes",Ny);Ct(i.map(s=>s.capability),"Native spec change capabilities");let n=$e(e.acceptance,"Native acceptance",Sy);Ct(n.map(s=>s.id),"Native acceptance IDs");let a=$e(e.history,"Native history",Pd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ir,name:r,language:L(e.language,["en","zh-CN"],"Native state language"),phase:L(e.phase,["shape","build","verify","archive"],"Native state phase"),status:L(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:T(e.state_version,"Native state_version",1),brief:"brief.md",...e.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Cd(e.shape_confirmation_hash,"Native Shape confirmation hash")},...e.children_contract_hash===void 0?{}:{children_contract_hash:Cd(e.children_contract_hash,"Native children contract hash")},...e.coordination_mode===void 0?{}:{coordination_mode:L(e.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:by(e.workspace),loop:ky(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:xy(e.builder_handoff),blockers:$e(e.blockers,"Native blockers",Cy),verification:e.verification===null?null:Ry(e.verification),history:a,history_overflow:_y(e.history_overflow),verification_result:L(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:L(e.verification_report,["verification.md"],"Native verification_report"),archived:nr(e.archived,"Native archived"),created_at:ar(e.created_at,"Native created_at")};return Iy(o),Ty(o),o}function Rd(t){let e=t.createdAt instanceof Date?t.createdAt.toISOString():t.createdAt??new Date().toISOString();return be({schema:ir,name:t.name,language:t.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:t.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:t.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:ws(),verification_result:"pending",verification_report:null,archived:!1,created_at:e})}function ks(t,e){let r=be(t),i=Pd(e,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 be({...r,history:n,history_overflow:a})}function jy(t,e){let r=(0,Mn.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Me(t){let e=await py.readFile(t,"utf8");return be(jy(e,"Native portable state"))}async function Ss(t,e,r={}){let i=be(e);await _e(t,(0,Mn.stringify)(i),r)}async function $y(t,e){let r=Vn.get(t)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Vn.set(t,a),await r;try{return await e()}finally{i(),Vn.get(t)===a&&Vn.delete(t)}}async function Ad(t){return $y(t.file,async()=>{let e=T(t.expectedStateVersion,"Native expected state version",1),r=be(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Me(t.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==e)throw new oi(e,i.state_version);return await Ss(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Me(t.file);if(n.state_version!==e)throw new oi(e,n.state_version)}}),r})}var Mn,hy,my,vy,gy,wy,oi,Vn,Pt=E(()=>{"use strict";Mn=mr(Gt(),1);D();ai();hy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,my=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vy=/^A[1-9][0-9]*$/u,gy=/^[a-f0-9]{64}$/u,wy=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"]),oi=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"};Vn=new Map});var qn=E(()=>{"use strict"});var at,ot,st,Wn=E(()=>{"use strict";at="comet.native.v3",ot="comet.native.v2",st="comet.native.v1"});var Id=E(()=>{"use strict";J();gs();Pt();qn();ai();Wn()});var Td,Ix,Tx,xs=E(()=>{"use strict";ae();Id();Td="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Ix=new RegExp(`^portable-archive-(${Td})\\.json$`,"u"),Tx=new RegExp(`^portable-migration-(${Td})\\.json$`,"u")});import{createHash as Oy}from"node:crypto";import{constants as Un,promises as ke}from"node:fs";import Se from"node:path";import{TextDecoder as Hy}from"node:util";function Yn(t,e){let r=Se.relative(t,e);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function Dy(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Ly(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function By(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function Kn(t,e){return j({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Cs(t,e){let r=await ke.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await ke.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function jd(t,e,r){let i=Se.resolve(t),n=Se.resolve(e);if(!Yn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Cs(i,r)],o=i;for(let s of Se.relative(i,n).split(Se.sep).filter(Boolean)){await ct(a,r),o=Se.join(o,s);let c=await Cs(o,r);if(!Yn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await ct(a,r),a}async function ct(t,e){for(let r of t){let i=await ke.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ly(r,i)||await ke.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function Vy(t,e,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${r} exceeds ${e} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function or(t){let e=Dy(t.maxBytes),r=Se.resolve(t.file),i=await jd(t.root,Se.dirname(r),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>Cs(Se.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await ct(i,t.label);let a=await ke.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=By(a),s=await ke.realpath(r);if(!Yn(i[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>Yn(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?Un.O_RDONLY:Un.O_RDONLY|Un.O_NOFOLLOW|Un.O_NONBLOCK,l=await ke.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[d,f]=await Promise.all([ke.lstat(r),ke.realpath(r)]);if(await ct(i,t.label),await ct(n,t.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Kn(o,u)||!Kn(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await Vy(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,p,v]=await Promise.all([l.stat(),ke.lstat(r),ke.realpath(r)]);if(await ct(i,t.label),await ct(n,t.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Kn(o,g)||!Kn(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:Oy("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function $d(t){let e=await or(t),r;try{r=new Hy("utf-8",{fatal:!0}).decode(e.bytes)}catch(i){throw new Error(`${t.label} is not valid UTF-8`,{cause:i})}return{...e,text:r}}async function Ps(t){let e=await jd(t.root,t.directory,t.label);return{verify:()=>ct(e,t.label)}}var Ee=E(()=>{"use strict";D();Ae()});import{TextDecoder as Fy}from"util";var Ux,Kx,Yx,Xx,Qx,Xn=E(()=>{"use strict";D();$();Ee();Ux=256*1024,Kx=1024*1024,Yx=16*1024,Xx=64*1024*1024,Qx=new Fy("utf-8",{fatal:!0})});var le=E(()=>{"use strict";ye();ni();xs();Xn()});var Bd=E(()=>{"use strict"});import{createHash as Wy}from"crypto";function ee(t){return Wy("sha256").update(t).digest("hex")}var xe=E(()=>{"use strict"});import _s from"path";function Qn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function dN(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function fN(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
147
147
  `)}function pN(t,e){return ee(`comet.native.snapshot-policy.v1
148
- ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function As(t,e,r){let i=new Set(e),n=[...e];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=t[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 hN(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Vd(t){let e=Ln(t,"Native snapshot pattern"),r=[];for(let i=0;i<e.length;i+=1){let n=e[i];n==="*"&&e[i+1]==="*"?(i+=1,e[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?hN(n):void 0;if(a&&!a())return!1;let o=As(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 u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=As(r,c,a),o===null||o.size===0)return!1}return As(r,o,a)?.has(r.length)??!1}}function mN(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>Ln(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>Ln(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let i=pN(e,r);if("hash"in t&&t.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:i},includeMatchers:e.map(Vd),excludeMatchers:r.map(Vd),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 ue(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function de(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function cr(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function $e(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function qd(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=_s.posix.normalize(t);if(r!==t||_s.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function vN(t,e){let r=ue(t,`Native snapshot entry ${e}`);de(r,nN,`Native snapshot entry ${e}`);let i=qd(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!Zn.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:i,hash:r.hash,size:$e(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!uN.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function gN(t,e){let r=ue(t,`Native snapshot omission ${e}`);if(de(r,aN,`Native snapshot omission ${e}`),!cN.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!lN.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:qd(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:$e(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function wN(t){let e=ue(t,"Native snapshot omission overflow");if(de(e,oN,"Native snapshot omission overflow"),typeof e.hash!="string"||!Zn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:cr(e.count,"Native snapshot omission overflow count")}}function sr(t,e){let r=ue(t,e);if(de(r,tN,e),typeof r.hash!="string"||!Zn.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let i=$e(r.recordCount,`${e} recordCount`),n=$e(r.storedRecordCount,`${e} storedRecordCount`),a=$e(r.stdoutBytes,`${e} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Md(t){let e=ue(t,"Native Git selection evidence");if(de(e,eN,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=sr(e.stageBefore,"Native Git selection stageBefore"),i=sr(e.combined,"Native Git selection combined"),n=sr(e.stageAfter,"Native Git selection stageAfter"),a=sr(e.finalStageBefore,"Native Git selection finalStageBefore"),o=sr(e.finalCombined,"Native Git selection finalCombined"),s=sr(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Qn(r,n)||!Qn(n,a)||!Qn(i,o)||!Qn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Fd(t,e){let r=ue(t,e);if(de(r,iN,e),typeof r.hash!="string"||!Zn.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let i=$e(r.visitedNodeCount,`${e} visitedNodeCount`),n=$e(r.recordCount,`${e} recordCount`),a=$e(r.storedRecordCount,`${e} storedRecordCount`),o=$e(r.encodedBytes,`${e} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function yN(t){let e=ue(t,"Native physical selection evidence");if(de(e,rN,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Fd(e.before,"Native physical selection before"),i=Fd(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!dN(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(e.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 Wd(t){let e=ue(t,"Native content snapshot manifest");if(de(e,Ky,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!sN.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let w=ue(e.capture,"Native content snapshot capture");if(de(w,Qy,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=w.gitSelection===void 0?void 0:Md(w.gitSelection),S=w.physicalSelection===void 0?void 0:yN(w.physicalSelection),A=null;if(w.projection!==void 0){let G=ue(w.projection,"Native content snapshot projection");if(de(G,Zy,"Native content snapshot projection"),G.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");A={provider:"git",...G.selection===void 0?{}:{selection:Md(G.selection)}}}if(w.provider==="git"){if(S||A)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&&A)throw new Error("Native physical-tree capture cannot combine selection and projection");r=A?{provider:"physical-tree",projection:A}:{provider:"physical-tree",...S?{physicalSelection:S}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=ue(e.limits,"Native content snapshot limits");de(i,Yy,"Native content snapshot limits");let n={maxFiles:cr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:cr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:cr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:cr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:cr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let w=ue(e.policy,"Native snapshot policy");if(de(w,Xy,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=mN({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(vN),s=e.omitted.map(gN),c=$e(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:wN(e.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,P)=>w+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Jy||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,g=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(g!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),m=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...m])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||m.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,N=b?.status==="overflow"||b?.status==="overflow-and-changed",y=b?.status==="changed"||b?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(m.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let x={schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(fN(x)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return x}function NN(t,e){if(!Uy.test(e))throw new Error(`Invalid Native change name: ${e}`);return _s.join(se(t,e),"baseline-manifest.json")}async function zd(t,e){let r=NN(t,e),i=Ie(t,r);await V(i,r);try{let n=await $d({root:i,file:r,maxBytes:Gy,label:"Native baseline snapshot manifest"});return Wd(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var NC,Jy,Gy,Uy,Ky,Yy,Xy,Qy,Zy,eN,tN,rN,iN,nN,aN,oN,sN,cN,lN,Zn,uN,bC,kC,SC,EC,xC,si=E(()=>{"use strict";D();we();Ee();Re();$();Se();Kr();NC={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Jy=1e3,Gy=8*1024*1024,Uy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ky=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Yy=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Xy=new Set(["schema","include","exclude","hash"]),Qy=new Set(["provider","gitSelection","physicalSelection","projection"]),Zy=new Set(["provider","selection"]),eN=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),tN=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),rN=new Set(["schema","status","before","after"]),iN=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),nN=new Set(["path","hash","size","type","gitObjectId"]),aN=new Set(["path","size","type","reason"]),oN=new Set(["ref","hash","count"]),sN=new Set(["change-created","legacy-migration","explicit"]),cN=new Set(["file","directory","other"]),lN=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"]),Zn=/^[a-f0-9]{64}$/u,uN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,bC=64*1024,kC=64*1024,SC={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},EC={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};xC=(1n<<256n)-1n});var ci=E(()=>{"use strict"});var ea=E(()=>{"use strict"});var Jd=E(()=>{"use strict"});var Is=E(()=>{"use strict";ea()});var Gd=E(()=>{"use strict";ea();Is()});var CN,Ud=E(()=>{"use strict";CN=mr(Gt(),1);Zt();rt();St()});var MC,Kd=E(()=>{"use strict";Zt();St();MC=4*1024*1024});function RN(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Yd(t,e){return(...r)=>{let i=PN;if(i===null)return e(...r);let n=RN(`async:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var PN,Xd=E(()=>{"use strict";PN=null});var JC,Qd=E(()=>{"use strict";Xd();Qt();JC=Yd("hookWritePolicy",async t=>(await cs(t))?.hook??{allow_paths:[]})});var Zd=E(()=>{"use strict";ea();Zt();Jd();Gd();rt();Ud();St();Qt();fs();Kd();Qd();ls();Is()});var ef=E(()=>{"use strict";Zd();Yr()});var qP,tf=E(()=>{"use strict";ef();qP=256*1024});var rf=E(()=>{"use strict";tf();ci()});var rR,lr=E(()=>{"use strict";ci();rf();D();Re();rR={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 Ts=E(()=>{"use strict";ci();le();$();lr()});var vR,gR,ta=E(()=>{"use strict";Ze();D();ae();le();$();vR=16*1024,gR=process.platform});import{promises as IN}from"fs";import Rt from"path";function di(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function df(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function fi(t){if(!uf.test(t))throw new Error(`Invalid Native change name: ${t}`)}function BN(t){if(!uf.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function ff(t,e){if(t.length===0||Rt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function VN(t,e){let r=di(t,`spec_changes[${e}]`);if(df(r,$N,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(BN(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"&&ff(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"||!$s.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"||!$s.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 MN(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Ds(t,e){if(df(t,e,At),typeof t.name!="string")throw new Error("Native change name is required");if(fi(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!ON.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!HN.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(VN),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 t.verification_result!="string"||!DN.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&ff(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!MN(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function zn(t){let e=di(t,At);if(e.schema!==st)throw new Error(`Expected ${st}`);return{schema:st,...Ds(e,TN)}}function ui(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function js(t,e,r){if(t===null)return null;let i=typeof t=="string"?LN.exec(t):null;if(!i||i[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function FN(t){if(t==null)return null;if(typeof t!="string"||!$s.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function qN(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Jn(t){let e=di(t,At);if(e.schema!==ot)throw new Error(`Expected ${ot}`);if(ui(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ot} minimum_runtime_version must be 2`);return{schema:ot,minimum_runtime_version:2,revision:ui(e.revision,"Native v2 revision"),...Ds(e,lf)}}function Gn(t){let e=di(t,At);if(e.schema!==at){if(e.schema===st||e.schema===ot){let o=e.schema===st?zn(e):Jn(e);throw new Os(o.name,o.schema)}throw new ut(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=ui(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ut(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=ui(e.revision,"Native revision"),n=Ds(e,jN),a=FN(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:at,minimum_runtime_version:3,revision:i,verification_protocol:qN(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:js(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:js(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:js(e.partial_allowance,"Native partial_allowance","allowances")}}function WN(t){let e=di(t,At);if(e.schema===st){let n=zn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${at}`}}if(e.schema===ot){let n=Jn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${at}`}}if(e.schema!==at){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new ut(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=ui(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new ut(e.schema,r).message};let i=Gn(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function fe(t,e){fi(e);let r=Rt.join(t.changesDir,e);if(!U(t.changesDir,r))throw new Error("Native change path escaped");return r}async function Ls(t,e){let r=se(t,e),i=Rt.join(r,"schema-migration.json");await V(U(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await IN.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function zN(t,e=Rt.dirname(t)){let r=Rt.relative(e,t).split(Rt.sep).join("/"),i=await M({root:e,ref:r,maxBytes:null,includeHash:!1}),n=(0,Hs.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function pf(t,e){let r=Rt.join(fe(t,e),At);await V(t.nativeRoot,r);let i=WN(await zN(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Ls(t,e)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(i.status==="current"&&i.state&&await JN(t,i.state),i)}async function JN(t,e){if(await zd(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}var Hs,cf,TN,lf,jN,$N,ON,HN,DN,At,$s,uf,LN,Os,ut,ra,li,ia,qR,J=E(()=>{"use strict";Hs=mr(Gt(),1);Ze();ae();D();Nt();we();le();$();Se();Bd();si();Ts();ta();Wn();cf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],TN=new Set(cf),lf=new Set([...cf,"minimum_runtime_version","revision"]),jN=new Set([...lf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),$N=new Set(["capability","operation","source","base_hash"]),ON=new Set(["shape","build","verify","archive"]),HN=new Set(["implicit","confirmed"]),DN=new Set(["pending","pass","fail"]),At="comet-state.yaml",$s=/^[a-f0-9]{64}$/u,uf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Os=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"},ut=class extends Error{constructor(r,i){super(r!==at||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"},ra=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"},li=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"},ia=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"},qR=Sn("en")});import{execFileSync as GN}from"node:child_process";function YN(t,e){try{return GN("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:UN,maxBuffer:KN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Bs(t,e,i)}}function pi(t,e){return YN(t,e).trim()}var UN,KN,Bs,hi=E(()=>{"use strict";UN=3e4,KN=8*1024*1024,Bs=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}});var Vs=E(()=>{"use strict";hi();D()});var XR,na=E(()=>{"use strict";XR=["$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("; ")});var Ms=E(()=>{"use strict"});var dt=E(()=>{"use strict"});var Fs=E(()=>{"use strict";na();Ms();dt()});var mi=E(()=>{"use strict"});var aa=E(()=>{"use strict";mi()});var hf=E(()=>{"use strict"});var fA,mf=E(()=>{"use strict";na();fA=8*1024*1024});var vf=E(()=>{"use strict";mf()});var oa,qs=E(()=>{"use strict";hi();Ze();we();Vs();ni();$();oa=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import dr from"node:path";import{promises as gf}from"node:fs";function ib(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native Supervisor parent name: ${t}`);return`comet/supervisor/${t}/integration`}function nb(t,e){return dr.join(rr(t,e),"supervisor")}function wf(t,e){return dr.join(nb(t,e),"state.json")}function yf(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Supervisor state must be an object");let e=t;if(e.schema!==Ws)throw new Error(`Native Supervisor state schema must be ${Ws}`);if(!Number.isSafeInteger(e.stateVersion)||typeof e.stateVersion!="number"||e.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof e.parent!="string"||!e.parent)throw new Error("Native Supervisor state parent is invalid");if(!e.integration||typeof e.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(e.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(_t(e.integration.targetCommit,"Native Supervisor target commit"),_t(e.integration.headCommit,"Native Supervisor integration head commit"),e.integration.checkExecution){let n=e.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");_t(n.candidateCommit,"Native Supervisor integration candidate commit"),_t(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(e.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(e.history))throw new Error("Native Supervisor history is invalid");if(!e.finalVerification||!["pending","passed","failed","incomplete"].includes(e.finalVerification.status)||e.finalVerification.summary!==null&&typeof e.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(e.finalVerification.layers){let n=e.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 e.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 e.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&&_t(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(_t(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 sa(t,e,r={}){try{let i=await gf.readFile(wf(t,e),"utf8"),n=JSON.parse(i);if(yf(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=t;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(()=>(ca(),kf)),{readNativePortableState:l}=await Promise.resolve().then(()=>(Pt(),Es)),u=await l(dr.join(o.changesDir,e,"comet-state.yaml")),d=await s({changeDir:dr.join(o.changesDir,e),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:h})=>h===f.name)&&(f.acceptanceScope=bf(d.contract,f.name),f.contractHash=z("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=t;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Pt(),Es)),s=await o(dr.join(a.changesDir,e,"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 zs(t,e){yf(e),await gf.mkdir(t.changesRuntimeDir,{recursive:!0}),await oe(wf(t,e.parent),e,{containedRoot:t.changesRuntimeDir})}function _t(t,e){if(!rb.test(t))throw new Error(`${e} must be a Git commit`)}function ab(t,e){t.history.push({...e,at:new Date().toISOString()}),t.history.length>256&&t.history.splice(0,t.history.length-256)}function Nf(t){_t(t.targetCommit,"Native Supervisor target commit");let e=new Set(t.contract.children.map(({name:i})=>i)),r=t.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:bf(t.contract,i.name),contractHash:z("comet.native.supervisor-contract.v1",t.contract)}));for(let i of r)for(let n of i.dependsOn)if(!e.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ws,stateVersion:1,parent:t.parent,integration:{branch:t.integrationBranch,worktree:t.integrationWorktree,targetBranch:t.targetBranch,targetCommit:t.targetCommit,headCommit:t.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function bf(t,e){let r=t.children.find(i=>i.name===e);return r.covers.length>0?r.covers.map(i=>({id:i,source:t.acceptance_index?.[i]?.source??"brief.md",text:t.acceptance_index?.[i]?.text??i})):[{id:`child:${e}`,source:"children.yaml",text:r.summary??e}]}async function Js(t){let e=ib(t.parent),r=Gr(t.paths.projectRoot,e);if(!r)return null;let i=Gr(t.paths.projectRoot,t.targetBranch);if(!i)return null;let n=Kt(t.paths.projectRoot).map(o=>dr.resolve(o)).find(o=>Pe(o).currentBranch===e);if(!n)return null;let a=Nf({parent:t.parent,targetBranch:t.targetBranch,targetCommit:i,integrationBranch:e,integrationWorktree:n,contract:t.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 ab(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Gs(t){let e=t.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=t.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&&[...t.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:e?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:e,parentBranch:t.integration.branch,children:r,readyChildren:e?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:e&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Ws,rb,Us=E(()=>{"use strict";Vs();D();Z();Fs();aa();le();$();we();Ze();hf();hi();vf();qs();Ws="comet.native.supervisor.v2",rb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var kf={};vc(kf,{NATIVE_CHILDREN_FILE:()=>Ks,NATIVE_CHILDREN_SCHEMA:()=>It,NATIVE_CHILDREN_SCHEMA_V2:()=>Zs,NATIVE_CHILDREN_V2_SCHEMA:()=>Tt,findNativeV1SupervisorParents:()=>jf,hasNativeSupervisorShapeIntent:()=>If,hashNativeParentContract:()=>rc,inspectNativeChildren:()=>vi,nativeChildrenAcceptanceValidation:()=>ec,nativeChildrenIndexDrift:()=>Af,parseNativeChildrenContract:()=>_f,readNativeChildrenContract:()=>da,readNativeSupervisorShapeIntent:()=>tc});import{promises as Xs}from"node:fs";import te from"node:path";function ua(t,e,r=""){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object${r}`);return t}function la(t,e,r){let i=Object.keys(t).filter(a=>!e.has(a)),n=[...e].filter(a=>!(a in t));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...e].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Ef(t,e){if(!Array.isArray(t)||!t.every(r=>typeof r=="string"))throw new Error(`${e} must be an array of strings`);return[...new Set(t)].sort((r,i)=>r.localeCompare(i,"en"))}function Ys(t,e){let r=te.normalize(te.resolve(t)),i=te.normalize(te.resolve(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function db(t){let e=new Map(t.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 e.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of t)n(a.name)}function xf(t,e,r=e){let i=new Set(e);for(let o of t){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(t.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 Af(t,e,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(t.schema===Zs&&t.acceptance_index){let n=r.requiredAcceptanceIds??e??[],a=r.allowedAcceptanceIds??n,o=Object.keys(t.acceptance_index);i.missing=n.filter(l=>!(l in t.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 u=s.get(l),d=t.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of t.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!Cf(t.children,l)),Pf(i)?i:null}if(t.schema===It&&e){let n=new Set(e);for(let a of t.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=e.filter(a=>!Cf(t.children,a)),Pf(i)?i:null}return null}function Cf(t,e){return t.some(r=>r.covers.includes(e))}function Pf(t){return t.missing.length>0||t.extra.length>0||t.mismatched.length>0||t.uncovered.length>0||t.unknownCovers.length>0}function ec(t){let e=new Set(t.acceptance.map(({id:n})=>n)),r=new Set(t.acceptance.filter(({source:n})=>n===t.brief).map(({id:n})=>n)),i=new Set(r);for(let n of t.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)e.has(a)&&i.add(a);if(t.loop.stage==="repairing"&&t.verification_result==="fail"){let n=[...t.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:t.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function fb(t){let e=ua(t,"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(e)){let a=ua(n,`Native children acceptance_index.${i}`);if(la(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 pb(t,e,r){let i=r.requiredAcceptanceIds??e??[],n=r.allowedAcceptanceIds??i,a=Object.keys(t),o=i.filter(l=>!(l in t)),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 u=c.get(l);if(!u)continue;let d=t[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function _f(t,e,r={}){let i=(0,Qs.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ua(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==It&&a!==Tt)throw la(n,Sf,"Native children contract"),new Error(`Native children schema must be ${It} or ${Tt}`);let o=a===It?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(la(n,o==="indexed-v2"?sb:Sf,"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((f,h)=>{let g=ua(f,`Native child ${h}`);if(la(g,o==="indexed-v2"?ub:o==="summary-v2"?lb:cb,`Native ${s} child fields (child ${h})`),typeof g.name!="string"||!ob.test(g.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof g.summary!="string"||g.summary.trim().length===0)throw new Error(`Native child ${g.name} summary must be a non-empty string`);if(g.summary.length>2e3)throw new Error(`Native child ${g.name} summary exceeds 2000 characters`)}return{name:g.name,summary:p?g.summary:null,depends_on:Ef(g.depends_on,`Native child ${g.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Ef(g.covers,`Native child ${g.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(g=>!u.has(g));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}db(c);let d=r.policy==="advisory";if(a===Zs){if(o==="indexed-v2"){let f=fb(n.acceptance_index);d||pb(f,e,r);let h=Object.keys(f);return d||xf(c,h,h),{schema:Tt,acceptance_index:f,children:c}}return{schema:Tt,children:c}}return e&&!d&&xf(c,e),{schema:It,children:c}}async function da(t){let e=te.join(t.changeDir,Ks);try{await Xs.lstat(e)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await M({root:t.changeDir,ref:Ks}),i=t.policy==="advisory",n=i?{...t.validation,policy:"advisory"}:t.validation??{},a=_f(r.text,t.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Af(a,t.acceptanceIds,t.validation??{}):null}}function hb(t){let e=/^#\s+(?:Decisions|决策)\s*$/imu.exec(t);if(!e||e.index===void 0)return null;let r=t.slice(e.index+e[0].length);return r.split(/^#\s+/mu,1)[0]??r}function If(t){let e=hb(t);if(!e||!/Supervisor\s+Change/iu.test(e))return!1;let r=e.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=e.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function tc(t){try{let e=await M({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});return If(e.text)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function rc(t){return z("comet.native.parent-contract.v1",{acceptance:t.acceptance.map(({id:e,source:r,text:i})=>({id:e,source:r,text:i})),children:t.children})}async function Tf(t){let e=Kt(t.projectRoot);e.some(i=>Ys(i,t.projectRoot))||e.push(t.projectRoot);let r=[];for(let i of[...new Set(e.map(n=>te.resolve(n)))]){let n=await Te(i);n&&r.push({projectRoot:i,paths:await xt(i,n.native.artifact_root),parent:Ys(i,t.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:t.projectRoot,paths:t,parent:!0}),r}async function jf(t){let e=await Tf(t.paths),r=[],i=[],n=new Map;for(let a of e){let o;try{o=await Xs.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===t.childName)continue;let c=te.join(a.paths.changesDir,s.name),l;try{l=await Ve(te.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await da({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==It||u.contract.children.some(({name:d})=>d===t.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=t.targetBranch===null?[]:o.filter(({state:h})=>h.workspace.target_branch===t.targetBranch);if(t.targetBranch===null){i.push(`Native Supervisor Child ${t.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:h,state:g})=>Pe(h.projectRoot).currentBranch===g.workspace.change_branch);if(!c){let h=o.find(({state:g})=>g.workspace.target_branch!==t.targetBranch);if(h)i.push(`Native Supervisor parent ${a} targets ${h.state.workspace.target_branch??"(missing)"}, not ${t.targetBranch}`);else{let g=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${g.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await vi({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let h=f.children.filter(({status:g})=>g!=="done").map(({name:g,status:p,message:v})=>`${g}=${p}${v?` (${v})`:""}`).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 ${t.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${t.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 ${t.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function mb(t,e){let r=te.join(t.paths.changesDir,e,"comet-state.yaml");try{return await Ve(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function vb(t,e){let r;try{r=await Xs.readdir(t.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()||![...e].some(o=>n.name.endsWith(`-${o}`))))try{let o=te.join(t.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ve(o);e.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function gb(t,e,r){let i=te.relative(t.projectRoot,e);if(!i||i===".."||i.startsWith(`..${te.sep}`))return null;let n=i.split(te.sep).join("/");try{let a=(0,Qs.parseDocument)(pi(t.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Ne(a.toJS({mapAsMap:!1}))}catch{return null}}function wb(t,e,r){return t.workspace.isolation!=="worktree"||t.workspace.target_branch!==r||t.workspace.finish!==null&&t.workspace.finish!=="merge"?{kind:"blocked",phase:t.phase,projectRoot:e.projectRoot,message:`Native child ${t.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:t.status==="blocked"||t.status==="await-user"?{kind:"blocked",phase:t.phase,projectRoot:e.projectRoot,message:t.blockers[0]?.reason.text??`Native child ${t.name} requires user resolution`}:{kind:"active",phase:t.phase,projectRoot:e.projectRoot,message:null}}function Rf(t,e){return t.status==="done"&&t.archived&&t.workspace.finish==="merge"&&t.workspace.target_branch===e}async function vi(t){let e=te.join(t.paths.changesDir,t.state.name),r=await tc(e),i=null,n;try{n=await da({changeDir:e,validation:ec(t.state),...t.state.acceptance.length>0?{acceptanceIds:t.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"})}catch(m){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${m.message}`,n=null}if(!n){let m=await sa(t.paths,t.state.name,{diagnostics:!0});if(m){let b=Gs(m);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(N=>({...N,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return t.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:t.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:t.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=rc({acceptance:t.state.acceptance,children:n.contract}),o=t.state.workspace.change_branch,s=t.state.phase!=="shape"&&t.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Tt){let m=await sa(t.paths,t.state.name,{diagnostics:!0});if(!m){let y=t.state.workspace.change_branch??t.state.workspace.target_branch;if(y){let x=await Js({paths:t.paths,parent:t.state.name,targetBranch:y,contract:n.contract});x&&(m=x,await zs(t.paths,x))}}if(m){let y=Gs(m);return t.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let b=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==y.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await Tf(t.paths),l=new Set(n.contract.children.map(({name:m})=>m)),u=new Map,d=new Map;for(let m of c){let b=m.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await vb(m,l)){let y={...N,source:m,committedState:gb(m,N.file,b)};u.set(N.state.name,[...u.get(N.state.name)??[],y])}for(let N of l){let y=await mb(m,N);y&&d.set(N,[...d.get(N)??[],{source:m,state:y}])}}let f=new Map;for(let m of n.contract.children){let b=(u.get(m.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===m.name&&Rf(w,o));if(b){f.set(m.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let N=u.get(m.name)?.[0];if(N){f.set(m.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=d.get(m.name)??[];y.length>1?f.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):y[0]&&f.set(m.name,wb(y[0].state,y[0].source,o))}let h=new Map(n.contract.children.map(m=>[m.name,m])),g=new Map,p=m=>{let b=g.get(m);if(b)return b;let N=h.get(m),x=N.depends_on.map(p).every(({status:pe})=>pe==="done"),w=f.get(m),P=w?.kind==="active"&&x?N.depends_on.filter(pe=>!(u.get(pe)??[]).some(({source:O,committedState:hr})=>Ys(O.projectRoot,w.projectRoot)&&hr?.name===pe&&Rf(hr,o))):[],S,A=w?.message??null;w?.kind==="done"?(S=x?"done":"blocked",x||(A=`Native child ${m} was merged before its dependencies`)):w?.kind==="active"?(S=x&&P.length===0?"active":"blocked",x?P.length>0&&(A=`Native child ${m} does not include merged dependencies: ${P.join(", ")}`):A=`Native child ${m} started before its dependencies merged`):w?.kind==="blocked"?S="blocked":(S=s&&x?"ready":"pending",s||(A="Parent Shape confirmation is required"));let G={name:m,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:S,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:A};return g.set(m,G),G},v=n.contract.children.map(({name:m})=>p(m));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:v.every(({status:m})=>m==="done")}}var Qs,Ks,It,Tt,Zs,ob,Sf,sb,cb,lb,ub,ca=E(()=>{"use strict";Qs=mr(Gt(),1);Ze();hi();ae();Z();we();$();Pt();Us();Ks="children.yaml",It="comet.native.children.v1",Tt="comet.native.children.v2",Zs=Tt,ob=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Sf=new Set(["schema","children"]),sb=new Set(["schema","acceptance_index","children"]),cb=new Set(["name","depends_on","covers"]),lb=new Set(["name","summary","depends_on"]),ub=new Set(["name","depends_on","covers"])});var Of,fr=E(()=>{"use strict";Z();si();Of=1024*1024});var fa=E(()=>{"use strict";Z();dt();Kr();fr()});var Qf,Lb,Bb,Vb,BT,Mb,VT,ac=E(()=>{"use strict";Z();Qf="scoped-text-safety",Lb=1,Bb=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Vb="comet.native.checker-policy.v1",BT=z(Vb,{policy:Qf,version:Lb,limits:Bb,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Mb=["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"],VT=new Set(Mb)});var pa=E(()=>{"use strict";Z();ac();dt()});var qb,ij,pr=E(()=>{"use strict";D();$();Re();fr();fa();pa();qb=Of,ij=3*qb});J();ae();ca();ae();Bn();Z();var u_={maxAcceptanceCriteria:Ed.maxCriteria};var jt={maxSpecs:64,maxFileBytes:Nn,maxTotalBytes:4*1024*1024};import{promises as qf}from"fs";import Wf from"path";Nt();J();ae();Ee();$();var yb=["outcome","scope","nonGoals","acceptanceExamples"],k_=[...yb,"constraints","decisions","openQuestions","verificationExpectations"];ae();J();D();J();Ee();$();Se();Kr();dt();var T_={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};le();ci();D();J();Ee();ni();le();$();Se();dt();Z();Z();fa();fr();Ee();var Df={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:[]},bb=ee("comet-native-runtime:v3:scope-reopen"),oI=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];lr();Ee();lr();Ee();Ts();Wn();var Mf=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],BI=new Set(Mf),Cb=new Set([...Mf,"minimum_runtime_version","revision"]),VI=new Set([...Cb,"operation"]),MI=512*1024,Pb=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),FI=new Set([...Pb,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);lr();J();Ee();le();Se();dt();$();var zf=jt.maxSpecs*4;async function Rb(t,e){let r=Wf.join(fe(t,e),"specs"),i;try{i=await Ps({root:t.nativeRoot,directory:r,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await qf.opendir(r);try{for await(let s of o){if(a+=1,a>zf)throw new Error(`Native proposed specs directory exceeds ${zf} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;fi(s.name);let c=Wf.join(r,s.name,"spec.md");await V(t.nativeRoot,c);let l;try{l=await qf.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>jt.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await i.verify(),n.sort()}async function Uf(t,e){let r=fe(t,e),i={},n=0;for(let a of await Rb(t,e)){let o=await M({root:r,ref:`specs/${a}/spec.md`,maxBytes:jt.maxFileBytes});if(n+=o.size,n>jt.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");i[a]=o.text}return i}ai();function Me(t,e,r){return t.language==="zh-CN"?r:e}function Ab(t,e){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(t.phase==="shape"&&t.status==="await-user"&&t.loop.next_action==="confirm-shape")return t.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(e&&t.phase==="shape"&&t.status==="active")return{required:!0,message:Me(t,"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:Me(t,"Reply A or B","回复 A 或 B"),agentInstruction:Me(t,"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(t.phase==="verify"&&t.status==="active"&&t.loop.stage==="verify-ready"&&t.loop.next_action!=="await-verifier-result")return r(Me(t,"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(t.phase==="verify"&&t.status==="active"&&t.loop.next_action==="await-verifier-result")return r(Me(t,"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(t.status==="blocked"&&t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return t.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(t.phase==="verify"&&t.status==="await-user"&&t.verification?.assurance==="semantic-verification-unavailable")return t.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(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="resolve-verifier-blocker")return t.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(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="await-user"){let n=(t.loop.stop_reason??(t.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 t.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(Me(t,"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 _b(t){let e=t.workspace.change_branch??"<change-branch>",r=t.workspace.target_branch??"<target-branch>";return t.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${e},目标分支为 ${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 ${e} 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 Ib(t){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:t.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",t.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:Me(t,a[1],a[0])})),{name:"defer-archive",stateVersion:t.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Me(t,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Yf(t){return["comet","native","next",t.change,"--summary","<summary>",t.flag,"--expected-state-version",String(t.stateVersion),"--expected-action",t.action]}function Ot(t,e){return{name:t,flag:e,valueKind:"text",required:!0,template:null}}function Tb(t,e){return{name:t,flag:e,valueKind:"confirmation",required:!0,template:null}}function Kf(t,e,r){return{name:t,flag:e,valueKind:"choice",required:!0,template:null,choices:[...r]}}function jb(t){return t?.coordinationChoiceRequired===!0||t?.schema==="comet.native.children.v2"&&t.children.length>=2}function $b(t){return["comet","native","next",t.change,"--summary","<summary>",...t.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(t.stateVersion),"--expected-action","prepare-shape-confirmation"]}function ft(t){return{name:t.name,stateVersion:t.stateVersion,expectedAction:t.expectedAction,commandArgs:Yf({change:t.change,stateVersion:t.stateVersion,action:t.expectedAction,flag:t.flag}),requiredInputs:["summary",t.confirmationInput],inputOptions:[Ot("summary","--summary"),Tb(t.name,t.flag)]}}function nc(t){return[ft({name:"revise-implementation",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),ft({name:"revise-requirements",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Xf(t,e,r={}){let i=jb(e)&&t.coordination_mode===void 0,n=Ab(t,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(t.status==="await-user")return t.phase==="shape"&&t.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"confirm-shape",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"accept-result",change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...nc({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"retry-verifier",change:t.name,stateVersion:t.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),ft({name:"confirm-verifier-unavailable",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"resolve-verifier-blocker",change:t.name,stateVersion:t.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...nc({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:nc({change:t.name,stateVersion:t.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(t.status==="blocked"){let s=t.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Yf({change:t.name,stateVersion:t.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(t.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:$b({change:t.name,stateVersion:t.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Kf("coordination-mode","--coordination-mode",xd)]:[]],runnerAction:o("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(e.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",t.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=e.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.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=e.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=e.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>",...t.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[Ot("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.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(t.phase==="verify"){let s=t.loop.next_action==="await-verifier-result",c=!!t.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} ${Me(t,"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",t.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:t.loop.iteration,attempt:t.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.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:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(t.phase==="archive"&&t.status==="active"&&t.loop.stage==="archive-ready"&&!t.archived){let s=r.archiveMode??"archive-ready",l=t.workspace.isolation!=="current"&&t.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",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Kf("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Ib(t)],userCommunication:_b(t),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--dry-run"],requiredInputs:[],commandAlternatives:[ft({name:"revise-requirements",change:t.name,stateVersion:t.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}Ze();D();import{promises as zb}from"node:fs";import Zf from"node:path";ae();Z();ca();Us();J();Fs();Pt();qn();mi();aa();D();ai();le();gs();Pt();xs();qn();mi();aa();D();Nt();mi();$();Nt();pr();we();var Jb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Gb="comet-state.yaml";var u$=Sn("en");function oc(t,e){if(!Jb.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=Zf.join(t.changesDir,e);if(!U(t.changesDir,r))throw new Error("Native change path escaped");return r}function ep(t,e){return Zf.join(oc(t,e),Gb)}async function sc(t,e){try{let r=await zb.readFile(ep(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function cc(t,e){return Ve(ep(t,e))}ti();import wi from"path";import{realpathSync as Sk}from"fs";Ze();var Fe={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function tp(t){return t?t.command?`${Fe.next} ${t.command}`:t.ask_user?`${Fe.next} ${t.ask_user}`:null:null}function rp(t,e){let r=[t.summary],i=tp(t.next);return i&&r.push(i),t.user_message&&r.push("",Fe.relay,t.user_message),e!==void 0&&r.push("",Fe.details,JSON.stringify(e,null,2)),`${r.join(`
148
+ ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function As(t,e,r){let i=new Set(e),n=[...e];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=t[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 hN(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Vd(t){let e=Ln(t,"Native snapshot pattern"),r=[];for(let i=0;i<e.length;i+=1){let n=e[i];n==="*"&&e[i+1]==="*"?(i+=1,e[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?hN(n):void 0;if(a&&!a())return!1;let o=As(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 u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=As(r,c,a),o===null||o.size===0)return!1}return As(r,o,a)?.has(r.length)??!1}}function mN(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>Ln(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>Ln(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let i=pN(e,r);if("hash"in t&&t.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:i},includeMatchers:e.map(Vd),excludeMatchers:r.map(Vd),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 ue(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function de(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function cr(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Oe(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function qd(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=_s.posix.normalize(t);if(r!==t||_s.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function vN(t,e){let r=ue(t,`Native snapshot entry ${e}`);de(r,nN,`Native snapshot entry ${e}`);let i=qd(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!Zn.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:i,hash:r.hash,size:Oe(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!uN.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function gN(t,e){let r=ue(t,`Native snapshot omission ${e}`);if(de(r,aN,`Native snapshot omission ${e}`),!cN.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!lN.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:qd(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:Oe(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function wN(t){let e=ue(t,"Native snapshot omission overflow");if(de(e,oN,"Native snapshot omission overflow"),typeof e.hash!="string"||!Zn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:cr(e.count,"Native snapshot omission overflow count")}}function sr(t,e){let r=ue(t,e);if(de(r,tN,e),typeof r.hash!="string"||!Zn.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let i=Oe(r.recordCount,`${e} recordCount`),n=Oe(r.storedRecordCount,`${e} storedRecordCount`),a=Oe(r.stdoutBytes,`${e} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Md(t){let e=ue(t,"Native Git selection evidence");if(de(e,eN,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=sr(e.stageBefore,"Native Git selection stageBefore"),i=sr(e.combined,"Native Git selection combined"),n=sr(e.stageAfter,"Native Git selection stageAfter"),a=sr(e.finalStageBefore,"Native Git selection finalStageBefore"),o=sr(e.finalCombined,"Native Git selection finalCombined"),s=sr(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Qn(r,n)||!Qn(n,a)||!Qn(i,o)||!Qn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Fd(t,e){let r=ue(t,e);if(de(r,iN,e),typeof r.hash!="string"||!Zn.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let i=Oe(r.visitedNodeCount,`${e} visitedNodeCount`),n=Oe(r.recordCount,`${e} recordCount`),a=Oe(r.storedRecordCount,`${e} storedRecordCount`),o=Oe(r.encodedBytes,`${e} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function yN(t){let e=ue(t,"Native physical selection evidence");if(de(e,rN,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Fd(e.before,"Native physical selection before"),i=Fd(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!dN(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(e.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 Wd(t){let e=ue(t,"Native content snapshot manifest");if(de(e,Ky,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!sN.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let w=ue(e.capture,"Native content snapshot capture");if(de(w,Qy,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=w.gitSelection===void 0?void 0:Md(w.gitSelection),S=w.physicalSelection===void 0?void 0:yN(w.physicalSelection),A=null;if(w.projection!==void 0){let G=ue(w.projection,"Native content snapshot projection");if(de(G,Zy,"Native content snapshot projection"),G.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");A={provider:"git",...G.selection===void 0?{}:{selection:Md(G.selection)}}}if(w.provider==="git"){if(S||A)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&&A)throw new Error("Native physical-tree capture cannot combine selection and projection");r=A?{provider:"physical-tree",projection:A}:{provider:"physical-tree",...S?{physicalSelection:S}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=ue(e.limits,"Native content snapshot limits");de(i,Yy,"Native content snapshot limits");let n={maxFiles:cr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:cr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:cr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:cr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:cr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let w=ue(e.policy,"Native snapshot policy");if(de(w,Xy,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=mN({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(vN),s=e.omitted.map(gN),c=Oe(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:wN(e.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,P)=>w+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Jy||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,g=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(g!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),m=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...m])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||m.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,N=b?.status==="overflow"||b?.status==="overflow-and-changed",y=b?.status==="changed"||b?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(m.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let x={schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(fN(x)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return x}function NN(t,e){if(!Uy.test(e))throw new Error(`Invalid Native change name: ${e}`);return _s.join(se(t,e),"baseline-manifest.json")}async function zd(t,e){let r=NN(t,e),i=Te(t,r);await V(i,r);try{let n=await $d({root:i,file:r,maxBytes:Gy,label:"Native baseline snapshot manifest"});return Wd(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var NC,Jy,Gy,Uy,Ky,Yy,Xy,Qy,Zy,eN,tN,rN,iN,nN,aN,oN,sN,cN,lN,Zn,uN,bC,kC,SC,EC,xC,si=E(()=>{"use strict";D();ye();xe();Ae();$();Ee();Kr();NC={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Jy=1e3,Gy=8*1024*1024,Uy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ky=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Yy=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Xy=new Set(["schema","include","exclude","hash"]),Qy=new Set(["provider","gitSelection","physicalSelection","projection"]),Zy=new Set(["provider","selection"]),eN=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),tN=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),rN=new Set(["schema","status","before","after"]),iN=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),nN=new Set(["path","hash","size","type","gitObjectId"]),aN=new Set(["path","size","type","reason"]),oN=new Set(["ref","hash","count"]),sN=new Set(["change-created","legacy-migration","explicit"]),cN=new Set(["file","directory","other"]),lN=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"]),Zn=/^[a-f0-9]{64}$/u,uN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,bC=64*1024,kC=64*1024,SC={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},EC={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};xC=(1n<<256n)-1n});var ci=E(()=>{"use strict"});var ea=E(()=>{"use strict"});var Jd=E(()=>{"use strict"});var Is=E(()=>{"use strict";ea()});var Gd=E(()=>{"use strict";ea();Is()});var CN,Ud=E(()=>{"use strict";CN=mr(Gt(),1);Zt();rt();St()});var MC,Kd=E(()=>{"use strict";Zt();St();MC=4*1024*1024});function RN(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Yd(t,e){return(...r)=>{let i=PN;if(i===null)return e(...r);let n=RN(`async:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var PN,Xd=E(()=>{"use strict";PN=null});var JC,Qd=E(()=>{"use strict";Xd();Qt();JC=Yd("hookWritePolicy",async t=>(await cs(t))?.hook??{allow_paths:[]})});var Zd=E(()=>{"use strict";ea();Zt();Jd();Gd();rt();Ud();St();Qt();fs();Kd();Qd();ls();Is()});var ef=E(()=>{"use strict";Zd();Yr()});var qP,tf=E(()=>{"use strict";ef();qP=256*1024});var rf=E(()=>{"use strict";tf();ci()});var rR,lr=E(()=>{"use strict";ci();rf();D();Ae();rR={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 Ts=E(()=>{"use strict";ci();le();$();lr()});var vR,gR,ta=E(()=>{"use strict";Ze();D();ae();le();$();vR=16*1024,gR=process.platform});import{promises as IN}from"fs";import Rt from"path";function di(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function df(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function fi(t){if(!uf.test(t))throw new Error(`Invalid Native change name: ${t}`)}function BN(t){if(!uf.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function ff(t,e){if(t.length===0||Rt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function VN(t,e){let r=di(t,`spec_changes[${e}]`);if(df(r,$N,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(BN(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"&&ff(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"||!$s.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"||!$s.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 MN(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Ds(t,e){if(df(t,e,At),typeof t.name!="string")throw new Error("Native change name is required");if(fi(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!ON.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!HN.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(VN),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 t.verification_result!="string"||!DN.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&ff(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!MN(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function zn(t){let e=di(t,At);if(e.schema!==st)throw new Error(`Expected ${st}`);return{schema:st,...Ds(e,TN)}}function ui(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function js(t,e,r){if(t===null)return null;let i=typeof t=="string"?LN.exec(t):null;if(!i||i[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function FN(t){if(t==null)return null;if(typeof t!="string"||!$s.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function qN(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Jn(t){let e=di(t,At);if(e.schema!==ot)throw new Error(`Expected ${ot}`);if(ui(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ot} minimum_runtime_version must be 2`);return{schema:ot,minimum_runtime_version:2,revision:ui(e.revision,"Native v2 revision"),...Ds(e,lf)}}function Gn(t){let e=di(t,At);if(e.schema!==at){if(e.schema===st||e.schema===ot){let o=e.schema===st?zn(e):Jn(e);throw new Os(o.name,o.schema)}throw new ut(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=ui(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ut(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=ui(e.revision,"Native revision"),n=Ds(e,jN),a=FN(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:at,minimum_runtime_version:3,revision:i,verification_protocol:qN(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:js(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:js(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:js(e.partial_allowance,"Native partial_allowance","allowances")}}function WN(t){let e=di(t,At);if(e.schema===st){let n=zn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${at}`}}if(e.schema===ot){let n=Jn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${at}`}}if(e.schema!==at){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new ut(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=ui(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new ut(e.schema,r).message};let i=Gn(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function fe(t,e){fi(e);let r=Rt.join(t.changesDir,e);if(!U(t.changesDir,r))throw new Error("Native change path escaped");return r}async function Ls(t,e){let r=se(t,e),i=Rt.join(r,"schema-migration.json");await V(U(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await IN.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function zN(t,e=Rt.dirname(t)){let r=Rt.relative(e,t).split(Rt.sep).join("/"),i=await M({root:e,ref:r,maxBytes:null,includeHash:!1}),n=(0,Hs.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function pf(t,e){let r=Rt.join(fe(t,e),At);await V(t.nativeRoot,r);let i=WN(await zN(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Ls(t,e)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(i.status==="current"&&i.state&&await JN(t,i.state),i)}async function JN(t,e){if(await zd(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}var Hs,cf,TN,lf,jN,$N,ON,HN,DN,At,$s,uf,LN,Os,ut,ra,li,ia,qR,J=E(()=>{"use strict";Hs=mr(Gt(),1);Ze();ae();D();Nt();ye();le();$();Ee();Bd();si();Ts();ta();Wn();cf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],TN=new Set(cf),lf=new Set([...cf,"minimum_runtime_version","revision"]),jN=new Set([...lf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),$N=new Set(["capability","operation","source","base_hash"]),ON=new Set(["shape","build","verify","archive"]),HN=new Set(["implicit","confirmed"]),DN=new Set(["pending","pass","fail"]),At="comet-state.yaml",$s=/^[a-f0-9]{64}$/u,uf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Os=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"},ut=class extends Error{constructor(r,i){super(r!==at||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"},ra=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"},li=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"},ia=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"},qR=Sn("en")});import{execFileSync as GN}from"node:child_process";function YN(t,e){try{return GN("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:UN,maxBuffer:KN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Bs(t,e,i)}}function pi(t,e){return YN(t,e).trim()}var UN,KN,Bs,hi=E(()=>{"use strict";UN=3e4,KN=8*1024*1024,Bs=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}});var Vs=E(()=>{"use strict";hi();D()});var XR,na=E(()=>{"use strict";XR=["$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("; ")});var Ms=E(()=>{"use strict"});var dt=E(()=>{"use strict"});var Fs=E(()=>{"use strict";na();Ms();dt()});var mi=E(()=>{"use strict"});var aa=E(()=>{"use strict";mi()});var hf=E(()=>{"use strict"});var fA,mf=E(()=>{"use strict";na();fA=8*1024*1024});var vf=E(()=>{"use strict";mf()});var oa,qs=E(()=>{"use strict";hi();Ze();ye();Vs();ni();$();oa=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import dr from"node:path";import{promises as gf}from"node:fs";function ib(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native Supervisor parent name: ${t}`);return`comet/supervisor/${t}/integration`}function nb(t,e){return dr.join(rr(t,e),"supervisor")}function wf(t,e){return dr.join(nb(t,e),"state.json")}function yf(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Supervisor state must be an object");let e=t;if(e.schema!==Ws)throw new Error(`Native Supervisor state schema must be ${Ws}`);if(!Number.isSafeInteger(e.stateVersion)||typeof e.stateVersion!="number"||e.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof e.parent!="string"||!e.parent)throw new Error("Native Supervisor state parent is invalid");if(!e.integration||typeof e.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(e.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(_t(e.integration.targetCommit,"Native Supervisor target commit"),_t(e.integration.headCommit,"Native Supervisor integration head commit"),e.integration.checkExecution){let n=e.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");_t(n.candidateCommit,"Native Supervisor integration candidate commit"),_t(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(e.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(e.history))throw new Error("Native Supervisor history is invalid");if(!e.finalVerification||!["pending","passed","failed","incomplete"].includes(e.finalVerification.status)||e.finalVerification.summary!==null&&typeof e.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(e.finalVerification.layers){let n=e.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 e.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 e.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&&_t(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(_t(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 sa(t,e,r={}){try{let i=await gf.readFile(wf(t,e),"utf8"),n=JSON.parse(i);if(yf(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=t;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(()=>(ca(),kf)),{readNativePortableState:l}=await Promise.resolve().then(()=>(Pt(),Es)),u=await l(dr.join(o.changesDir,e,"comet-state.yaml")),d=await s({changeDir:dr.join(o.changesDir,e),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:h})=>h===f.name)&&(f.acceptanceScope=bf(d.contract,f.name),f.contractHash=z("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=t;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Pt(),Es)),s=await o(dr.join(a.changesDir,e,"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 zs(t,e){yf(e),await gf.mkdir(t.changesRuntimeDir,{recursive:!0}),await oe(wf(t,e.parent),e,{containedRoot:t.changesRuntimeDir})}function _t(t,e){if(!rb.test(t))throw new Error(`${e} must be a Git commit`)}function ab(t,e){t.history.push({...e,at:new Date().toISOString()}),t.history.length>256&&t.history.splice(0,t.history.length-256)}function Nf(t){_t(t.targetCommit,"Native Supervisor target commit");let e=new Set(t.contract.children.map(({name:i})=>i)),r=t.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:bf(t.contract,i.name),contractHash:z("comet.native.supervisor-contract.v1",t.contract)}));for(let i of r)for(let n of i.dependsOn)if(!e.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ws,stateVersion:1,parent:t.parent,integration:{branch:t.integrationBranch,worktree:t.integrationWorktree,targetBranch:t.targetBranch,targetCommit:t.targetCommit,headCommit:t.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function bf(t,e){let r=t.children.find(i=>i.name===e);return r.covers.length>0?r.covers.map(i=>({id:i,source:t.acceptance_index?.[i]?.source??"brief.md",text:t.acceptance_index?.[i]?.text??i})):[{id:`child:${e}`,source:"children.yaml",text:r.summary??e}]}async function Js(t){let e=ib(t.parent),r=Gr(t.paths.projectRoot,e);if(!r)return null;let i=Gr(t.paths.projectRoot,t.targetBranch);if(!i)return null;let n=Kt(t.paths.projectRoot).map(o=>dr.resolve(o)).find(o=>Re(o).currentBranch===e);if(!n)return null;let a=Nf({parent:t.parent,targetBranch:t.targetBranch,targetCommit:i,integrationBranch:e,integrationWorktree:n,contract:t.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 ab(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Gs(t){let e=t.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=t.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&&[...t.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:e?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:e,parentBranch:t.integration.branch,children:r,readyChildren:e?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:e&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Ws,rb,Us=E(()=>{"use strict";Vs();D();Z();Fs();aa();le();$();ye();Ze();hf();hi();vf();qs();Ws="comet.native.supervisor.v2",rb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var kf={};vc(kf,{NATIVE_CHILDREN_FILE:()=>Ks,NATIVE_CHILDREN_SCHEMA:()=>It,NATIVE_CHILDREN_SCHEMA_V2:()=>Zs,NATIVE_CHILDREN_V2_SCHEMA:()=>Tt,findNativeV1SupervisorParents:()=>jf,hasNativeSupervisorShapeIntent:()=>If,hashNativeParentContract:()=>rc,inspectNativeChildren:()=>vi,nativeChildrenAcceptanceValidation:()=>ec,nativeChildrenIndexDrift:()=>Af,parseNativeChildrenContract:()=>_f,readNativeChildrenContract:()=>da,readNativeSupervisorShapeIntent:()=>tc});import{promises as Xs}from"node:fs";import te from"node:path";function ua(t,e,r=""){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object${r}`);return t}function la(t,e,r){let i=Object.keys(t).filter(a=>!e.has(a)),n=[...e].filter(a=>!(a in t));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...e].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Ef(t,e){if(!Array.isArray(t)||!t.every(r=>typeof r=="string"))throw new Error(`${e} must be an array of strings`);return[...new Set(t)].sort((r,i)=>r.localeCompare(i,"en"))}function Ys(t,e){let r=te.normalize(te.resolve(t)),i=te.normalize(te.resolve(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function db(t){let e=new Map(t.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 e.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of t)n(a.name)}function xf(t,e,r=e){let i=new Set(e);for(let o of t){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(t.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 Af(t,e,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(t.schema===Zs&&t.acceptance_index){let n=r.requiredAcceptanceIds??e??[],a=r.allowedAcceptanceIds??n,o=Object.keys(t.acceptance_index);i.missing=n.filter(l=>!(l in t.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 u=s.get(l),d=t.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of t.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!Cf(t.children,l)),Pf(i)?i:null}if(t.schema===It&&e){let n=new Set(e);for(let a of t.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=e.filter(a=>!Cf(t.children,a)),Pf(i)?i:null}return null}function Cf(t,e){return t.some(r=>r.covers.includes(e))}function Pf(t){return t.missing.length>0||t.extra.length>0||t.mismatched.length>0||t.uncovered.length>0||t.unknownCovers.length>0}function ec(t){let e=new Set(t.acceptance.map(({id:n})=>n)),r=new Set(t.acceptance.filter(({source:n})=>n===t.brief).map(({id:n})=>n)),i=new Set(r);for(let n of t.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)e.has(a)&&i.add(a);if(t.loop.stage==="repairing"&&t.verification_result==="fail"){let n=[...t.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:t.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function fb(t){let e=ua(t,"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(e)){let a=ua(n,`Native children acceptance_index.${i}`);if(la(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 pb(t,e,r){let i=r.requiredAcceptanceIds??e??[],n=r.allowedAcceptanceIds??i,a=Object.keys(t),o=i.filter(l=>!(l in t)),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 u=c.get(l);if(!u)continue;let d=t[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function _f(t,e,r={}){let i=(0,Qs.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ua(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==It&&a!==Tt)throw la(n,Sf,"Native children contract"),new Error(`Native children schema must be ${It} or ${Tt}`);let o=a===It?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(la(n,o==="indexed-v2"?sb:Sf,"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((f,h)=>{let g=ua(f,`Native child ${h}`);if(la(g,o==="indexed-v2"?ub:o==="summary-v2"?lb:cb,`Native ${s} child fields (child ${h})`),typeof g.name!="string"||!ob.test(g.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof g.summary!="string"||g.summary.trim().length===0)throw new Error(`Native child ${g.name} summary must be a non-empty string`);if(g.summary.length>2e3)throw new Error(`Native child ${g.name} summary exceeds 2000 characters`)}return{name:g.name,summary:p?g.summary:null,depends_on:Ef(g.depends_on,`Native child ${g.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Ef(g.covers,`Native child ${g.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(g=>!u.has(g));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}db(c);let d=r.policy==="advisory";if(a===Zs){if(o==="indexed-v2"){let f=fb(n.acceptance_index);d||pb(f,e,r);let h=Object.keys(f);return d||xf(c,h,h),{schema:Tt,acceptance_index:f,children:c}}return{schema:Tt,children:c}}return e&&!d&&xf(c,e),{schema:It,children:c}}async function da(t){let e=te.join(t.changeDir,Ks);try{await Xs.lstat(e)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await M({root:t.changeDir,ref:Ks}),i=t.policy==="advisory",n=i?{...t.validation,policy:"advisory"}:t.validation??{},a=_f(r.text,t.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Af(a,t.acceptanceIds,t.validation??{}):null}}function hb(t){let e=/^#\s+(?:Decisions|决策)\s*$/imu.exec(t);if(!e||e.index===void 0)return null;let r=t.slice(e.index+e[0].length);return r.split(/^#\s+/mu,1)[0]??r}function If(t){let e=hb(t);if(!e||!/Supervisor\s+Change/iu.test(e))return!1;let r=e.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=e.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function tc(t){try{let e=await M({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});return If(e.text)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function rc(t){return z("comet.native.parent-contract.v1",{acceptance:t.acceptance.map(({id:e,source:r,text:i})=>({id:e,source:r,text:i})),children:t.children})}async function Tf(t){let e=Kt(t.projectRoot);e.some(i=>Ys(i,t.projectRoot))||e.push(t.projectRoot);let r=[];for(let i of[...new Set(e.map(n=>te.resolve(n)))]){let n=await je(i);n&&r.push({projectRoot:i,paths:await xt(i,n.native.artifact_root),parent:Ys(i,t.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:t.projectRoot,paths:t,parent:!0}),r}async function jf(t){let e=await Tf(t.paths),r=[],i=[],n=new Map;for(let a of e){let o;try{o=await Xs.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===t.childName)continue;let c=te.join(a.paths.changesDir,s.name),l;try{l=await Me(te.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await da({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==It||u.contract.children.some(({name:d})=>d===t.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=t.targetBranch===null?[]:o.filter(({state:h})=>h.workspace.target_branch===t.targetBranch);if(t.targetBranch===null){i.push(`Native Supervisor Child ${t.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:h,state:g})=>Re(h.projectRoot).currentBranch===g.workspace.change_branch);if(!c){let h=o.find(({state:g})=>g.workspace.target_branch!==t.targetBranch);if(h)i.push(`Native Supervisor parent ${a} targets ${h.state.workspace.target_branch??"(missing)"}, not ${t.targetBranch}`);else{let g=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${g.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await vi({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let h=f.children.filter(({status:g})=>g!=="done").map(({name:g,status:p,message:v})=>`${g}=${p}${v?` (${v})`:""}`).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 ${t.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${t.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 ${t.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function mb(t,e){let r=te.join(t.paths.changesDir,e,"comet-state.yaml");try{return await Me(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function vb(t,e){let r;try{r=await Xs.readdir(t.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()||![...e].some(o=>n.name.endsWith(`-${o}`))))try{let o=te.join(t.paths.archiveDir,n.name,"comet-state.yaml"),s=await Me(o);e.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function gb(t,e,r){let i=te.relative(t.projectRoot,e);if(!i||i===".."||i.startsWith(`..${te.sep}`))return null;let n=i.split(te.sep).join("/");try{let a=(0,Qs.parseDocument)(pi(t.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:be(a.toJS({mapAsMap:!1}))}catch{return null}}function wb(t,e,r){return t.workspace.isolation!=="worktree"||t.workspace.target_branch!==r||t.workspace.finish!==null&&t.workspace.finish!=="merge"?{kind:"blocked",phase:t.phase,projectRoot:e.projectRoot,message:`Native child ${t.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:t.status==="blocked"||t.status==="await-user"?{kind:"blocked",phase:t.phase,projectRoot:e.projectRoot,message:t.blockers[0]?.reason.text??`Native child ${t.name} requires user resolution`}:{kind:"active",phase:t.phase,projectRoot:e.projectRoot,message:null}}function Rf(t,e){return t.status==="done"&&t.archived&&t.workspace.finish==="merge"&&t.workspace.target_branch===e}async function vi(t){let e=te.join(t.paths.changesDir,t.state.name),r=await tc(e),i=null,n;try{n=await da({changeDir:e,validation:ec(t.state),...t.state.acceptance.length>0?{acceptanceIds:t.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"})}catch(m){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${m.message}`,n=null}if(!n){let m=await sa(t.paths,t.state.name,{diagnostics:!0});if(m){let b=Gs(m);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(N=>({...N,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return t.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:t.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:t.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=rc({acceptance:t.state.acceptance,children:n.contract}),o=t.state.workspace.change_branch,s=t.state.phase!=="shape"&&t.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Tt){let m=await sa(t.paths,t.state.name,{diagnostics:!0});if(!m){let y=t.state.workspace.change_branch??t.state.workspace.target_branch;if(y){let x=await Js({paths:t.paths,parent:t.state.name,targetBranch:y,contract:n.contract});x&&(m=x,await zs(t.paths,x))}}if(m){let y=Gs(m);return t.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let b=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==y.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await Tf(t.paths),l=new Set(n.contract.children.map(({name:m})=>m)),u=new Map,d=new Map;for(let m of c){let b=m.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await vb(m,l)){let y={...N,source:m,committedState:gb(m,N.file,b)};u.set(N.state.name,[...u.get(N.state.name)??[],y])}for(let N of l){let y=await mb(m,N);y&&d.set(N,[...d.get(N)??[],{source:m,state:y}])}}let f=new Map;for(let m of n.contract.children){let b=(u.get(m.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===m.name&&Rf(w,o));if(b){f.set(m.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let N=u.get(m.name)?.[0];if(N){f.set(m.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=d.get(m.name)??[];y.length>1?f.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):y[0]&&f.set(m.name,wb(y[0].state,y[0].source,o))}let h=new Map(n.contract.children.map(m=>[m.name,m])),g=new Map,p=m=>{let b=g.get(m);if(b)return b;let N=h.get(m),x=N.depends_on.map(p).every(({status:he})=>he==="done"),w=f.get(m),P=w?.kind==="active"&&x?N.depends_on.filter(he=>!(u.get(he)??[]).some(({source:O,committedState:hr})=>Ys(O.projectRoot,w.projectRoot)&&hr?.name===he&&Rf(hr,o))):[],S,A=w?.message??null;w?.kind==="done"?(S=x?"done":"blocked",x||(A=`Native child ${m} was merged before its dependencies`)):w?.kind==="active"?(S=x&&P.length===0?"active":"blocked",x?P.length>0&&(A=`Native child ${m} does not include merged dependencies: ${P.join(", ")}`):A=`Native child ${m} started before its dependencies merged`):w?.kind==="blocked"?S="blocked":(S=s&&x?"ready":"pending",s||(A="Parent Shape confirmation is required"));let G={name:m,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:S,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:A};return g.set(m,G),G},v=n.contract.children.map(({name:m})=>p(m));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:v.every(({status:m})=>m==="done")}}var Qs,Ks,It,Tt,Zs,ob,Sf,sb,cb,lb,ub,ca=E(()=>{"use strict";Qs=mr(Gt(),1);Ze();hi();ae();Z();ye();$();Pt();Us();Ks="children.yaml",It="comet.native.children.v1",Tt="comet.native.children.v2",Zs=Tt,ob=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Sf=new Set(["schema","children"]),sb=new Set(["schema","acceptance_index","children"]),cb=new Set(["name","depends_on","covers"]),lb=new Set(["name","summary","depends_on"]),ub=new Set(["name","depends_on","covers"])});var Of,fr=E(()=>{"use strict";Z();si();Of=1024*1024});var fa=E(()=>{"use strict";Z();dt();Kr();fr()});var Qf,Lb,Bb,Vb,BT,Mb,VT,ac=E(()=>{"use strict";Z();Qf="scoped-text-safety",Lb=1,Bb=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Vb="comet.native.checker-policy.v1",BT=z(Vb,{policy:Qf,version:Lb,limits:Bb,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Mb=["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"],VT=new Set(Mb)});var pa=E(()=>{"use strict";Z();ac();dt()});var qb,ij,pr=E(()=>{"use strict";D();$();Ae();fr();fa();pa();qb=Of,ij=3*qb});J();ae();ca();ae();Bn();Z();var u_={maxAcceptanceCriteria:Ed.maxCriteria};var jt={maxSpecs:64,maxFileBytes:Nn,maxTotalBytes:4*1024*1024};import{promises as qf}from"fs";import Wf from"path";Nt();J();ae();xe();$();var yb=["outcome","scope","nonGoals","acceptanceExamples"],k_=[...yb,"constraints","decisions","openQuestions","verificationExpectations"];ae();J();D();J();xe();$();Ee();Kr();dt();var T_={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};le();ci();D();J();xe();ni();le();$();Ee();dt();Z();Z();fa();fr();xe();var Df={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:[]},bb=ee("comet-native-runtime:v3:scope-reopen"),oI=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];lr();xe();lr();xe();Ts();Wn();var Mf=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],BI=new Set(Mf),Cb=new Set([...Mf,"minimum_runtime_version","revision"]),VI=new Set([...Cb,"operation"]),MI=512*1024,Pb=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),FI=new Set([...Pb,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);lr();J();xe();le();Ee();dt();$();var zf=jt.maxSpecs*4;async function Rb(t,e){let r=Wf.join(fe(t,e),"specs"),i;try{i=await Ps({root:t.nativeRoot,directory:r,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await qf.opendir(r);try{for await(let s of o){if(a+=1,a>zf)throw new Error(`Native proposed specs directory exceeds ${zf} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;fi(s.name);let c=Wf.join(r,s.name,"spec.md");await V(t.nativeRoot,c);let l;try{l=await qf.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>jt.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await i.verify(),n.sort()}async function Uf(t,e){let r=fe(t,e),i={},n=0;for(let a of await Rb(t,e)){let o=await M({root:r,ref:`specs/${a}/spec.md`,maxBytes:jt.maxFileBytes});if(n+=o.size,n>jt.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");i[a]=o.text}return i}ai();function pe(t,e,r){return t.language==="zh-CN"?r:e}function Ab(t,e){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(t.phase==="shape"&&t.status==="await-user"&&t.loop.next_action==="confirm-shape")return t.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(e&&t.phase==="shape"&&t.status==="active")return{required:!0,message:pe(t,"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:pe(t,"Reply A or B","回复 A 或 B"),agentInstruction:pe(t,"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(t.phase==="verify"&&t.status==="active"&&t.loop.stage==="verify-ready"&&t.loop.next_action!=="await-verifier-result")return r(pe(t,"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(t.phase==="verify"&&t.status==="active"&&t.loop.next_action==="await-verifier-result")return r(pe(t,"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(t.status==="blocked"&&t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return t.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(t.phase==="verify"&&t.status==="await-user"&&t.verification?.assurance==="semantic-verification-unavailable")return t.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(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="resolve-verifier-blocker")return t.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(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="await-user"){let n=(t.loop.stop_reason??(t.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 t.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 t.phase==="verify"&&t.status==="await-user"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{required:!0,message:pe(t,"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:pe(t,"Accept the result","接受结果"),agentInstruction:pe(t,"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(pe(t,"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 _b(t){let e=t.workspace.change_branch??"<change-branch>",r=t.workspace.target_branch??"<target-branch>";return t.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${e},目标分支为 ${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 ${e} 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 Ib(t){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:t.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",t.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:pe(t,a[1],a[0])})),{name:"defer-archive",stateVersion:t.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:pe(t,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Yf(t){return["comet","native","next",t.change,"--summary","<summary>",t.flag,"--expected-state-version",String(t.stateVersion),"--expected-action",t.action]}function Ot(t,e){return{name:t,flag:e,valueKind:"text",required:!0,template:null}}function Tb(t,e){return{name:t,flag:e,valueKind:"confirmation",required:!0,template:null}}function Kf(t,e,r){return{name:t,flag:e,valueKind:"choice",required:!0,template:null,choices:[...r]}}function jb(t){return t?.coordinationChoiceRequired===!0||t?.schema==="comet.native.children.v2"&&t.children.length>=2}function $b(t){return["comet","native","next",t.change,"--summary","<summary>",...t.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(t.stateVersion),"--expected-action","prepare-shape-confirmation"]}function ft(t){return{name:t.name,stateVersion:t.stateVersion,expectedAction:t.expectedAction,commandArgs:Yf({change:t.change,stateVersion:t.stateVersion,action:t.expectedAction,flag:t.flag}),requiredInputs:["summary",t.confirmationInput],inputOptions:[Ot("summary","--summary"),Tb(t.name,t.flag)]}}function nc(t){return[ft({name:"revise-implementation",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),ft({name:"revise-requirements",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Xf(t,e,r={}){let i=jb(e)&&t.coordination_mode===void 0,n=Ab(t,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(t.status==="await-user")return t.phase==="shape"&&t.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"confirm-shape",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"accept-result",change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...nc({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"retry-verifier",change:t.name,stateVersion:t.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),ft({name:"confirm-verifier-unavailable",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:[ft({name:"resolve-verifier-blocker",change:t.name,stateVersion:t.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...nc({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ot("summary","--summary")],commandAlternatives:nc({change:t.name,stateVersion:t.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(t.status==="blocked"){let s=t.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Yf({change:t.name,stateVersion:t.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(t.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:$b({change:t.name,stateVersion:t.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Kf("coordination-mode","--coordination-mode",xd)]:[]],runnerAction:o("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(e.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",t.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=e.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.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=e.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=e.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>",...t.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[Ot("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.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(t.phase==="verify"){let s=t.loop.next_action==="await-verifier-result",c=!!t.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} ${pe(t,"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",t.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:t.loop.iteration,attempt:t.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.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:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(t.phase==="archive"&&t.status==="active"&&t.loop.stage==="archive-ready"&&!t.archived){let s=r.archiveMode??"archive-ready",l=t.workspace.isolation!=="current"&&t.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",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Kf("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Ib(t)],userCommunication:_b(t),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--dry-run"],requiredInputs:[],commandAlternatives:[ft({name:"revise-requirements",change:t.name,stateVersion:t.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}Ze();D();import{promises as zb}from"node:fs";import Zf from"node:path";ae();Z();ca();Us();J();Fs();Pt();qn();mi();aa();D();ai();le();gs();Pt();xs();qn();mi();aa();D();Nt();mi();$();Nt();pr();ye();var Jb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Gb="comet-state.yaml";var u$=Sn("en");function oc(t,e){if(!Jb.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=Zf.join(t.changesDir,e);if(!U(t.changesDir,r))throw new Error("Native change path escaped");return r}function ep(t,e){return Zf.join(oc(t,e),Gb)}async function sc(t,e){try{let r=await zb.readFile(ep(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function cc(t,e){return Me(ep(t,e))}ti();import wi from"path";import{realpathSync as Sk}from"fs";Ze();var Fe={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function tp(t){return t?t.command?`${Fe.next} ${t.command}`:t.ask_user?`${Fe.next} ${t.ask_user}`:null:null}function rp(t,e){let r=[t.summary],i=tp(t.next);return i&&r.push(i),t.user_message&&r.push("",Fe.relay,t.user_message),e!==void 0&&r.push("",Fe.details,JSON.stringify(e,null,2)),`${r.join(`
149
149
  `)}
150
150
  `}function ip(t,e,r){let i=[t.summary],n=tp(t.next);return n&&i.push(n),t.user_message&&i.push("",Fe.relay,t.user_message),i.push("",`${Fe.detail} ${e}`),r!==void 0&&i.push("",Fe.details,JSON.stringify(r,null,2)),i.join(`
151
- `)}lr();Z();ae();J();Z();var Ub=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});pr();Se();ta();J();we();$();Bn();ae();J();pr();si();fr();fa();import{execFile as rk}from"node:child_process";na();Ms();J();import{promisify as ik}from"node:util";D();ac();$();Re();var B$=512*1024;pr();le();dt();var gi=class extends Error{recovery;constructor(e,r){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=r}};si();pa();fr();var cO=64*1024;var lO=3600*1e3;var uO=ik(rk);pa();var ha=class extends Error{details;constructor(e){let r=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=e}};ta();Ee();Se();var UO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};D();Re();$();Se();Xn();var a0=16*1024*1024,o0=256*1024,s0=16*1024;J();D();Nt();J();pr();var p0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ee();ni();le();$();Se();ti();var v0=16*1024;J();we();le();var R0=16*1024;Xn();var wH=16*1024*1024,ma=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"},va=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"};J();$();we();function C(t,e,r){return t==="zh-CN"?r:e}var lc={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function ap(t,e){return typeof t=="string"&&lc[t]?C(e,lc[t].en,lc[t].zh):typeof t=="string"?t:""}function uc(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&typeof e.passed=="number"&&typeof e.failed=="number"&&typeof e.blocked=="number"&&typeof e.pending=="number"}function lk(t){let e={total:t.length,passed:0,failed:0,blocked:0,pending:0};for(let r of t){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;e[i]+=1}return e}function op(t,e){let r=[];t.failed>0&&r.push(C(e,`${t.failed} failed`,`${t.failed} 项失败`)),t.blocked>0&&r.push(C(e,`${t.blocked} blocked`,`${t.blocked} 项受阻`)),t.pending>0&&r.push(C(e,`${t.pending} pending`,`${t.pending} 项待验`));let i=C(e,`acceptance ${t.passed}/${t.total} passed`,`验收 ${t.passed}/${t.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function sp(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;if(typeof e.change!="string"||e.disposition!=="continue"&&e.disposition!=="await-user"&&e.disposition!=="blocked"&&e.disposition!=="done"||e.commandArgs!==null&&e.commandArgs!==void 0&&!Array.isArray(e.commandArgs))return!1;let r=e.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function dc(t){return/[\u4e00-\u9fff]/u.test(t.userCommunication.agentInstruction)?"zh-CN":"en"}function uk(t,e,r){return t==="done"?C(r,"complete","已完成"):t==="await-user"?C(r,"waiting for a user decision","等待用户决定"):t==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):e?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function dk(t,e,r){let i=dc(t),n=[];r&&n.push(r);let a=C(i,`Change ${t.change}`,`需求 ${t.change}`),o=ap(t.phase,i),s=uk(t.disposition,t.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),e&&e.total>0&&n.push(op(e,i));let c=t.userCommunication,l=cp(t,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function cp(t,e){let r=t.userCommunication;if(t.disposition==="await-user"&&r.required)return{ask_user:C(e,"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(t.commandArgs&&t.commandArgs.length>0)return{command:t.commandArgs.join(" ")};if(t.disposition==="done")return{ask_user:C(e,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(t.disposition==="blocked")return{ask_user:C(e,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function fk(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&Array.isArray(e.items)}function pk(t,e){let r=typeof t.name=="string"?t.name:"(unnamed)",i=ap(t.phase,e),n=t.status==="await-user"?C(e,"waiting for a user decision","等待用户决定"):t.status==="blocked"?C(e,"paused","已暂停"):t.status==="done"?C(e,"complete","已完成"):C(e,"in progress","进行中"),a=uc(t.acceptance)?`${C(e,", ",",")}${op(t.acceptance,e)}`:"";return` ${r} · ${i||String(t.phase??"?")} · ${n}${a}`}function hk(t){for(let e of t){let r=e.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function mk(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.healthy!="boolean"?!1:e.findings===void 0||Array.isArray(e.findings)}function vk(t){if(t.healthy){let i=t.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=gk(t.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(t.findings)?t.findings.length:0;return{summary:C("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:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function gk(t){return sp(t)?cp(t,dc(t)):void 0}function lp(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(mk(e))return vk(e);if(fk(e)){let i=hk(e.items);return{summary:[e.total===e.items.length?C(i,`Native changes (${e.total})`,`Native 需求列表(共 ${e.total} 条)`):C(i,`Native changes (showing ${e.items.length} of ${e.total})`,`Native 需求列表(显示 ${e.items.length}/${e.total} 条)`),...e.items.map(a=>pk(a,i))].join(`
152
- `)}}let r=e.continuation;if(sp(r))return dk(r,wk(e),yk(e,dc(r)));if(typeof e.artifactRoot=="string"&&typeof e.nativeRoot=="string"){let i=e.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in e;return{summary:C(i,n?`Comet Native artifacts live under ${e.artifactRoot} (state root: ${e.nativeRoot}).`:`Initialized Comet Native at ${e.nativeRoot} (artifacts: ${e.artifactRoot}).`,n?`Comet Native 产物位于 ${e.artifactRoot}(状态根目录:${e.nativeRoot})。`:`Comet Native 已初始化于 ${e.nativeRoot}(产物目录:${e.artifactRoot})。`)}}}function wk(t){if(uc(t.acceptance))return t.acceptance;let e=t.state;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(uc(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return lk(r.acceptance)}return null}function yk(t,e){if(t.selected!==void 0&&typeof t.selected=="string")return C(e,`Selected ${t.selected}.`,`已选择需求 ${t.selected}。`);let r=t.migration;return r&&typeof r=="object"&&r.completed===!0?C(e,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function up(t){let r=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:{};switch(t.code){case"conflict":return{summary:C("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:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}qs();var dp=["--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."],pc=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:dp,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>
153
- 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>]
151
+ `)}lr();Z();ae();J();Z();var Ub=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});pr();Ee();ta();J();ye();$();Bn();ae();J();pr();si();fr();fa();import{execFile as rk}from"node:child_process";na();Ms();J();import{promisify as ik}from"node:util";D();ac();$();Ae();var B$=512*1024;pr();le();dt();var gi=class extends Error{recovery;constructor(e,r){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=r}};si();pa();fr();var cO=64*1024;var lO=3600*1e3;var uO=ik(rk);pa();var ha=class extends Error{details;constructor(e){let r=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=e}};ta();xe();Ee();var UO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};D();Ae();$();Ee();Xn();var a0=16*1024*1024,o0=256*1024,s0=16*1024;J();D();Nt();J();pr();var p0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});xe();ni();le();$();Ee();ti();var v0=16*1024;J();ye();le();var R0=16*1024;Xn();var wH=16*1024*1024,ma=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"},va=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"};J();$();ye();function C(t,e,r){return t==="zh-CN"?r:e}var lc={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function ap(t,e){return typeof t=="string"&&lc[t]?C(e,lc[t].en,lc[t].zh):typeof t=="string"?t:""}function uc(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&typeof e.passed=="number"&&typeof e.failed=="number"&&typeof e.blocked=="number"&&typeof e.pending=="number"}function lk(t){let e={total:t.length,passed:0,failed:0,blocked:0,pending:0};for(let r of t){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;e[i]+=1}return e}function op(t,e){let r=[];t.failed>0&&r.push(C(e,`${t.failed} failed`,`${t.failed} 项失败`)),t.blocked>0&&r.push(C(e,`${t.blocked} blocked`,`${t.blocked} 项受阻`)),t.pending>0&&r.push(C(e,`${t.pending} pending`,`${t.pending} 项待验`));let i=C(e,`acceptance ${t.passed}/${t.total} passed`,`验收 ${t.passed}/${t.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function sp(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;if(typeof e.change!="string"||e.disposition!=="continue"&&e.disposition!=="await-user"&&e.disposition!=="blocked"&&e.disposition!=="done"||e.commandArgs!==null&&e.commandArgs!==void 0&&!Array.isArray(e.commandArgs))return!1;let r=e.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function dc(t){return/[\u4e00-\u9fff]/u.test(t.userCommunication.agentInstruction)?"zh-CN":"en"}function uk(t,e,r){return t==="done"?C(r,"complete","已完成"):t==="await-user"?C(r,"waiting for a user decision","等待用户决定"):t==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):e?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function dk(t,e,r){let i=dc(t),n=[];r&&n.push(r);let a=C(i,`Change ${t.change}`,`需求 ${t.change}`),o=ap(t.phase,i),s=uk(t.disposition,t.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),e&&e.total>0&&n.push(op(e,i));let c=t.userCommunication,l=cp(t,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function cp(t,e){let r=t.userCommunication;if(t.disposition==="await-user"&&r.required)return{ask_user:C(e,"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(t.commandArgs&&t.commandArgs.length>0)return{command:t.commandArgs.join(" ")};if(t.disposition==="done")return{ask_user:C(e,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(t.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(e,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function fk(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&Array.isArray(e.items)}function pk(t,e){let r=typeof t.name=="string"?t.name:"(unnamed)",i=ap(t.phase,e),n=t.status==="await-user"?C(e,"waiting for a user decision","等待用户决定"):t.status==="blocked"?C(e,"paused","已暂停"):t.status==="done"?C(e,"complete","已完成"):C(e,"in progress","进行中"),a=uc(t.acceptance)?`${C(e,", ",",")}${op(t.acceptance,e)}`:"";return` ${r} · ${i||String(t.phase??"?")} · ${n}${a}`}function hk(t){for(let e of t){let r=e.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function mk(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.healthy!="boolean"?!1:e.findings===void 0||Array.isArray(e.findings)}function vk(t){if(t.healthy){let i=t.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=gk(t.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(t.findings)?t.findings.length:0;return{summary:C("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:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function gk(t){return sp(t)?cp(t,dc(t)):void 0}function lp(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(mk(e))return vk(e);if(fk(e)){let i=hk(e.items);return{summary:[e.total===e.items.length?C(i,`Native changes (${e.total})`,`Native 需求列表(共 ${e.total} 条)`):C(i,`Native changes (showing ${e.items.length} of ${e.total})`,`Native 需求列表(显示 ${e.items.length}/${e.total} 条)`),...e.items.map(a=>pk(a,i))].join(`
152
+ `)}}let r=e.continuation;if(sp(r))return dk(r,wk(e),yk(e,dc(r)));if(typeof e.artifactRoot=="string"&&typeof e.nativeRoot=="string"){let i=e.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in e;return{summary:C(i,n?`Comet Native artifacts live under ${e.artifactRoot} (state root: ${e.nativeRoot}).`:`Initialized Comet Native at ${e.nativeRoot} (artifacts: ${e.artifactRoot}).`,n?`Comet Native 产物位于 ${e.artifactRoot}(状态根目录:${e.nativeRoot})。`:`Comet Native 已初始化于 ${e.nativeRoot}(产物目录:${e.artifactRoot})。`)}}}function wk(t){if(uc(t.acceptance))return t.acceptance;let e=t.state;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(uc(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return lk(r.acceptance)}return null}function yk(t,e){if(t.selected!==void 0&&typeof t.selected=="string")return C(e,`Selected ${t.selected}.`,`已选择需求 ${t.selected}。`);let r=t.migration;return r&&typeof r=="object"&&r.completed===!0?C(e,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function up(t){let r=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:{};switch(t.code){case"conflict":return{summary:C("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:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}qs();var dp=["--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."],pc=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:dp,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>
153
+ 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>]
154
154
  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>]
155
155
  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]
156
156
  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 fc(t,e){return`${t}:
@@ -158,7 +158,7 @@ ${e.map(r=>` ${r}`).join(`
158
158
  `)}`}function Nk(t){let e=t.filter(i=>i!=="--help");if(e.length===0)return"";let r=e.slice(0,2).join(" ");return pc[r]||e.length>1&&pc[e[0]]?.subcommands?r:e[0]}function bk(t=[]){let e=Nk(t),r=pc[e];if(!r)throw new Error(`Unknown Native help topic: ${e}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",fc("Commands",r.subcommands));let n=e===""?r.options:[...r.options??[],...dp];return n&&n.length>0&&i.push("",fc("Options",n)),i.push("",`Output:
159
159
  ${r.output}`),r.examples&&i.push("",fc("Examples",r.examples)),e===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${i.join(`
160
160
  `)}
161
- `}}var kk=bk().usage;var pp=10*1024*1024,pt=class extends Error{};function mc(t,e){let r=t.flatMap((i,n)=>i===e?[n]:[]);if(r.length>1)throw new pt(`${e} may only be provided once`);return r.length===0?!1:(t.splice(r[0],1),!0)}function hp(t,e){let r=t.flatMap((a,o)=>a===e?[o]:[]);if(r.length>1)throw new pt(`${e} may only be provided once`);if(r.length===0)return;let i=r[0],n=t[i+1];if(n===void 0||n.startsWith("--"))throw new pt(`${e} requires a value`);return t.splice(i,2),n}function mp(t){if(t.length>0)throw new pt(`Unexpected argument: ${t[0]}`)}function vp(t,e){let r=t.shift();if(!r||r.startsWith("--"))throw new pt(`${e} is required`);return r}function hc(t,e){let r=wi.normalize(fp(t)),i=wi.normalize(fp(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function fp(t){let e=wi.resolve(t);try{return Sk.native(e)}catch{return e}}function Ek(t){let e=wi.resolve(t),r=Pe(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return e;let i=Pe(e);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!hc(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||hc(r.currentWorktreeRoot,i.currentWorktreeRoot)?e:hc(process.cwd(),r.currentWorktreeRoot)?wi.resolve(process.cwd()):r.currentWorktreeRoot}async function gp(t){return t?Ek(t):Hn(process.cwd())}async function wp(t){let e=await Sd({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function yp(t){return JSON.stringify(t,null,2)+`
161
+ `}}var kk=bk().usage;var pp=10*1024*1024,pt=class extends Error{};function mc(t,e){let r=t.flatMap((i,n)=>i===e?[n]:[]);if(r.length>1)throw new pt(`${e} may only be provided once`);return r.length===0?!1:(t.splice(r[0],1),!0)}function hp(t,e){let r=t.flatMap((a,o)=>a===e?[o]:[]);if(r.length>1)throw new pt(`${e} may only be provided once`);if(r.length===0)return;let i=r[0],n=t[i+1];if(n===void 0||n.startsWith("--"))throw new pt(`${e} requires a value`);return t.splice(i,2),n}function mp(t){if(t.length>0)throw new pt(`Unexpected argument: ${t[0]}`)}function vp(t,e){let r=t.shift();if(!r||r.startsWith("--"))throw new pt(`${e} is required`);return r}function hc(t,e){let r=wi.normalize(fp(t)),i=wi.normalize(fp(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function fp(t){let e=wi.resolve(t);try{return Sk.native(e)}catch{return e}}function Ek(t){let e=wi.resolve(t),r=Re(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return e;let i=Re(e);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!hc(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||hc(r.currentWorktreeRoot,i.currentWorktreeRoot)?e:hc(process.cwd(),r.currentWorktreeRoot)?wi.resolve(process.cwd()):r.currentWorktreeRoot}async function gp(t){return t?Ek(t):Hn(process.cwd())}async function wp(t){let e=await Sd({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function yp(t){return JSON.stringify(t,null,2)+`
162
162
  `}function ga(t,e,r){return{command:t,exitCode:0,data:e,text:r??yp(e)}}function xk(t,e){if(e instanceof pt)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof ma)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof va)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof ra)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof li)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof oa)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof ia)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.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:e.message}};if(e instanceof ha)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof gi)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let r=e.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Np(t,e){let r=xk(t,e),i=r.error;if(!i)return r;let n=up({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function bp(t,e,r=!1){let i=t.envelope??lp(t.data);return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
163
163
  `}:t.error?{exitCode:t.exitCode,stderr:i?ip(i,t.error.message,r?t.data:void 0):t.error.message}:i?{exitCode:t.exitCode,stdout:rp(i,r?t.data:void 0)}:r&&t.text!==void 0&&t.data!==void 0&&t.text!==yp(t.data)?{exitCode:t.exitCode,stdout:`${t.text}
164
164
  ${Fe.details}